text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { createSelector } from 'reselect' import last from 'lodash/last' import uniq from 'lodash/uniq' import { selectors as stepFormSelectors } from '../../step-forms' import { getDefaultsForStepType } from '../../steplist/formLevel/getDefaultsForStepType' import { SubstepIdentifier, TerminalItemId, PRESAVED_STEP_ID, } from '../../steplist/types' import { getLabwareOnModule } from '../modules/utils' import { SelectableItem, StepsState, CollapsedStepsState, HoverableItem, initialSelectedItemState, SINGLE_STEP_SELECTION_TYPE, TERMINAL_ITEM_SELECTION_TYPE, MULTI_STEP_SELECTION_TYPE, } from './reducers' import { getAspirateLabwareDisabledFields, getDispenseLabwareDisabledFields, getMultiAspiratePathDisabledFields, getMultiDispensePathDisabledFields, getPipetteDifferentAndMultiAspiratePathFields, getPipetteDifferentAndMultiDispensePathFields, getPipetteDifferentDisabledFields, getLabwareDisabledFields, } from './utils' import { CountPerStepType, FormData, StepFieldName, StepIdType, StepType, } from '../../form-types' import { BaseState, Selector } from '../../types' export const rootSelector = (state: BaseState): StepsState => state.ui.steps // ======= Selectors =============================================== // NOTE: when the selected step is deleted, we need to fall back to the last step // (or the initial selected item, if there are no more saved steps). // Ideally this would happen in the selectedItem reducer itself, // but it's not easy to feed orderedStepIds into that reducer. // @ts-expect-error(sa, 2021-6-15): lodash/last might return undefined, change line 55 to pull out the last element directly const getSelectedItem: Selector<SelectableItem> = createSelector( rootSelector, stepFormSelectors.getOrderedStepIds, (state, orderedStepIds) => { if (state.selectedItem != null) return state.selectedItem if (orderedStepIds.length > 0) return { selectionType: SINGLE_STEP_SELECTION_TYPE, id: last(orderedStepIds), } return initialSelectedItemState } ) export const getSelectedStepId: Selector<StepIdType | null> = createSelector( getSelectedItem, item => (item.selectionType === SINGLE_STEP_SELECTION_TYPE ? item.id : null) ) export const getSelectedTerminalItemId: Selector<TerminalItemId | null> = createSelector( getSelectedItem, item => (item.selectionType === TERMINAL_ITEM_SELECTION_TYPE ? item.id : null) ) export const getIsMultiSelectMode: Selector<boolean> = createSelector( getSelectedItem, item => { return item.selectionType === MULTI_STEP_SELECTION_TYPE } ) export const getMultiSelectItemIds: Selector< StepIdType[] | null > = createSelector(getSelectedItem, item => { if (item && item.selectionType === MULTI_STEP_SELECTION_TYPE) { return item.ids } return null }) export const getMultiSelectLastSelected: Selector<StepIdType | null> = createSelector( getSelectedItem, item => { if (item.selectionType === MULTI_STEP_SELECTION_TYPE) { return item.lastSelected } return null } ) export const getHoveredItem: Selector<HoverableItem | null> = createSelector( rootSelector, (state: StepsState) => state.hoveredItem ) export const getHoveredStepId: Selector<StepIdType | null> = createSelector( getHoveredItem, item => item && item.selectionType === SINGLE_STEP_SELECTION_TYPE ? item.id : null ) /** Array of labware (labwareId's) involved in hovered Step, or [] */ export const getHoveredStepLabware: Selector<string[]> = createSelector( stepFormSelectors.getArgsAndErrorsByStepId, getHoveredStepId, stepFormSelectors.getInitialDeckSetup, (allStepArgsAndErrors, hoveredStep, initialDeckState) => { const blank: string[] = [] if (!hoveredStep || !allStepArgsAndErrors[hoveredStep]) { return blank } const stepArgs = allStepArgsAndErrors[hoveredStep].stepArgs if (!stepArgs) { return blank } if ( stepArgs.commandCreatorFnName === 'consolidate' || stepArgs.commandCreatorFnName === 'distribute' || stepArgs.commandCreatorFnName === 'transfer' ) { // source and dest labware const src = stepArgs.sourceLabware const dest = stepArgs.destLabware return [src, dest] } if (stepArgs.commandCreatorFnName === 'mix') { // only 1 labware return [stepArgs.labware] } // @ts-expect-error(sa, 2021-6-15): type narrow stepArgs.module if (stepArgs.module) { // @ts-expect-error(sa, 2021-6-15): this expect error should not be necessary after type narrowing above const labware = getLabwareOnModule(initialDeckState, stepArgs.module) return labware ? [labware.id] : [] } // step types that have no labware that gets highlighted if (!(stepArgs.commandCreatorFnName === 'delay')) { // TODO Ian 2018-05-08 use assert here console.warn( `getHoveredStepLabware does not support step type "${stepArgs.commandCreatorFnName}"` ) } return blank } ) export const getHoveredTerminalItemId: Selector<TerminalItemId | null> = createSelector( getHoveredItem, item => item && item.selectionType === TERMINAL_ITEM_SELECTION_TYPE ? item.id : null ) export const getHoveredSubstep: Selector<SubstepIdentifier> = createSelector( rootSelector, (state: StepsState) => state.hoveredSubstep ) // Hovered or selected item. Hovered has priority. Used to tell deck what to display export const getActiveItem: Selector<HoverableItem | null> = createSelector( getSelectedItem, getHoveredItem, (selected, hovered) => { if (hovered != null) { return hovered } else if (selected.selectionType === MULTI_STEP_SELECTION_TYPE) { return null } else { return selected } } ) // TODO: BC 2018-12-17 refactor as react state export const getCollapsedSteps: Selector<CollapsedStepsState> = createSelector( rootSelector, (state: StepsState) => state.collapsedSteps ) interface StepTitleInfo { stepName: string stepType: StepType } const _stepToTitleInfo = (stepForm: FormData): StepTitleInfo => ({ stepName: stepForm.stepName, stepType: stepForm.stepType, }) export const getSelectedStepTitleInfo: Selector<StepTitleInfo | null> = createSelector( stepFormSelectors.getUnsavedForm, stepFormSelectors.getSavedStepForms, getSelectedStepId, getSelectedTerminalItemId, (unsavedForm, savedStepForms, selectedStepId, terminalItemId) => { if (unsavedForm != null && terminalItemId === PRESAVED_STEP_ID) { return _stepToTitleInfo(unsavedForm) } if (selectedStepId == null) { return null } return _stepToTitleInfo(savedStepForms[selectedStepId]) } ) export const getWellSelectionLabwareKey: Selector< string | null > = createSelector( rootSelector, (state: StepsState) => state.wellSelectionLabwareKey ) export type MultiselectFieldValues = Record< StepFieldName, { value?: any isIndeterminate: boolean } > export const _getSavedMultiSelectFieldValues: Selector<MultiselectFieldValues | null> = createSelector( stepFormSelectors.getSavedStepForms, getMultiSelectItemIds, (savedStepForms, multiSelectItemIds) => { if (!multiSelectItemIds) return null const forms = multiSelectItemIds.map(id => savedStepForms[id]) const stepTypes = uniq(forms.map(form => form.stepType)) if (stepTypes.length !== 1) { return null } const stepType: StepType = stepTypes[0] if (stepType !== 'moveLiquid' && stepType !== 'mix') { return null } const allFieldNames = Object.keys(getDefaultsForStepType(stepType)) return allFieldNames.reduce( (acc: MultiselectFieldValues, fieldName: StepFieldName) => { const firstFieldValue = forms[0][fieldName] const isFieldValueIndeterminant = forms.some( form => form[fieldName] !== firstFieldValue ) if (isFieldValueIndeterminant) { acc[fieldName] = { isIndeterminate: true, } return acc } else { acc[fieldName] = { value: firstFieldValue, isIndeterminate: false, } return acc } }, {} ) } ) export const getMultiSelectFieldValues: Selector<MultiselectFieldValues | null> = createSelector( _getSavedMultiSelectFieldValues, stepFormSelectors.getBatchEditFieldChanges, (savedValues, changes) => { if (savedValues === null) { // multi-selection has an invalid combination of stepTypes return null } const multiselectChanges = Object.keys( changes ).reduce<MultiselectFieldValues>((acc, name) => { acc[name] = { value: changes[name], isIndeterminate: false, } return acc }, {}) return { ...savedValues, ...multiselectChanges } } ) // NOTE: the value is the tooltip text explaining why the field is disabled type TooltipText = string export type DisabledFields = Record<string, TooltipText> export const getMultiSelectDisabledFields: Selector<DisabledFields | null> = createSelector( stepFormSelectors.getSavedStepForms, getMultiSelectItemIds, (savedStepForms, multiSelectItemIds) => { if (!multiSelectItemIds) return null const forms: FormData[] = multiSelectItemIds.map(id => savedStepForms[id]) if (forms.every(form => form.stepType === 'moveLiquid')) { return getMoveLiquidMultiSelectDisabledFields(forms) } else if (forms.every(form => form.stepType === 'mix')) { return getMixMultiSelectDisabledFields(forms) } else { return null } } ) export const getCountPerStepType: Selector<CountPerStepType> = createSelector( getMultiSelectItemIds, stepFormSelectors.getSavedStepForms, (stepIds, allSteps) => { if (stepIds === null) return {} const steps = stepIds.map(id => allSteps[id]) const countPerStepType = steps.reduce<CountPerStepType>((acc, step) => { const { stepType } = step // @ts-expect-error(sa, 2021-6-15): cannot type narrow this way in TS const newCount = acc[stepType] ? acc[stepType] + 1 : 1 acc[stepType] = newCount return acc }, {}) return countPerStepType } ) export const getBatchEditSelectedStepTypes: Selector< StepType[] > = createSelector(getCountPerStepType, countPerStepType => { return uniq( (Object.keys(countPerStepType) as StepType[]).filter( // @ts-expect-error(sa, 2021-6-15): TS thinks countPerStepType[stepType] might be undefined because CountPerStepType is a partial record stepType => countPerStepType[stepType] > 0 ) ).sort() }) function getMoveLiquidMultiSelectDisabledFields( forms: FormData[] ): DisabledFields { const { pipettesDifferent, aspirateLabwareDifferent, dispenseLabwareDifferent, includesMultiAspirate, includesMultiDispense, } = forms.reduce( (acc, form) => ({ lastPipette: form.pipette, lastAspirateLabware: form.aspirate_labware, lastDispenseLabware: form.dispense_labware, pipettesDifferent: form.pipette !== acc.lastPipette || acc.pipettesDifferent, aspirateLabwareDifferent: form.aspirate_labware !== acc.lastAspirateLabware || acc.aspirateLabwareDifferent, dispenseLabwareDifferent: form.dispense_labware !== acc.lastDispenseLabware || acc.dispenseLabwareDifferent, includesMultiAspirate: form.path === 'multiAspirate' || acc.includesMultiAspirate, includesMultiDispense: form.path === 'multiDispense' || acc.includesMultiDispense, }), { lastPipette: forms[0].pipette, lastAspirateLabware: forms[0].aspirate_labware, lastDispenseLabware: forms[0].dispense_labware, pipettesDifferent: false, aspirateLabwareDifferent: false, dispenseLabwareDifferent: false, includesMultiAspirate: false, includesMultiDispense: false, } ) const disabledFields: DisabledFields = { ...(pipettesDifferent && getPipetteDifferentDisabledFields('moveLiquid')), ...(aspirateLabwareDifferent && getAspirateLabwareDisabledFields()), ...(dispenseLabwareDifferent && getDispenseLabwareDisabledFields()), ...(includesMultiAspirate && getMultiAspiratePathDisabledFields()), ...(includesMultiDispense && getMultiDispensePathDisabledFields()), ...(includesMultiAspirate && pipettesDifferent && getPipetteDifferentAndMultiAspiratePathFields()), ...(includesMultiDispense && pipettesDifferent && getPipetteDifferentAndMultiDispensePathFields()), } return disabledFields } function getMixMultiSelectDisabledFields(forms: FormData[]): DisabledFields { const { pipettesDifferent, labwareDifferent } = forms.reduce( (acc, form) => ({ lastPipette: form.pipette, lastLabware: form.labware, pipettesDifferent: form.pipette !== acc.lastPipette || acc.pipettesDifferent, labwareDifferent: form.labware !== acc.lastLabware || acc.labwareDifferent, }), { lastPipette: forms[0].pipette, lastLabware: forms[0].labware, pipettesDifferent: false, labwareDifferent: false, } ) const disabledFields: DisabledFields = { ...(pipettesDifferent && getPipetteDifferentDisabledFields('mix')), ...(labwareDifferent && getLabwareDisabledFields()), } return disabledFields }
the_stack
import { mat3, mat4, quat, vec3, vec4 } from 'gl-matrix'; import { createVec3, getAngle } from '../../utils/math'; // import Landmark from './Landmark'; export enum CAMERA_TYPE { ORBITING = 'ORBITING', EXPLORING = 'EXPLORING', TRACKING = 'TRACKING', } export enum CAMERA_TRACKING_MODE { DEFAULT = 'DEFAULT', ROTATIONAL = 'ROTATIONAL', TRANSLATIONAL = 'TRANSLATIONAL', CINEMATIC = 'CINEMATIC', } const DEG_2_RAD = Math.PI / 180; const RAD_2_DEG = 180 / Math.PI; /** * 参考「WebGL Insights - 23.Designing Cameras for WebGL Applications」,基于 Responsible Camera 思路设计 * 保存相机参数,定义相机动作: * 1. dolly 沿 n 轴移动 * 2. pan 沿 u v 轴移动 * 3. rotate 以方位角旋转 * 4. 移动到 Landmark,具有平滑的动画效果,其间禁止其他用户交互 */ export default class Camera { /** * 相机矩阵 */ public matrix = mat4.create(); /** * u 轴 * @see http://learnwebgl.brown37.net/07_cameras/camera_introduction.html#a-camera-definition */ public right = vec3.fromValues(1, 0, 0); /** * v 轴 */ public up = vec3.fromValues(0, 1, 0); /** * n 轴 */ public forward = vec3.fromValues(0, 0, 1); /** * 相机位置 */ public position = vec3.fromValues(0, 0, 1); /** * 视点位置 */ public focalPoint = vec3.fromValues(0, 0, 0); /** * 相机位置到视点向量 * focalPoint - position */ public distanceVector = vec3.fromValues(0, 0, 0); /** * 相机位置到视点距离 * length(focalPoint - position) */ public distance = 1; /** * @see https://en.wikipedia.org/wiki/Azimuth */ public azimuth = 0; public elevation = 0; public roll = 0; public relAzimuth = 0; public relElevation = 0; public relRoll = 0; /** * 沿 n 轴移动时,保证移动速度从快到慢 */ public dollyingStep = 0; /** * invert the horizontal coordinate system HCS */ public rotateWorld = false; /** * 投影矩阵参数 */ /** * field of view [0-360] * @see http://en.wikipedia.org/wiki/Angle_of_view */ private fov = 30; private near = 0.1; private far = 10000; private aspect = 1; /** * 投影矩阵 */ private perspective = mat4.create(); private following = undefined; private type = CAMERA_TYPE.EXPLORING; private trackingMode = CAMERA_TRACKING_MODE.DEFAULT; constructor(type: CAMERA_TYPE) { this.setType(type, undefined); } public setType( type: CAMERA_TYPE, trackingMode: CAMERA_TRACKING_MODE | undefined, ) { this.type = type; if (this.type === CAMERA_TYPE.EXPLORING) { this.setWorldRotation(true); } else { this.setWorldRotation(false); } this._getAngles(); if (this.type === CAMERA_TYPE.TRACKING && trackingMode !== undefined) { this.setTrackingMode(trackingMode); } } public setTrackingMode(trackingMode: CAMERA_TRACKING_MODE) { if (this.type !== CAMERA_TYPE.TRACKING) { throw new Error( 'Impossible to set a tracking mode if the camera is not of tracking type', ); } this.trackingMode = trackingMode; } /** * If flag is true, it reverses the azimuth and elevation angles. * Subsequent calls to rotate, setAzimuth, setElevation, * changeAzimuth or changeElevation will cause the inverted effect. * setRoll or changeRoll is not affected by this method. * * This inversion is useful when one wants to simulate that the world * is moving, instead of the camera. * * By default the camera angles are not reversed. * @param {Boolean} flag the boolean flag to reverse the angles. */ public setWorldRotation(flag: boolean) { this.rotateWorld = flag; this._getAngles(); } /** * 计算 MV 矩阵,为相机矩阵的逆矩阵 */ public getViewTransform(): mat4 | null { return mat4.invert(mat4.create(), this.matrix); } /** * 设置相机矩阵 */ public setMatrix(matrix: mat4) { this.matrix = matrix; this._update(); } public setPerspective( near: number, far: number, angle: number, aspect: number, ) { this.fov = angle; this.near = near; this.far = far; this.aspect = aspect; this.updatePerspective(); } public updatePerspective() { mat4.perspective( this.perspective, this.fov * DEG_2_RAD, this.aspect, this.near, this.far, ); } /** * 设置相机位置 */ public setPosition(x: number, y: number, z: number) { this._setPosition(x, y, z); this.setFocalPoint(this.focalPoint); return this; } /** * 设置视点位置 */ public setFocalPoint(x: number | vec3, y?: number, z?: number) { let up = vec3.fromValues(0, 1, 0); this.focalPoint = createVec3(x, y, z); if (this.trackingMode === CAMERA_TRACKING_MODE.CINEMATIC) { const d = vec3.subtract(vec3.create(), this.focalPoint, this.position); x = d[0]; y = d[1] as number; z = d[2] as number; const r = vec3.length(d); const el = Math.asin(y / r) * RAD_2_DEG; const az = 90 + Math.atan2(z, x) * RAD_2_DEG; const m = mat4.create(); mat4.rotateY(m, m, az * DEG_2_RAD); mat4.rotateX(m, m, el * DEG_2_RAD); up = vec3.transformMat4(vec3.create(), [0, 1, 0], m); } mat4.invert( this.matrix, mat4.lookAt(mat4.create(), this.position, this.focalPoint, up), ); this._getAxes(); this._getDistance(); this._getAngles(); return this; } /** * 固定当前视点,按指定距离放置相机 */ public setDistance(d: number) { if (this.distance === d || d < 0) { return; } this.distance = d; this.dollyingStep = this.distance / 100; const pos = vec3.create(); const n = this.forward; const f = this.focalPoint; pos[0] = d * n[0] + f[0]; pos[1] = d * n[1] + f[1]; pos[2] = d * n[2] + f[2]; this._setPosition(pos); return this; } /** * Changes the initial azimuth of the camera */ public changeAzimuth(az: number) { this.setAzimuth(this.azimuth + az); return this; } /** * Changes the initial elevation of the camera */ public changeElevation(el: number) { this.setElevation(this.elevation + el); return this; } /** * Changes the initial roll of the camera */ public changeRoll(rl: number) { this.setRoll(this.roll + rl); return this; } /** * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置 * @param {Number} el the azimuth in degrees */ public setAzimuth(az: number) { this.azimuth = getAngle(az); this.computeMatrix(); this._getAxes(); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { this._getPosition(); } else if (this.type === CAMERA_TYPE.TRACKING) { this._getFocalPoint(); } return this; } public getAzimuth() { return this.azimuth; } /** * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置 * @param {Number} el the elevation in degrees */ public setElevation(el: number) { this.elevation = getAngle(el); this.computeMatrix(); this._getAxes(); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { this._getPosition(); } else if (this.type === CAMERA_TYPE.TRACKING) { this._getFocalPoint(); } return this; } /** * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置 * @param {Number} angle the roll angle */ public setRoll(angle: number) { this.roll = getAngle(angle); this.computeMatrix(); this._getAxes(); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { this._getPosition(); } else if (this.type === CAMERA_TYPE.TRACKING) { this._getFocalPoint(); } return this; } /** * Changes the azimuth and elevation with respect to the current camera axes * @param {Number} azimuth the relative azimuth * @param {Number} elevation the relative elevation * @param {Number} roll the relative roll */ public rotate(azimuth: number, elevation: number, roll: number) { if (this.type === CAMERA_TYPE.EXPLORING) { azimuth = getAngle(azimuth); elevation = getAngle(elevation); roll = getAngle(roll); const rotX = quat.setAxisAngle( quat.create(), [1, 0, 0], (this.rotateWorld ? 1 : -1) * elevation * DEG_2_RAD, ); const rotY = quat.setAxisAngle( quat.create(), [0, 1, 0], (this.rotateWorld ? 1 : -1) * azimuth * DEG_2_RAD, ); const rotZ = quat.setAxisAngle( quat.create(), [0, 0, 1], roll * DEG_2_RAD, ); let rotQ = quat.multiply(quat.create(), rotY, rotX); rotQ = quat.multiply(quat.create(), rotQ, rotZ); const rotMatrix = mat4.fromQuat(mat4.create(), rotQ); mat4.translate(this.matrix, this.matrix, [0, 0, -this.distance]); mat4.multiply(this.matrix, this.matrix, rotMatrix); mat4.translate(this.matrix, this.matrix, [0, 0, this.distance]); } else { if (Math.abs(this.elevation + elevation) > 90) { return; } this.relElevation = getAngle(elevation); this.relAzimuth = getAngle(azimuth); this.relRoll = getAngle(roll); this.elevation += this.relElevation; this.azimuth += this.relAzimuth; this.roll += this.relRoll; this.computeMatrix(); } this._getAxes(); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { this._getPosition(); } else if (this.type === CAMERA_TYPE.TRACKING) { this._getFocalPoint(); } this._update(); return this; } /** * 沿水平(right) & 垂直(up)平移相机 */ public pan(tx: number, ty: number) { const coords = createVec3(tx, ty, 0); const pos = vec3.clone(this.position); vec3.add(pos, pos, vec3.scale(vec3.create(), this.right, coords[0])); vec3.add(pos, pos, vec3.scale(vec3.create(), this.up, coords[1])); this._setPosition(pos); return this; } /** * 沿 n 轴移动,当距离视点远时移动速度较快,离视点越近速度越慢 */ public dolly(value: number) { const n = this.forward; const pos = vec3.clone(this.position); const step = value * this.dollyingStep; pos[0] += step * n[0]; pos[1] += step * n[1]; pos[2] += step * n[2]; this._setPosition(pos); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { // 重新计算视点距离 this._getDistance(); } else if (this.type === CAMERA_TYPE.TRACKING) { // 保持视距,移动视点位置 vec3.add(this.focalPoint, pos, this.distanceVector); } return this; } // public createLandmark(name: string): Landmark { // return new Landmark(name, this); // } /** * 根据相机矩阵重新计算各种相机参数 */ private _update() { this._getAxes(); this._getPosition(); this._getDistance(); this._getAngles(); } /** * 计算相机矩阵 */ private computeMatrix() { let rotX; let rotY; // 使用四元数描述 3D 旋转 // @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html const rotZ = quat.setAxisAngle( quat.create(), [0, 0, 1], this.roll * DEG_2_RAD, ); mat4.identity(this.matrix); // only consider HCS for EXPLORING and ORBITING cameras rotX = quat.setAxisAngle( quat.create(), [1, 0, 0], (this.rotateWorld || this.type === CAMERA_TYPE.TRACKING ? 1 : -1) * this.elevation * DEG_2_RAD, ); rotY = quat.setAxisAngle( quat.create(), [0, 1, 0], (this.rotateWorld ? 1 : -1) * this.azimuth * DEG_2_RAD, ); let rotQ = quat.multiply(quat.create(), rotY, rotX); rotQ = quat.multiply(quat.create(), rotQ, rotZ); const rotMatrix = mat4.fromQuat(mat4.create(), rotQ); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { mat4.translate(this.matrix, this.matrix, this.focalPoint); mat4.multiply(this.matrix, this.matrix, rotMatrix); mat4.translate(this.matrix, this.matrix, [0, 0, this.distance]); } else if (this.type === CAMERA_TYPE.TRACKING) { mat4.translate(this.matrix, this.matrix, this.position); mat4.multiply(this.matrix, this.matrix, rotMatrix); } } /** * Sets the camera position in the camera matrix */ private _setPosition(x: number | vec3, y?: number, z?: number) { this.position = createVec3(x, y, z); const m = this.matrix; m[12] = this.position[0]; m[13] = this.position[1]; m[14] = this.position[2]; m[15] = 1; } /** * Recalculates axes based on the current matrix */ private _getAxes() { vec3.copy( this.right, createVec3(vec4.transformMat4(vec4.create(), [1, 0, 0, 0], this.matrix)), ); vec3.copy( this.up, createVec3(vec4.transformMat4(vec4.create(), [0, 1, 0, 0], this.matrix)), ); vec3.copy( this.forward, createVec3(vec4.transformMat4(vec4.create(), [0, 0, 1, 0], this.matrix)), ); vec3.normalize(this.right, this.right); vec3.normalize(this.up, this.up); vec3.normalize(this.forward, this.forward); } /** * Recalculates euler angles based on the current state */ private _getAngles() { // Recalculates angles const x = this.distanceVector[0]; const y = this.distanceVector[1]; const z = this.distanceVector[2]; const r = vec3.length(this.distanceVector); // FAST FAIL: If there is no distance we cannot compute angles if (r === 0) { this.elevation = 0; this.azimuth = 0; return; } if (this.type === CAMERA_TYPE.TRACKING) { this.elevation = Math.asin(y / r) * RAD_2_DEG; this.azimuth = Math.atan2(-x, -z) * RAD_2_DEG; } else { if (this.rotateWorld) { this.elevation = Math.asin(y / r) * RAD_2_DEG; this.azimuth = Math.atan2(-x, -z) * RAD_2_DEG; } else { this.elevation = -Math.asin(y / r) * RAD_2_DEG; this.azimuth = -Math.atan2(-x, -z) * RAD_2_DEG; } } } /** * 重新计算相机位置,只有 ORBITING 模式相机位置才会发生变化 */ private _getPosition() { vec3.copy( this.position, createVec3(vec4.transformMat4(vec4.create(), [0, 0, 0, 1], this.matrix)), ); // 相机位置变化,需要重新计算视距 this._getDistance(); } /** * 重新计算视点,只有 TRACKING 模式视点才会发生变化 */ private _getFocalPoint() { vec3.transformMat3( this.distanceVector, [0, 0, -this.distance], mat3.fromMat4(mat3.create(), this.matrix), ); vec3.add(this.focalPoint, this.position, this.distanceVector); // 视点变化,需要重新计算视距 this._getDistance(); } /** * 重新计算视距 */ private _getDistance() { this.distanceVector = vec3.subtract( vec3.create(), this.focalPoint, this.position, ); this.distance = vec3.length(this.distanceVector); this.dollyingStep = this.distance / 100; } }
the_stack
import './setup'; import { Container } from '../src/container'; import { inject, autoinject } from '../src/injection'; describe('injection', () => { it('instantiates class without injected services', () => { class App { } const container = new Container(); const app = container.get(App); expect(app).toEqual(jasmine.any(App)); }); describe('inject', () => { it('uses public static inject method (ES6)', () => { class Logger { } class App { public static inject() { return [Logger]; } constructor(public logger: Logger) { this.logger = logger; } } const container = new Container(); const app = container.get(App); expect(app.logger).toEqual(jasmine.any(Logger)); }); it('uses public static inject property (TypeScript,CoffeeScript,ES5)', () => { class Logger { } class App { public static inject: Logger[]; constructor(public logger: Logger) { this.logger = logger; } } App.inject = [Logger]; const container = new Container(); const app = container.get(App); expect(app.logger).toEqual(jasmine.any(Logger)); }); it('uses inject decorator', () => { class Logger { } @inject(Logger) class App { constructor(public logger: Logger) { this.logger = logger; } } const container = new Container(); const app = container.get(App); expect(app.logger).toEqual(jasmine.any(Logger)); }); it('uses inject as param decorator', () => { class Logger { } @inject(Logger) @autoinject() class App1 { constructor(public logger: Logger) { this.logger = logger; } } const container = new Container(); const app1 = container.get(App1); const logger = app1.logger; expect(logger).toEqual(jasmine.any(Logger)); }); describe('inheritance', () => { class Logger { } class Service { } it('loads dependencies for the parent class', () => { class ParentApp { public static inject() { return [Logger]; } constructor(public logger: Logger) { this.logger = logger; } } class ChildApp extends ParentApp { constructor(...rest) { // @ts-ignore super(...rest); } } const container = new Container(); const app = container.get(ChildApp); expect(app.logger).toEqual(jasmine.any(Logger)); }); it('loads dependencies for the child class', () => { class ParentApp { } class ChildApp extends ParentApp { public static inject() { return [Service]; } constructor(public service: Service, ...rest) { // @ts-ignore super(...rest); this.service = service; } } const container = new Container(); const app = container.get(ChildApp); expect(app.service).toEqual(jasmine.any(Service)); }); it('loads dependencies for both classes', () => { class ParentApp { public static inject() { return [Logger]; } constructor(public logger: Logger) { this.logger = logger; } } class ChildApp extends ParentApp { public static inject() { return [Service]; } constructor(public service: Service, ...rest) { // @ts-ignore super(...rest); this.service = service; } } const container = new Container(); const app = container.get(ChildApp); expect(app.service).toEqual(jasmine.any(Service)); expect(app.logger).toEqual(jasmine.any(Logger)); }); }); }); describe('autoinject', () => { class Logger { } class Service { } class SubService1 { } class SubService2 { } it('injects using design:paramtypes metadata', () => { @autoinject() class App { constructor(public logger: Logger, public service: Service) { } } const container = new Container(); const app = container.get(App); expect(app.logger).toEqual(jasmine.any(Logger)); expect(app.service).toEqual(jasmine.any(Service)); }); describe('inheritance', () => { @autoinject() abstract class ParentApp { constructor(public logger: Logger) { this.logger = logger; } } @autoinject() class ChildApp extends ParentApp { constructor(public service: Service, ...rest) { // @ts-ignore super(...rest); this.service = service; } } @autoinject() class SubChildApp1 extends ChildApp { constructor(public subService1: SubService1, ...rest) { // @ts-ignore super(...rest); this.subService1 = subService1; } } @autoinject() class SubChildApp2 extends ChildApp { constructor(public subService2: SubService2, ...rest) { // @ts-ignore super(...rest); this.subService2 = subService2; } } class SubChildApp3 extends ChildApp { } @autoinject() class SubChildApp4 extends ChildApp { constructor(public logger: Logger, public subService1: SubService1, public service: Service) { super(service, logger); this.subService1 = subService1; } } const container = new Container(); const app1 = container.get(SubChildApp1); const app2 = container.get(SubChildApp2); const app3 = container.get(SubChildApp3); const app4 = container.get(SubChildApp4); it('loads dependencies in tree classes', () => { expect(app1.subService1).toEqual(jasmine.any(SubService1)); expect(app1.service).toEqual(jasmine.any(Service)); expect(app1.logger).toEqual(jasmine.any(Logger)); }); it('does not effect other child classes with different parameters', () => { expect(app2.subService2).toEqual(jasmine.any(SubService2)); expect(app2.service).toEqual(jasmine.any(Service)); expect(app2.logger).toEqual(jasmine.any(Logger)); }); it('does inherit injection without own autoinject', () => { expect(app3.service).toEqual(jasmine.any(Service)); expect(app3.logger).toEqual(jasmine.any(Logger)); }); it('does allow a changed constructor parameter order', () => { expect(app4.subService1).toEqual(jasmine.any(SubService1)); expect(app4.service).toEqual(jasmine.any(Service)); expect(app4.logger).toEqual(jasmine.any(Logger)); }); it('not fail with inherited inject() method', () => { class ParentApp { public static inject() { return [Logger]; } constructor(public logger: Logger) { this.logger = logger; } } Reflect.set(ParentApp, 'design:paramtypes', [Logger]); @inject(Logger) class App { public static inject() { return [Logger]; } constructor(public logger: Logger) { this.logger = logger; } } @autoinject() class ChildApp extends ParentApp { constructor(public service: Service, ...rest) { // @ts-ignore super(...rest); this.service = service; } } const container = new Container(); const app1 = container.get(ParentApp); expect(app1.logger).toEqual(jasmine.any(Logger)); const app2 = container.get(ChildApp); expect(app2.logger).toEqual(jasmine.any(Logger)); expect(app2.service).toEqual(jasmine.any(Service)); }); it('test variadic arguments (TypeScript metadata)', () => { const container = new Container(); const VariadicArg = Object; // TypeScript emits "Object" type for "...rest" param class Dep$1 { } class Dep$2 { } class Dep$3 { } class Dep$4 { } class Dep$5 { } @autoinject() class ParentOneDep { constructor(public dep1: Dep$1) { this.dep1 = dep1; } } @autoinject() class ParentTwoDeps { constructor(public dep1: Dep$1, public dep2: Dep$2) { this.dep1 = dep1; this.dep2 = dep2; } } class ChildZeroDeps$1 extends ParentOneDep { } class ChildZeroDeps$2 extends ParentTwoDeps { } @autoinject() class ChildOneDep$1 extends ParentOneDep { constructor(public dep3: Dep$3, ...rest) { // @ts-ignore super(...rest); this.dep3 = dep3; } } { const a = container.get(ChildOneDep$1); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); } @autoinject() class ChildOneDep$2 extends ParentTwoDeps { constructor(public dep3: Dep$3, ...rest) { // @ts-ignore super(...rest); this.dep3 = dep3; } } { const a = container.get(ChildOneDep$2); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep2).toEqual(jasmine.any(Dep$2)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); } @autoinject() class ChildTwoDeps$1 extends ParentOneDep { constructor(public dep3: Dep$3, public dep4: Dep$4, ...rest) { // @ts-ignore super(...rest); this.dep3 = dep3; this.dep4 = dep4; } } @autoinject() class ChildTwoDeps$2 extends ParentTwoDeps { constructor(public dep3: Dep$3, public dep4: Dep$4, ...rest) { // @ts-ignore super(...rest); this.dep3 = dep3; this.dep4 = dep4; } } class GrandChildZeroDeps$01 extends ChildZeroDeps$1 { } { const a = container.get(GrandChildZeroDeps$01); expect(a.dep1).toEqual(jasmine.any(Dep$1)); } class GrandChildZeroDeps$02 extends ChildZeroDeps$2 { } { const a = container.get(GrandChildZeroDeps$02); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep2).toEqual(jasmine.any(Dep$2)); } class GrandChildZeroDeps$11 extends ChildOneDep$1 { } { const a = container.get(GrandChildZeroDeps$11); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); } class GrandChildZeroDeps$12 extends ChildOneDep$2 { } { const a = container.get(GrandChildZeroDeps$12); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep2).toEqual(jasmine.any(Dep$2)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); } class GrandChildZeroDeps$21 extends ChildTwoDeps$1 { } { const a = container.get(GrandChildZeroDeps$21); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); expect(a.dep4).toEqual(jasmine.any(Dep$4)); } class GrandChildZeroDeps$22 extends ChildTwoDeps$2 { } { const a = container.get(GrandChildZeroDeps$22); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep2).toEqual(jasmine.any(Dep$2)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); expect(a.dep4).toEqual(jasmine.any(Dep$4)); } @autoinject() class GrandChildOneDep$01 extends ChildZeroDeps$1 { constructor(public dep5: Dep$5, ...rest) { // @ts-ignore super(...rest); this.dep5 = dep5; } } { const a = container.get(GrandChildOneDep$01); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep5).toEqual(jasmine.any(Dep$5)); } @autoinject() class GrandChildOneDep$02 extends ChildZeroDeps$2 { constructor(public dep5: Dep$5, ...rest) { // @ts-ignore super(...rest); this.dep5 = dep5; } } { const a = container.get(GrandChildOneDep$02); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep2).toEqual(jasmine.any(Dep$2)); expect(a.dep5).toEqual(jasmine.any(Dep$5)); } @autoinject() class GrandChildOneDep$11 extends ChildOneDep$1 { constructor(public dep5: Dep$5, ...rest) { // @ts-ignore super(...rest); this.dep5 = dep5; } } { const a = container.get(GrandChildOneDep$11); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); expect(a.dep5).toEqual(jasmine.any(Dep$5)); } @autoinject() class GrandChildOneDep$12 extends ChildOneDep$2 { constructor(public dep5: Dep$5, ...rest) { // @ts-ignore super(...rest); this.dep5 = dep5; } } { const a = container.get(GrandChildOneDep$12); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep2).toEqual(jasmine.any(Dep$2)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); expect(a.dep5).toEqual(jasmine.any(Dep$5)); } @autoinject() class GrandChildOneDep$21 extends ChildTwoDeps$1 { constructor(public dep5: Dep$5, ...rest) { // @ts-ignore super(...rest); this.dep5 = dep5; } } { const a = container.get(GrandChildOneDep$21); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); expect(a.dep4).toEqual(jasmine.any(Dep$4)); expect(a.dep5).toEqual(jasmine.any(Dep$5)); } @autoinject() class GrandChildOneDep$22 extends ChildTwoDeps$2 { constructor(public dep5: Dep$5, ...rest) { // @ts-ignore super(...rest); this.dep5 = dep5; } } { const a = container.get(GrandChildOneDep$22); expect(a.dep1).toEqual(jasmine.any(Dep$1)); expect(a.dep2).toEqual(jasmine.any(Dep$2)); expect(a.dep3).toEqual(jasmine.any(Dep$3)); expect(a.dep4).toEqual(jasmine.any(Dep$4)); expect(a.dep5).toEqual(jasmine.any(Dep$5)); } }); }); }); describe('inject as param decorator', () => { it('a simple dependency (Typescript)', () => { class Logger { } @inject(Logger) @autoinject() class App1 { constructor(public logger: Logger) { this.logger = logger; } } const container = new Container(); const app1 = container.get(App1); const logger = app1.logger; expect(logger).toEqual(jasmine.any(Logger)); }); // not very useful maybe, but allowed in the current implementation it('a simple dependency (ES6)', () => { class Logger { } class App1 { constructor(public logger: Logger) { this.logger = logger; } } inject(Logger)(App1, null, 0); const container = new Container(); const app1 = container.get(App1); const logger = app1.logger; expect(logger).toEqual(jasmine.any(Logger)); }); it('fixes the dependency derived from metadata (Typescript)', () => { class LoggerBase { } class Logger extends LoggerBase { } @inject(LoggerBase) @autoinject() class App1 { constructor(public logger: LoggerBase) { this.logger = logger; } } const container = new Container(); const app1 = container.get(App1); const logger = app1.logger; expect(logger).not.toEqual(jasmine.any(Logger)); expect(logger).toEqual(jasmine.any(LoggerBase)); }); // not sure if that's useful, but current implementation allows it it('on a member function', () => { class Logger { } /* class App1 { @inject(Logger) member(logger){ this.logger=logger; } } */ class App1 { public logger; @inject(Logger) public member(logger) { this.logger = logger; } } const container = new Container(); const app1 = container.get(App1); // @ts-ignore const member: App1 = container.get(app1.member); const logger = member.logger; expect(logger).toEqual(jasmine.any(Logger)); }); }); });
the_stack
import {useEffect, useMemo, useRef} from "react"; import { QueryClient, useInfiniteQuery, useMutation, useQueryClient, } from "react-query"; import { DocumentData, FieldPath, FirebaseFirestore, Query, QueryDocumentSnapshot, } from "@firebase/firestore-types"; import {useFirestore} from "./Provider"; import {collectionCache} from "./Cache"; import { CollectionQueryType, Document, empty, InfiniteOptions, OrderByArray, OrderByType, WhereArray, WhereType, } from "./types"; import {parseDates} from "./utils"; const createFirestoreRef = ( firestore: FirebaseFirestore, path: string, { where, orderBy, limit, startAt, endAt, startAfter, endBefore, isCollectionGroup, }: CollectionQueryType, ) => { let ref: Query = firestore.collection(path); if (isCollectionGroup) { ref = firestore.collectionGroup(path); } if (where) { function multipleConditions(w: WhereType): w is WhereArray { return !!(w as WhereArray) && Array.isArray(w[0]); } if (multipleConditions(where)) { where.forEach((w) => { ref = ref.where(w[0] as string | FieldPath, w[1], w[2]); }); } else if ( typeof where[0] === "string" && typeof where[1] === "string" ) { ref = ref.where(where[0], where[1], where[2]); } } if (orderBy) { if (typeof orderBy === "string") { ref = ref.orderBy(orderBy); } else if (Array.isArray(orderBy)) { function multipleOrderBy(o: OrderByType): o is OrderByArray[] { return Array.isArray((o as OrderByArray[])[0]); } if (multipleOrderBy(orderBy)) { orderBy.forEach(([order, direction]) => { ref = ref.orderBy(order as string | FieldPath, direction); }); } else { const [order, direction] = orderBy; ref = ref.orderBy(order as string | FieldPath, direction); } } } if (startAt) { ref = ref.startAt(startAt); } if (endAt) { ref = ref.endAt(endAt); } if (startAfter) { ref = ref.startAfter(startAfter); } if (endBefore) { ref = ref.endBefore(endBefore); } if (limit) { ref = ref.limit(limit); } return ref; }; type ListenerReturnType<Doc extends Document = Document> = { response: { data: Doc[]; lastDoc?: QueryDocumentSnapshot<DocumentData>; }; unsubscribe: () => void; }; const createListenerAsync = async <Doc extends Document = Document>( firestore: FirebaseFirestore, queryClient: QueryClient, path: string | undefined = undefined, queryString: string, pageParam: any, ): Promise<ListenerReturnType<Doc>> => { return new Promise((resolve, reject) => { if (!path) { return resolve({ response: { data: [], }, unsubscribe: empty.function, }); } const query: CollectionQueryType = JSON.parse(queryString) ?? {}; let ref = createFirestoreRef(firestore, path, query); if (pageParam) { ref = ref.startAfter(pageParam); } const unsubscribe = ref.onSnapshot( {includeMetadataChanges: false}, { next: (querySnapshot) => { const data: Doc[] = []; querySnapshot.forEach((doc) => { const docData = doc.data() ?? empty.object; parseDates(docData); const docToAdd = { ...docData, id: doc.id, exists: doc.exists, hasPendingWrites: doc.metadata.hasPendingWrites, __snapshot: doc, } as Doc; // update individual docs in the cache queryClient.setQueryData(doc.ref.path, docToAdd); data.push(docToAdd); }); resolve({ response: { data, lastDoc: data[data.length - 1]?.__snapshot, }, unsubscribe, }); }, error: reject, }, ); }); }; /** * Call a Firestore Collection * @template Doc * @param path String if the document is ready. If it's not ready yet, pass `undefined`, and the request won't start yet. * @param [options] - takes any of useQuery options. * @param [query] - Dictionary with options to query the collection. */ export const useInfiniteCollection = <Data, TransData extends Data = Data>( path?: string, options?: InfiniteOptions< {data: Document<Data>[]; lastDoc?: QueryDocumentSnapshot<DocumentData>}, {data: Document<TransData>} >, query?: CollectionQueryType<Document<Data>>, ) => { const {firestore} = useFirestore(); const queryClient = useQueryClient(); const unsubscribeRef = useRef<ListenerReturnType["unsubscribe"] | null>( null, ); const { where, endAt, endBefore, startAfter, startAt, orderBy, limit, isCollectionGroup, } = query || {}; // why not just put this into the ref directly? // so that we can use the useEffect down below that triggers revalidate() const memoQueryString = useMemo( () => JSON.stringify({ where, endAt, endBefore, startAfter, startAt, orderBy, limit, isCollectionGroup, }), [ endAt, endBefore, isCollectionGroup, limit, orderBy, startAfter, startAt, where, ], ); async function fetch({pageParam}: any) { if (unsubscribeRef.current) { unsubscribeRef.current(); unsubscribeRef.current = null; } const {unsubscribe, response} = await createListenerAsync< Document<Data> >(firestore, queryClient, path, memoQueryString, pageParam); unsubscribeRef.current = unsubscribe; return response; } const { data, status, error, fetchNextPage, hasNextPage, isFetchingNextPage, } = useInfiniteQuery< {data: Document<Data>[]; lastDoc?: QueryDocumentSnapshot<DocumentData>}, Error, {data: Document<TransData>} >([path, memoQueryString], fetch, { ...options, notifyOnChangeProps: "tracked", getNextPageParam: (lastPage) => { return lastPage.lastDoc; }, }); const {mutateAsync} = useMutation< Document<Data>[], Error, {data: Data | Data[]; subPath?: string}, {previousPages: any} >( async ({data: newData, subPath}) => { if (!path) return Promise.resolve([]); const newPath = subPath ? path + "/" + subPath : path; const dataArray = Array.isArray(newData) ? newData : [newData]; const ref = firestore.collection(newPath); const docsToAdd: Document<Data>[] = dataArray.map((doc) => ({ ...doc, // generate IDs we can use that in the local cache that match the server id: ref.doc().id, })); // add to network const batch = firestore.batch(); docsToAdd.forEach(({id, ...doc}) => { // take the ID out of the document batch.set(ref.doc(id), doc); }); await batch.commit(); return Promise.resolve(docsToAdd); }, { // When mutate is called: // onMutate: async ({data}) => { // const dataArray = Array.isArray(data) ? data : [data]; // // Cancel any outgoing refetches (so they don't overwrite our optimistic update) // await queryClient.cancelQueries([path, memoQueryString]); // // Snapshot the previous value // const previousPages = queryClient.getQueryData([ // path, // memoQueryString, // ]); // // Optimistically update to the new value // queryClient.setQueryData<{ // pages: { // data: Document<Data>[]; // lastDoc?: QueryDocumentSnapshot<DocumentData>; // }[]; // pageParams: any; // }>([path, memoQueryString], (resp) => { // if (!resp) return resp as any; // const newPagesArray = resp.pages.map((page, index) => { // return index === resp.pages.length - 1 // ? { // data: [...dataArray, ...page.data], // lastDoc: page.lastDoc, // } // : page; // }); // return {pages: newPagesArray, pageParams: resp.pageParams}; // }); // // Return a context object with the snapshotted value // return {previousPages}; // }, // // If the mutation fails, use the context returned from onMutate to roll back // onError: (_, __, context) => { // queryClient.setQueryData( // [path, memoQueryString], // context?.previousPages, // ); // }, // Always refetch after error or success: onSettled: () => { queryClient.invalidateQueries([path, memoQueryString]); }, }, ); useEffect(() => { //should it go before the useQuery? return () => { // clean up listener on unmount if it exists if (unsubscribeRef.current) { unsubscribeRef.current(); unsubscribeRef.current = null; } }; // should depend on the path, queyr being the same... }, [path, memoQueryString]); // add the collection to the cache, // so that we can mutate it from document calls later useEffect(() => { if (path) collectionCache.addCollectionToCache(path, memoQueryString); }, [path, memoQueryString]); /** * `add(data, subPath?)`: Extends the Firestore document [`add` function](https://firebase.google.com/docs/firestore/manage-data/add-data). * - It also updates the local cache using react-query's `setQueryData`. This will prove highly convenient over the regular `add` function provided by Firestore. * - If the second argument is defined it will be concatinated to path arg as a prefix */ const add = async (newData: Data | Data[], subPath?: string) => mutateAsync({data: newData, subPath}); const formattedData = useMemo(() => { return data?.pages.map((page) => page.data).flat(); }, [data]); return { data: formattedData, status, error, add, fetchNextPage, hasNextPage, isFetchingNextPage, /** * A function that, when called, unsubscribes the Firestore listener. * * The function can be null, so make sure to check that it exists before calling it. * * Note: This is not necessary to use. `useCollection` already unmounts the listener for you. This is only intended if you want to unsubscribe on your own. */ unsubscribe: unsubscribeRef.current, }; };
the_stack
import * as THREE from 'three'; import type {Point2D} from '../types'; import ScatterChart from '../ScatterChart'; import fragmentShader from './fragment.glsl'; import vertexShader from './vertex.glsl'; const CANVAS_MAX_WIDTH = 16384; const CANVAS_MAX_HEIGHT = 16384; const VERTEX_COUNT_PER_LABEL = 6; type Position2D = [Point2D, Point2D]; export default class LabelScatterChart extends ScatterChart { static readonly LABEL_COLOR = new THREE.Color(0x000000); static readonly LABEL_BACKGROUND_COLOR_DEFAULT = new THREE.Color(0xffffff); static readonly LABEL_BACKGROUND_COLOR_HOVER = new THREE.Color(0x2932e1); static readonly LABEL_BACKGROUND_COLOR_HIGHLIGHT = new THREE.Color(0x2932e1); static readonly LABEL_BACKGROUND_COLOR_FOCUS = new THREE.Color(0x2932e1); static readonly LABEL_FONT = 'roboto'; static readonly LABEL_FONT_SIZE = 20; static readonly LABEL_PADDING = [3, 5] as const; protected blending: THREE.Blending = THREE.NormalBlending; protected vertexShader: string = vertexShader; protected fragmentShader: string = fragmentShader; private glyphTexture: THREE.CanvasTexture | null = null; private mesh: THREE.Mesh | null = null; private textWidthInGlyphTexture: number[] = []; private textPositionInGlyphTexture: Position2D[] = []; get object() { return this.mesh; } get defaultColor() { return LabelScatterChart.LABEL_BACKGROUND_COLOR_DEFAULT; } get hoveredColor() { return LabelScatterChart.LABEL_BACKGROUND_COLOR_HOVER; } get focusedColor() { return LabelScatterChart.LABEL_BACKGROUND_COLOR_FOCUS; } get highLightColor() { return LabelScatterChart.LABEL_BACKGROUND_COLOR_HIGHLIGHT; } // eslint-disable-next-line @typescript-eslint/no-explicit-any protected createShaderUniforms(picking: boolean): Record<string, THREE.IUniform<any>> { return { glyphTexture: {value: this.glyphTexture}, picking: {value: picking} }; } private convertVertexes() { const count = this.dataCount; const vertexes = new Float32Array(count * VERTEX_COUNT_PER_LABEL * 3); for (let i = 0; i < count; i++) { for (let j = 0; j < VERTEX_COUNT_PER_LABEL; j++) { for (let k = 0; k < 3; k++) { vertexes[i * VERTEX_COUNT_PER_LABEL * 3 + j * 3 + k] = this.positions[i * 3 + k]; } } } return vertexes; } private convertPickingColors() { if (this.pickingColors) { const count = this.dataCount; const colors = new Float32Array(count * VERTEX_COUNT_PER_LABEL * 3); for (let i = 0; i < count; i++) { for (let j = 0; j < VERTEX_COUNT_PER_LABEL; j++) { for (let k = 0; k < 3; k++) { colors[i * VERTEX_COUNT_PER_LABEL * 3 + j * 3 + k] = this.pickingColors[i * 3 + k]; } } } return colors; } return null; } private convertPositionsToLabelPosition() { const count = this.dataCount; const vertexes = new Float32Array(count * VERTEX_COUNT_PER_LABEL * 2); const scaleFactor = 1 / (700 * LabelScatterChart.CUBE_LENGTH); const height = (LabelScatterChart.LABEL_FONT_SIZE + 2 * LabelScatterChart.LABEL_PADDING[0]) * scaleFactor; for (let i = 0; i < count; i++) { const vi = i * VERTEX_COUNT_PER_LABEL * 2; const width = this.textWidthInGlyphTexture[i] * scaleFactor; const x1 = -width; const y1 = -height; const x2 = width; const y2 = height; vertexes[vi] = x1; vertexes[vi + 1] = y1; vertexes[vi + 2] = x2; vertexes[vi + 3] = y1; vertexes[vi + 4] = x1; vertexes[vi + 5] = y2; vertexes[vi + 6] = x1; vertexes[vi + 7] = y2; vertexes[vi + 8] = x2; vertexes[vi + 9] = y1; vertexes[vi + 10] = x2; vertexes[vi + 11] = y2; } return vertexes; } private convertGlyphTexturePositionsToUV() { const count = this.dataCount; const uv = new Float32Array(count * VERTEX_COUNT_PER_LABEL * 2); for (let i = 0; i < count; i++) { const vi = i * VERTEX_COUNT_PER_LABEL * 2; let x1 = 0; let y1 = 0; let x2 = 1; let y2 = 1; if (this.textPositionInGlyphTexture[i]) { const [topLeft, bottomRight] = this.textPositionInGlyphTexture[i]; x1 = topLeft[0]; y1 = 1 - topLeft[1]; x2 = bottomRight[0]; y2 = 1 - bottomRight[1]; } uv[vi] = x1; uv[vi + 1] = y2; uv[vi + 2] = x2; uv[vi + 3] = y2; uv[vi + 4] = x1; uv[vi + 5] = y1; uv[vi + 6] = x1; uv[vi + 7] = y1; uv[vi + 8] = x2; uv[vi + 9] = y2; uv[vi + 10] = x2; uv[vi + 11] = y1; } return uv; } private convertVertexColors() { const count = this.dataCount; const colors = new Float32Array(count * VERTEX_COUNT_PER_LABEL * 3); for (let i = 0; i < count; i++) { const color = this.getColorByIndex(i); for (let j = 0; j < VERTEX_COUNT_PER_LABEL; j++) { colors[i * VERTEX_COUNT_PER_LABEL * 3 + j * 3] = color.r; colors[i * VERTEX_COUNT_PER_LABEL * 3 + j * 3 + 1] = color.g; colors[i * VERTEX_COUNT_PER_LABEL * 3 + j * 3 + 2] = color.b; } } return colors; } private createGlyphTexture() { const dpr = window.devicePixelRatio; const labelCount = this.labels.length; const fontSize = LabelScatterChart.LABEL_FONT_SIZE * dpr; const font = `bold ${fontSize}px roboto`; const [vPadding, hPadding] = LabelScatterChart.LABEL_PADDING; const canvas = document.createElement('canvas'); canvas.width = CANVAS_MAX_WIDTH; canvas.height = fontSize; const ctx = canvas.getContext('2d'); let canvasWidth = 0; let canvasHeight = fontSize + 2 * vPadding; const positions: Position2D[] = []; const textWidths: number[] = []; if (ctx) { ctx.font = font; ctx.fillStyle = LabelScatterChart.LABEL_COLOR.getStyle(); ctx.textAlign = 'start'; ctx.textBaseline = 'top'; let x = hPadding; let y = vPadding; for (let i = 0; i < labelCount; i++) { const label = this.labels[i]; const index = this.labels.indexOf(label); if (index >= 0 && i !== index) { textWidths.push(textWidths[index]); // deep copy position positions.push([ [positions[index][0][0], positions[index][0][1]], [positions[index][1][0], positions[index][1][1]] ]); continue; } const textWidth = Math.ceil(ctx.measureText(label).width); textWidths.push(Math.floor(textWidth / dpr) + 2 * hPadding); const deltaX = textWidth + hPadding; const deltaY = fontSize + vPadding; if (x + deltaX > CANVAS_MAX_WIDTH) { x = hPadding; y += deltaY; if (y > CANVAS_MAX_HEIGHT) { throw new Error('Texture too large!'); } canvasHeight = y + deltaY; } positions.push([ [x - hPadding, y - vPadding], [x + deltaX, y + deltaY] ]); x += deltaX; if (canvasWidth < x) { canvasWidth = x; } } canvas.width = canvasWidth; canvas.height = canvasHeight; ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, canvasWidth, canvasHeight); ctx.font = font; ctx.fillStyle = LabelScatterChart.LABEL_COLOR.getStyle(); ctx.textAlign = 'start'; ctx.textBaseline = 'top'; for (let i = 0; i < labelCount; i++) { const label = this.labels[i]; const index = this.labels.indexOf(label); if (index >= 0 && i !== index) { continue; } const [position] = positions[i]; ctx.fillText(label, position[0] + hPadding, position[1] + vPadding); } positions.forEach(position => { position[0][0] /= canvasWidth; position[0][1] /= canvasHeight; position[1][0] /= canvasWidth; position[1][1] /= canvasHeight; }); } const texture = new THREE.CanvasTexture(canvas); texture.needsUpdate = true; texture.minFilter = THREE.LinearFilter; texture.generateMipmaps = false; texture.flipY = true; this.glyphTexture = texture; this.textWidthInGlyphTexture = textWidths; this.textPositionInGlyphTexture = positions; } private setLabelPosition(position: Float32Array) { this.setGeometryAttribute('labelPosition', position, 2); } private setTextureUV(uv: Float32Array) { this.setGeometryAttribute('uv', uv, 2); } protected onRender() { this.colors = this.convertVertexColors(); } protected onSetSize() { // nothing to do } protected onDataSet() { this.createGlyphTexture(); const uv = this.convertGlyphTexturePositionsToUV(); this.setTextureUV(uv); const labelPosition = this.convertPositionsToLabelPosition(); this.setLabelPosition(labelPosition); const vertexes = this.convertVertexes(); this.setPosition(vertexes); this.pickingColors = this.convertPickingColors(); this.createMaterial(); if (this.material) { this.mesh = new THREE.Mesh(this.geometry, this.material); this.mesh.frustumCulled = false; } } protected onDispose() { this.glyphTexture?.dispose(); } }
the_stack
import {Component, HostListener, Input, OnChanges, ViewEncapsulation} from '@angular/core'; import * as d3 from 'd3'; import {DistributionDataDTO} from '../../models/distribution-data.model'; import '../util/chart-label-util'; import ChartLabelUtil from '../util/chart-label-util'; import {MeasurandColorService} from '../../../shared/services/measurand-color.service'; import {ViolinChartMathService} from '../../services/violin-chart-math.service'; import {SpinnerService} from '../../../shared/services/spinner.service'; import {DistributionDTO} from '../../models/distribution.model'; import {CurveFactory} from 'd3-shape'; import {TranslateService} from '@ngx-translate/core'; @Component({ selector: 'osm-violin-chart', encapsulation: ViewEncapsulation.None, templateUrl: './violin-chart.component.html', styleUrls: ['./violin-chart.component.scss'] }) export class ViolinChartComponent implements OnChanges { @Input() dataInput: DistributionDataDTO; maxValueForInputField: number = null; dataTrimValue: number = null; stepForInputField = 50; filterRules: {} = {}; selectedSortingRule = 'desc'; selectedFilterRule = ''; private height = 600; private width = 600; private margin = {top: 50, right: 0, bottom: 70, left: 100}; private violinWidth: number = null; private maxViolinWidth = 150; private interpolation: CurveFactory = d3.curveBasis; private mainDataResolution = 30; private chartData: DistributionDataDTO = null; private currentSeries: DistributionDTO[] = null; private commonLabelParts: string = null; constructor(private measurandColorProviderService: MeasurandColorService, private violinChartMathService: ViolinChartMathService, private spinnerService: SpinnerService, private translationService: TranslateService) { } @HostListener('window:resize') windowResize() { this.drawChart(); } ngOnChanges(): void { this.drawChart(); } drawChart(): void { this.spinnerService.showSpinner('violin-chart-spinner'); d3.select('#svg-container').selectAll('*').remove(); if (this.dataInput == null || this.dataInput.series.length === 0) { return; } this.chartData = this.prepareChartData(this.dataInput); this.initSvg(); this.assignShortLabels(); this.currentSeries = this.sortSeries(); this.drawChartElements(); this.setSvgWidth(); this.spinnerService.hideSpinner('violin-chart-spinner'); } setSortingRule(sortingRule: string): void { if (sortingRule !== 'desc' && sortingRule !== 'asc') { return; } this.selectedSortingRule = sortingRule; this.selectedFilterRule = ''; this.drawChart(); } setFilterRule(filterRule: string): void { if (!Object.keys(this.filterRules).includes(filterRule)) { return; } this.selectedFilterRule = filterRule; this.selectedSortingRule = ''; this.drawChart(); } hasFilterRules(): boolean { return Object.keys(this.filterRules).length > 0; } private prepareChartData(inputData: DistributionDataDTO): DistributionDataDTO { const chartData = {...inputData}; chartData.series.forEach((elem: DistributionDTO) => { return elem.data.sort(d3.ascending); }); chartData.sortingRules = this.getSortingRulesByMedian(chartData); chartData.measurandGroup = this.translationService.instant(`frontend.de.iteratec.isr.measurand.group.${chartData.measurandGroup}`); this.filterRules = chartData.filterRules; return chartData; } private initSvg(): void { const svgContainerSelection = d3.select('#svg-container'); svgContainerSelection .append('svg') .attr('id', 'svg') .attr('class', 'd3chart') .attr('height', this.height) .attr('width', '100%'); this.width = (<HTMLElement>svgContainerSelection.node()).getBoundingClientRect().width; } private assignShortLabels(): void { const seriesLabelParts = this.chartData.series.map((elem: DistributionDTO) => { return {grouping: elem.identifier, page: elem.page, jobGroup: elem.jobGroup, label: elem.identifier}; }); const labelUtil = ChartLabelUtil.processWith(seriesLabelParts); labelUtil.getSeriesWithShortestUniqueLabels(); this.commonLabelParts = labelUtil.getCommonLabelParts(); seriesLabelParts.forEach((labelPart: { grouping: string, page: string, jobGroup: string, label: string }, index: number) => { this.chartData.series[index].label = labelPart.label; }); } private sortSeries(): DistributionDTO[] { if ((this.selectedSortingRule === 'desc' || this.selectedSortingRule === 'asc') && this.selectedFilterRule.length === 0) { return this.chartData.sortingRules[this.selectedSortingRule].map(trace => { return this.chartData.series[trace]; }); } else if (Object.keys(this.filterRules).includes(this.selectedFilterRule)) { const keyForSelectedFilterRule = Object.keys(this.filterRules).filter((key: string) => key === this.selectedFilterRule).toString(); const filteredDistributionIdentifiers: string[] = this.filterRules[keyForSelectedFilterRule]; return this.chartData.series.filter((distribution: DistributionDTO) => filteredDistributionIdentifiers.some((distributionIdentifier: string) => distribution.identifier === distributionIdentifier )); } } private drawChartElements(): void { this.violinWidth = this.calculateViolinWidth(); const maxValue: number = this.violinChartMathService.getMaxValue(this.currentSeries); if (this.dataTrimValue && this.dataTrimValue > maxValue) { this.dataTrimValue = null; } const domain: number[] = this.violinChartMathService.getDomain(maxValue, this.dataTrimValue); this.stepForInputField = this.violinChartMathService.getAdequateStep(maxValue); this.maxValueForInputField = Math.ceil(maxValue / this.stepForInputField) * this.stepForInputField; this.drawXAxis(); this.drawYAxis(domain, `${this.chartData.measurandGroup} [${this.chartData.dimensionalUnit}]`); this.drawViolins(domain); this.drawHeader(); // remove the xAxis lines d3.select('.d3chart-axis.d3chart-x-axis > path.domain').remove(); d3.selectAll('.d3chart-axis.d3chart-x-axis g > line').remove(); } private setSvgWidth(): void { const lastLabelWidth: number = Math.ceil( (<SVGGElement>d3.select(`#x-axis-label${this.currentSeries.length - 1}`).node()).getBoundingClientRect().width ); const graphWidth: number = (this.violinWidth / 2 > lastLabelWidth) ? 120 + this.currentSeries.length * this.violinWidth : 120 + (this.currentSeries.length - 0.5) * this.violinWidth + lastLabelWidth; d3.select('#svg').attr('width', graphWidth); } private getSortingRulesByMedian(data: DistributionDataDTO): { desc: number[], asc: number[] } { data.series.forEach((seriesData: DistributionDTO) => { seriesData.median = this.violinChartMathService.calculateMedian(seriesData.data); }); const sortings = {desc: [], asc: []}; sortings.desc = Object.keys(data.series).sort((a, b) => { return data.series[b].median - data.series[a].median; }); sortings.asc = Object.keys(data.series).sort((a, b) => { return data.series[a].median - data.series[b].median; }); return sortings; } private calculateViolinWidth(): number { const svgWidth = this.width - this.margin.left; const numberOfViolins = this.currentSeries.length; if (numberOfViolins * this.maxViolinWidth > svgWidth) { return svgWidth / numberOfViolins; } return this.maxViolinWidth; } private drawXAxis(): void { const x = d3.scaleOrdinal(this.getXRange()) .domain(this.currentSeries.map(elem => elem.label)); d3.select('#svg') .append('g') .attr('id', 'x-axis') .attr('class', 'd3chart-axis d3chart-x-axis') .call(d3.axisBottom(x)) .call(() => this.rotateLabels()) .attr('transform', `translate(${this.margin.left}, ${(this.height - this.margin.bottom)})`); } private drawYAxis(domain: number[], text: string): void { const y = d3.scaleLinear() .range([this.height - this.margin.bottom, this.margin.top]) .domain(domain); const yAxis = d3.select('#svg') .append('g') .attr('id', 'y-axis') .attr('class', 'd3chart-axis d3chart-y-axis') .attr('transform', `translate(${this.margin.left}, 0)`); yAxis.append('text') .attr('class', 'y-axis-left-label') .attr('transform', `translate(-50, ${(this.height - this.margin.bottom - this.margin.top) / 2}) rotate(-90)`) .text(text); yAxis.call(d3.axisLeft(y)); yAxis.selectAll('.tick line').classed('d3chart-y-axis-line', true); yAxis.selectAll('path').classed('d3chart-y-axis-line', true); } private drawViolins(domain: number[]): void { const svgSelection = d3.select('#svg'); svgSelection.selectAll('clipPath').remove(); svgSelection.select('[clip-path]').remove(); const violinGroup = svgSelection.append('g'); this.createClipPathAroundViolins(violinGroup); this.currentSeries.forEach((distribution: DistributionDTO, index: number) => { const traceData = distribution.data; const g = violinGroup.append('g') .attr('id', `violin${index}`) .attr('class', 'd3chart-violin') .attr('style', 'fill: none;') .attr('transform', `translate(${(index * this.violinWidth + this.margin.left)}, 0)`); this.addViolin(g, traceData, this.height - this.margin.bottom, this.violinWidth, domain); }); } private drawHeader(): void { const getHeaderTransform = () => { const widthOfAllViolins = this.currentSeries.length * this.violinWidth; return `translate(${(this.margin.left + widthOfAllViolins / 2)}, 20)`; }; d3.select('#svg') .append('g') .attr('id', 'header') .selectAll('text') .data([this.commonLabelParts]) .enter() .append('text') .text(this.commonLabelParts) .attr('id', 'header-text') .attr('text-anchor', 'middle') .attr('transform', getHeaderTransform()); } private getXRange(): number[] { return this.currentSeries.map((_, index: number) => { return index * this.violinWidth + this.violinWidth / 2; }); } private rotateLabels(): void { let maxLabelLength = -1; let rotate; d3.selectAll('.d3chart-x-axis g').each((_, index: number, nodes: d3.BaseType[]) => { const gElement = d3.select(nodes[index]); gElement .attr('id', `x-axis-label${index}`) .attr('class', 'x-axis-label'); const childTextElem = gElement.select('text'); const childTextElemNode: SVGTSpanElement = <SVGTSpanElement>childTextElem.node(); const labelLength = childTextElemNode.getComputedTextLength(); if (labelLength > maxLabelLength) { maxLabelLength = labelLength; } if (labelLength > this.violinWidth) { rotate = true; } }); this.margin.bottom = Math.cos(Math.PI / 4) * maxLabelLength + 20; if (rotate) { d3.selectAll('.d3chart-x-axis g').each((_, index: number, nodes: d3.BaseType[]) => { const selectedLabel = d3.select(nodes[index] as SVGGElement); this.rotateLabel(selectedLabel); }); } } private createClipPathAroundViolins(violinGroup: d3.Selection<SVGGElement, {}, HTMLElement, any>): void { const clipPathId = 'drawing-area'; d3.select('#svg') .append('clipPath') .attr('id', clipPathId) .append('rect') .attr('x', this.margin.left) .attr('y', this.margin.top) .attr('width', this.width - this.margin.left - this.margin.right) .attr('height', this.height - this.margin.top - this.margin.bottom); violinGroup.attr('clip-path', `url(#${clipPathId})`); } private addViolin(gElement: d3.Selection<SVGGElement, {}, HTMLElement, {}>, traceData: number[], height: number, violinWidth: number, domain: number[]): void { const resolution = this.violinChartMathService .histogramResolutionForTraceData(this.currentSeries, traceData, this.mainDataResolution); const data = d3.histogram() .thresholds(resolution) (traceData); // y is now the horizontal axis because of the violin being a 90 degree rotated histogram const y: d3.ScaleLinear<number, number> = d3.scaleLinear() .range([violinWidth / 2, 0]) .domain([0, d3.max(data, datum => datum.length)]); // x is now the vertical axis because of the violin being a 90 degree rotated histogram const x: d3.ScaleLinear<number, number> = d3.scaleLinear() .range([height, this.margin.top]) .domain(domain) .nice(); const area: d3.Area<number[]> = d3.area() .curve(this.interpolation) .x(datum => x(datum['x0'])) .y0(violinWidth / 2) .y1(d => y(d.length)); const line: d3.Line<number[]> = d3.line() .curve(this.interpolation) .x(datum => x(datum['x0'])) .y(datum => y(datum.length)); const gPlus: d3.Selection<SVGGElement, {}, HTMLElement, {}> = gElement.append('g'); const gMinus: d3.Selection<SVGGElement, {}, HTMLElement, {}> = gElement.append('g'); const colorScale: d3.ScaleOrdinal<string, any> = this.measurandColorProviderService.getColorScaleForMeasurandGroup(this.chartData.dimensionalUnit); const violinColor: string = colorScale('0'); gPlus.append('path') .datum(data) .attr('class', 'd3chart-violin-area') .attr('d', area) .style('fill', violinColor); gPlus.append('path') .datum(data) .attr('class', 'd3chart-violin-outline') .attr('d', line) .style('stroke', violinColor); gMinus.append('path') .datum(data) .attr('class', 'd3chart-violin-area') .attr('d', area) .style('fill', violinColor); gMinus.append('path') .datum(data) .attr('class', 'd3chart-violin-outline') .attr('d', line) .style('stroke', violinColor); gPlus.attr('transform', `rotate(90, 0, 0) translate(0, -${violinWidth})`); gMinus.attr('transform', 'rotate(90, 0, 0) scale(1, -1)'); } private rotateLabel(labelElem: d3.Selection<SVGGElement, {}, null, undefined>): void { labelElem.style('text-anchor', 'start'); const childTextElem = labelElem.select('text'); const y = childTextElem.attr('y'); const transformBaseVal: SVGTransformList = labelElem.node().transform.baseVal; const transformMatrix: SVGMatrix = transformBaseVal.getItem(0).matrix; const translateX = transformMatrix.e; const translateY = transformMatrix.f; labelElem.attr('transform', `translate(${translateX - 30}, ${translateY}) rotate(45, 0, ${y})`); } }
the_stack
import { i18n } from '../i18n/i18n'; import { utils } from '../utils/utils'; import { EditorTag } from '../types/editor_tag'; import { DataType } from '../types/data_type'; import { MetaDataDTO } from './dto/meta_data_dto'; import { MetaEntity, MetaEntityAttr } from './meta_entity'; import { ValueEditor } from './value_editor'; /** * Represents a data model */ export class MetaData { /** The ID of the data mode. */ public id: string; /** The name of the data model. */ public name: string; /** The version of the data model. */ public version: string; /** The root entity. */ public rootEntity: MetaEntity; /** The list of value editors. */ public editors: ValueEditor[]; protected mainEntity: MetaEntity | null = null; protected displayFormats: Map<DataType, DisplayFormatDescriptor[]>; /** The default constructor. */ constructor() { this.id = '__none'; this.name = 'Empty model'; this.rootEntity = this.createEntity(); this.displayFormats = new Map<DataType, DisplayFormatDescriptor[]>(); } /** * Gets the main entity of model * @return The main entity. */ public getMainEntity(): MetaEntity { return this.mainEntity; } public createEntity(parent?: MetaEntity): MetaEntity { return new MetaEntity(parent); } public createEntityAttr(parent?: MetaEntity): MetaEntityAttr { return new MetaEntityAttr(parent); } public createValueEditor(): ValueEditor { return new ValueEditor(); } /** * Loads data model from JSON. * @param stringJson The JSON string. */ public loadFromJSON(stringJson: string) { let model = JSON.parse(stringJson); this.loadFromData(model); } /** * Loads data model from its JSON representation object. * @param data The JSON representation object. */ public loadFromData(data: MetaDataDTO) { this.id = data.id; this.name = data.name; this.version = data.vers; //Editors this.editors = new Array<ValueEditor>(); if (data.editors) { for(let i = 0; i < data.editors.length; i++) { let newEditor = this.createValueEditor(); newEditor.loadFromData(data.editors[i]); this.editors.push(newEditor); } } //rootEntity this.rootEntity.loadFromData(this, data.entroot); //DataFormats this.displayFormats = new Map<DataType, DisplayFormatDescriptor[]>(); if (data.displayFormats) { for (const dtypeStr in data.displayFormats) { const dtype = DataType[dtypeStr]; const formats: DisplayFormatDescriptor[] = data.displayFormats[dtypeStr] || new Array(); this.displayFormats.set(dtype, formats); } } } /** * Gets the display formats. * @returns The display formats. */ public getDisplayFormats(): Map<DataType, DisplayFormatDescriptor[]> { return this.displayFormats; } /** * Gets the display formats for type * @param type The type * @returns An array of display formats */ public getDisplayFormatsForType(type: DataType): DisplayFormatDescriptor[] { if (this.displayFormats.has(type)) { return this.displayFormats.get(type); } return []; } /** * Gets the default display format for the provided type * @param type The type * @returns The default type format or null */ public getDefaultFormat(type: DataType): DisplayFormatDescriptor | null { if (this.displayFormats.has(type)) { return this.displayFormats.get(type).filter(f => f.isdef)[0]; } return null; } /** * Sets data to data model. * @param model Its JSON representation object or JSON string. */ public setData(model: MetaDataDTO | string) { if (typeof model === 'string') { this.loadFromJSON(model); } else { this.loadFromData(model); } } /** * Checks wether the data model is empty. * @returns `true` if the data model is empty, otherwise `false`. */ public isEmpty(): boolean { return this.rootEntity.subEntities.length === 0 && this.rootEntity.attributes.length === 0; } /** * Gets ID of the data model. * @returns The ID. */ public getId(): string { return this.id; } /** * Gets name of the data model. * @returns The name. */ public getName(): string { return this.name; } /** * Gets root entity of the data model. * @returns The root entity. */ public getRootEntity(): MetaEntity { return this.rootEntity; } /** * Finds editor by its ID. * @param editorId The editor ID. * @returns The value editor or `null`. */ public getEditorById(editorId: string): ValueEditor | null { for(let editor of this.editors) { if (editor.id === editorId) { return editor; } } return null; } /** * Gets entity attribute by its ID. * This function runs through all attributes inside specified model (it's root entity and all its sub-entities). * @param attrId The attribute ID. * @returns The attribute or `null`. */ public getAttributeById(attrId: string): MetaEntityAttr | null { let attr = this.getEntityAttrById(this.getRootEntity(), attrId); if (!attr) { return null; } return attr; } /** * Checks wether attribute contains such property. * @param attrId The attribute ID. * @param propName The property name. * @returns `true` if the attribute contains the property, otherwise `false`. */ public checkAttrProperty(attrId: string, propName: string) : boolean { let attribute = this.getAttributeById(attrId); if (attribute) { if (typeof attribute[propName] === 'undefined') { throw 'No such property: ' + propName; } if (attribute[propName]) { return true; } else if (attribute.lookupAttr) { attrId = attribute.lookupAttr; attribute = this.getAttributeById(attrId); return attribute && attribute[propName]; } else { return false; } } else return false; } /** * Gets entity attribute by its ID. * This function runs through all attributes inside specified entity and all its sub-entities. * @param entity * @param attrId * @returns The attribute or `null`. */ public getEntityAttrById(entity: MetaEntity, attrId: string): MetaEntityAttr | null { let idx: number; if (entity.attributes) { let attrCount = entity.attributes.length; for (idx = 0; idx < attrCount; idx++) { if (entity.attributes[idx].id == attrId) { return entity.attributes[idx]; } } } let res: MetaEntityAttr; if (entity.subEntities) { let subEntityCount = entity.subEntities.length; for (idx = 0; idx < subEntityCount; idx++) { res = this.getEntityAttrById(entity.subEntities[idx], attrId); if (res) return res; } } return null } private listByEntityWithFilter(entity: MetaEntity, filterFunc: (ent: MetaEntity, attr: MetaEntityAttr) => boolean): MetaEntity[] { let result = new Array<MetaEntity>(); let caption; let ent = null; if (entity.subEntities) { let subEntityCount = entity.subEntities.length; for (let entIdx = 0; entIdx < subEntityCount; entIdx++) { ent = entity.subEntities[entIdx]; if (!filterFunc || filterFunc(ent, null)) { caption = i18n.getText('Entities', ent.name); if (!caption) { caption = ent.caption; } let newEnt = utils.assign(this.createEntity(), { id: ent.name, text: caption, items: [], isEntity: true }); newEnt.items = this.listByEntityWithFilter(ent, filterFunc); if (newEnt.items.length > 0) result.push(newEnt); } } } let attr = null; if (entity.attributes) { let attrCount = entity.attributes.length; for (let attrIdx = 0; attrIdx < attrCount; attrIdx++) { attr = entity.attributes[attrIdx]; if (!filterFunc || filterFunc(entity, attr)) { caption = i18n.getText('Attributes', attr.id); if (!caption) caption = attr.caption; let newEnt = utils.assign(this.createEntity(), { id: attr.id, text: caption, dataType: attr.dataType }); result.push(newEnt); } } } return result; } private listByEntity(entity: MetaEntity, opts, filterFunc: (ent: MetaEntity, attr: MetaEntityAttr) => boolean) { opts = opts || {}; let resultEntities = []; let resultAttributes = []; let caption: string; let ent: MetaEntity = null; if (entity.subEntities) { let subEntityCount = entity.subEntities.length; for (let entIdx = 0; entIdx < subEntityCount; entIdx++) { ent = entity.subEntities[entIdx]; if (!filterFunc || filterFunc(ent, null)) { caption = i18n.getText('Entities', ent.name) || ent.caption; let newEnt = utils.assign(this.createEntity(), { id: ent.name, text: caption, items: [], isEntity: true, description: ent.description }); let newOpts = utils.assign({}, opts); newOpts.includeRootData = false; newEnt.items = this.listByEntity(ent, newOpts, filterFunc); if (newEnt.items.length > 0) { resultEntities.push(newEnt); } } } } let attr:MetaEntityAttr = null; if (entity.attributes) { let attrCount = entity.attributes.length; for (let attrIdx = 0; attrIdx < attrCount; attrIdx++) { attr = entity.attributes[attrIdx]; if (!filterFunc || filterFunc(entity, attr)) { caption = i18n.getText('Attributes', attr.id) || attr.caption; resultAttributes.push(utils.assign(this.createEntityAttr(entity), { id: attr.id, text: caption, dataType: attr.dataType, lookupAttr: attr.lookupAttr, description: attr.description })); } } } let sortCheck = (a, b): number => { if (a.text.toLowerCase() == b.text.toLowerCase()) { return 0; } if (a.text.toLowerCase() > b.text.toLowerCase()) { return 1; } return -1; } if (opts.sortEntities) { resultEntities.sort(sortCheck); resultAttributes.sort(sortCheck); } let result; if (!opts.attrPlacement || opts.attrPlacement == 0) { result = resultEntities.concat(resultAttributes); } else { result = resultAttributes.concat(resultEntities); } if (opts.attrPlacement == 2) { result.sort(sortCheck); } if (opts.includeRootData) { caption = i18n.getText('Entities', entity.name); if (!caption) caption = entity.caption; return { id: entity.name, text: caption, items: result }; } else { return result; } } /** * Clears data model. */ public clear() { this.rootEntity = this.createEntity(); this.editors = []; this.version = ''; } /** * Add default value editors. */ public addDefaultValueEditors() { let ve: ValueEditor; ve = this.addOrUpdateValueEditor('_DTE', EditorTag.Edit, DataType.String); ve.defValue = ''; this.addOrUpdateValueEditor('_DPDE', EditorTag.DateTime, DataType.DateTime); this.addOrUpdateValueEditor('_DPTE', EditorTag.DateTime, DataType.DateTime); } /** * Add or update a value editor. * @param id The id. * @param tag The tag. * @param resType The result type. * @returns The value editor. */ public addOrUpdateValueEditor(id: string, tag: EditorTag, resType: DataType): ValueEditor { let ve = utils.findItemById(this.editors, id); if (!ve) { ve = this.createValueEditor(); ve.id = id; this.editors.push(ve); } ve.tag = tag; ve.resType = resType; return ve; } /** * Gets entities tree. * @param opts The options. * @param filterFunc The filter function. * Takes two parameters, Entity and EntityAttr (second parameter will be null for entities), and returns boolean (true if the corresponding entity or attribute). * @returns The tree of the entities and their attributes according to options and the filter function */ public getEntitiesTree(opts, filterFunc?: (ent: MetaEntity, attr: MetaEntityAttr) => boolean) { return this.listByEntity(this.getRootEntity(), opts, filterFunc); } /** * Gets entities tree due to filter. * @param filterFunc The filter function. * Takes two parameters, Entity and EntityAttr (second parameter will be null for entities), and returns boolean (true if the corresponding entity or attribute). * @returns The tree of the entities and their attributes according to the filter function */ public getEntitiesTreeWithFilter(filterFunc: (ent: MetaEntity, attr: MetaEntityAttr) => boolean) { return this.listByEntityWithFilter(this.getRootEntity(), filterFunc); } /** * Finds full entity path by attribute * @param attrId The attribute id. * @param sep The separator. * @returns The path. */ public getFullEntityPathByAttr(attrId: string, sep: string) : string { sep = sep || ' '; return this.getEntityPathByAttr(this.getRootEntity(), attrId, sep, true); } /** * Finds entity path by attribute * @param entity The entity. * @param attrId The attribute id. * @param sep The separator. * @param root The root option. * @returns The path. */ public getEntityPathByAttr(entity: MetaEntity, attrId: string, sep: string, root: boolean): string { if(!entity) return ''; sep = sep || ' '; let entityCaption = ''; if(entity.caption && !root) { let entityText = i18n.getText('Entities', entity.caption); entityCaption = entityText ? entityText : entity.caption; } if(entity.attributes) { let attrCount = entity.attributes.length; for (let i = 0; i < attrCount; i++) { if (entity.attributes[i].id == attrId) { return entityCaption; } } } if(entity.subEntities) { let subEntityCount = entity.subEntities.length; for (let i = 0; i < subEntityCount; i++) { let ent = entity.subEntities[i]; let res = this.getEntityPathByAttr(ent, attrId, sep, false); if (res !== '') { if (entityCaption !== '') res = entityCaption + sep + res; return res; } } } return ''; } /** * Gets the attribute text. * @param attr The attribute. * @param format The format. * @returns Formatted text. */ public getAttributeText(attr: MetaEntityAttr, format: string): string { let attrText = i18n.getText('Attributes', attr.id); if (!attrText) { attrText = attr.caption; } if (!format) { return attrText; } let result = ''; let entityPath = this.getFullEntityPathByAttr(attr.id, ' '); if(entityPath) { result = format.replace(new RegExp('{attr}', 'g'), attrText); result = result.replace(new RegExp('{entity}', 'g'), entityPath); } else { result = attrText; } return result.trim(); } /** * Scans model's entity tree and calls the callback functions for each attribute and entity. * @param processAttribute The callback function which is called for each attribute in model's entity tree. * The processed attribute is passed in the first function parameter. * @param processEntity The callback function which is called for each entity in tree. * The processed entity is passed in the first function parameter. */ public runThroughEntities( processAttribute?: (attr: MetaEntityAttr, opts: any) => void , processEntity?: (entity: MetaEntity, opts: any) => void) { this.getRootEntity().scan(processAttribute, processEntity); } /** * Finds first attribute by filter. * @param filterFunc The filter function. Takes EntityAttr object in parameter and returns boolean */ public getFirstAttributeByFilter(filterFunc: (attr: MetaEntityAttr) => boolean): MetaEntityAttr { let res = null; this.runThroughEntities(function (attr, opts) { if (filterFunc(attr)) { opts.stop = true; res = attr; } }, null); return res; } } export interface DisplayFormatDescriptor { name: string; format: string; isdef?: boolean; }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [mediaconnect](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awselementalmediaconnect.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Mediaconnect extends PolicyStatement { public servicePrefix = 'mediaconnect'; /** * Statement provider for service [mediaconnect](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awselementalmediaconnect.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); } /** * Grants permission to add media streams to any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-mediastreams.html */ public toAddFlowMediaStreams() { return this.to('AddFlowMediaStreams'); } /** * Grants permission to add outputs to any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-outputs.html */ public toAddFlowOutputs() { return this.to('AddFlowOutputs'); } /** * Grants permission to add sources to any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-source.html */ public toAddFlowSources() { return this.to('AddFlowSources'); } /** * Grants permission to add VPC interfaces to any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-vpcinterfaces.html */ public toAddFlowVpcInterfaces() { return this.to('AddFlowVpcInterfaces'); } /** * Grants permission to create flows * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows.html */ public toCreateFlow() { return this.to('CreateFlow'); } /** * Grants permission to delete flows * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn.html */ public toDeleteFlow() { return this.to('DeleteFlow'); } /** * Grants permission to display the details of a flow including the flow ARN, name, and Availability Zone, as well as details about the source, outputs, and entitlements * * Access Level: Read * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn.html */ public toDescribeFlow() { return this.to('DescribeFlow'); } /** * Grants permission to display the details of an offering * * Access Level: Read * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-offerings-offeringarn.html */ public toDescribeOffering() { return this.to('DescribeOffering'); } /** * Grants permission to display the details of a reservation * * Access Level: Read * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-reservations-reservationarn.html */ public toDescribeReservation() { return this.to('DescribeReservation'); } /** * Grants permission to grant entitlements on any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-entitlements.html */ public toGrantFlowEntitlements() { return this.to('GrantFlowEntitlements'); } /** * Grants permission to display a list of all entitlements that have been granted to the account * * Access Level: List * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-entitlements.html */ public toListEntitlements() { return this.to('ListEntitlements'); } /** * Grants permission to display a list of flows that are associated with this account * * Access Level: List * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows.html */ public toListFlows() { return this.to('ListFlows'); } /** * Grants permission to display a list of all offerings that are available to the account in the current AWS Region * * Access Level: List * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-offerings.html */ public toListOfferings() { return this.to('ListOfferings'); } /** * Grants permission to display a list of all reservations that have been purchased by the account in the current AWS Region * * Access Level: List * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-reservations.html */ public toListReservations() { return this.to('ListReservations'); } /** * Grants permission to display a list of all tags associated with a resource * * Access Level: Read * * https://docs.aws.amazon.com/mediaconnect/latest/api/tags-resourcearn.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to purchase an offering * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-offerings-offeringarn.html */ public toPurchaseOffering() { return this.to('PurchaseOffering'); } /** * Grants permission to remove media streams from any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-mediastreams-mediastreamname.html */ public toRemoveFlowMediaStream() { return this.to('RemoveFlowMediaStream'); } /** * Grants permission to remove outputs from any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-outputs-outputarn.html */ public toRemoveFlowOutput() { return this.to('RemoveFlowOutput'); } /** * Grants permission to remove sources from any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-source-sourcearn.html */ public toRemoveFlowSource() { return this.to('RemoveFlowSource'); } /** * Grants permission to remove VPC interfaces from any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-vpcinterfaces-vpcinterfacename.html */ public toRemoveFlowVpcInterface() { return this.to('RemoveFlowVpcInterface'); } /** * Grants permission to revoke entitlements on any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-entitlements-entitlementarn.html */ public toRevokeFlowEntitlement() { return this.to('RevokeFlowEntitlement'); } /** * Grants permission to start flows * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-start-flowarn.html */ public toStartFlow() { return this.to('StartFlow'); } /** * Grants permission to stop flows * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-stop-flowarn.html */ public toStopFlow() { return this.to('StopFlow'); } /** * Grants permission to associate tags with resources * * Access Level: Tagging * * https://docs.aws.amazon.com/mediaconnect/latest/api/tags-resourcearn.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove tags from resources * * Access Level: Tagging * * https://docs.aws.amazon.com/mediaconnect/latest/api/tags-resourcearn.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update flows * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn.html */ public toUpdateFlow() { return this.to('UpdateFlow'); } /** * Grants permission to update entitlements on any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-entitlements-entitlementarn.html */ public toUpdateFlowEntitlement() { return this.to('UpdateFlowEntitlement'); } /** * Grants permission to update media streams on any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-mediastreams-mediastreamname.html */ public toUpdateFlowMediaStream() { return this.to('UpdateFlowMediaStream'); } /** * Grants permission to update outputs on any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-outputs-outputarn.html */ public toUpdateFlowOutput() { return this.to('UpdateFlowOutput'); } /** * Grants permission to update the source of any flow * * Access Level: Write * * https://docs.aws.amazon.com/mediaconnect/latest/api/v1-flows-flowarn-source-sourcearn.html */ public toUpdateFlowSource() { return this.to('UpdateFlowSource'); } protected accessLevelList: AccessLevelList = { "Write": [ "AddFlowMediaStreams", "AddFlowOutputs", "AddFlowSources", "AddFlowVpcInterfaces", "CreateFlow", "DeleteFlow", "GrantFlowEntitlements", "PurchaseOffering", "RemoveFlowMediaStream", "RemoveFlowOutput", "RemoveFlowSource", "RemoveFlowVpcInterface", "RevokeFlowEntitlement", "StartFlow", "StopFlow", "UpdateFlow", "UpdateFlowEntitlement", "UpdateFlowMediaStream", "UpdateFlowOutput", "UpdateFlowSource" ], "Read": [ "DescribeFlow", "DescribeOffering", "DescribeReservation", "ListTagsForResource" ], "List": [ "ListEntitlements", "ListFlows", "ListOfferings", "ListReservations" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type Entitlement to the statement * * https://docs.aws.amazon.com/mediaconnect/latest/ug/entitlements.html * * @param flowId - Identifier for the flowId. * @param entitlementName - Identifier for the entitlementName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onEntitlement(flowId: string, entitlementName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mediaconnect:${Region}:${Account}:entitlement:${FlowId}:${EntitlementName}'; arn = arn.replace('${FlowId}', flowId); arn = arn.replace('${EntitlementName}', entitlementName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type Flow to the statement * * https://docs.aws.amazon.com/mediaconnect/latest/ug/flows.html * * @param flowId - Identifier for the flowId. * @param flowName - Identifier for the flowName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onFlow(flowId: string, flowName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mediaconnect:${Region}:${Account}:flow:${FlowId}:${FlowName}'; arn = arn.replace('${FlowId}', flowId); arn = arn.replace('${FlowName}', flowName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type Output to the statement * * https://docs.aws.amazon.com/mediaconnect/latest/ug/outputs.html * * @param outputId - Identifier for the outputId. * @param outputName - Identifier for the outputName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onOutput(outputId: string, outputName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mediaconnect:${Region}:${Account}:output:${OutputId}:${OutputName}'; arn = arn.replace('${OutputId}', outputId); arn = arn.replace('${OutputName}', outputName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type Source to the statement * * https://docs.aws.amazon.com/mediaconnect/latest/ug/sources.html * * @param sourceId - Identifier for the sourceId. * @param sourceName - Identifier for the sourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onSource(sourceId: string, sourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mediaconnect:${Region}:${Account}:source:${SourceId}:${SourceName}'; arn = arn.replace('${SourceId}', sourceId); arn = arn.replace('${SourceName}', sourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import { $Values } from 'utility-types'; import { Channel } from 'redux-saga'; import { all, call, fork, put, takeLatest } from 'redux-saga/effects'; import { getExtensionHash, Extension, ClientType, ROOT_DOMAIN_ID, ColonyClient, ColonyRole, TokenClientType, } from '@colony/colony-js'; import { AddressZero } from 'ethers/constants'; import { poll } from 'ethers/utils'; import { ContextModule, TEMP_getContext } from '~context/index'; import { getLoggedInUser, ProcessedColonyQuery, ProcessedColonyQueryVariables, ProcessedColonyDocument, SubscribeToColonyMutation, SubscribeToColonyMutationVariables, SubscribeToColonyDocument, NetworkExtensionVersionQuery, NetworkExtensionVersionQueryVariables, NetworkExtensionVersionDocument, cacheUpdates, } from '~data/index'; import { ActionTypes, Action, AllActions } from '~redux/index'; import { putError, takeFrom } from '~utils/saga/effects'; import { TxConfig } from '~types/index'; import { transactionAddParams, transactionReady, transactionPending, } from '../../core/actionCreators'; import { createTransaction, createTransactionChannels } from '../../core/sagas'; interface ChannelDefinition { channel: Channel<any>; index: number; id: string; } function* colonyRestartDeployment({ payload: { colonyAddress }, meta, }: Action<ActionTypes.COLONY_DEPLOYMENT_RESTART>) { try { const { walletAddress, username } = yield getLoggedInUser(); const apolloClient = TEMP_getContext(ContextModule.ApolloClient); const colonyManager = TEMP_getContext(ContextModule.ColonyManager); const { networkClient } = colonyManager; let startingIndex = 7; const channelNames: string[] = []; /* * Validate the required values */ if (!username) { throw new Error( `The user does not have a profile associated, hence cannot run the Colony Restart Deployment flow`, ); } if (!colonyAddress) { throw new Error( `The colony adress was not provided to the Colony Restart Deployment flow`, ); } const colonyClient: ColonyClient = yield networkClient.getColonyClient( colonyAddress, ); const { tokenClient } = colonyClient; const tokenOwnerAddress = yield tokenClient.owner(); /* * Check if the user **actually** has permissions to restart the colony * deployment flow, on the colony home we just do a superficial check * * Note that this accounts for user intreacting with the contracts in the * time between creation and re-starting the deployment flow, hence we * need to be more granular in our permissions checks */ const hasRootRole = yield colonyClient.hasUserRole( walletAddress, ROOT_DOMAIN_ID, ColonyRole.Root, ); const hasAdministrationRole = yield colonyClient.hasUserRole( walletAddress, ROOT_DOMAIN_ID, ColonyRole.Administration, ); const hasRecoveryRole = yield colonyClient.hasUserRole( walletAddress, ROOT_DOMAIN_ID, ColonyRole.Recovery, ); const isTokenOwner = tokenOwnerAddress === walletAddress; if ( !hasRootRole || !hasAdministrationRole || !hasRecoveryRole || !isTokenOwner ) { throw new Error( `User does not have the required permissions to run the Colony Restart Deployment flow`, ); } /* * Check if the token authority is set up */ if (tokenClient.tokenClientType === TokenClientType.Colony) { const tokenAuthority = yield tokenClient.authority(); if (tokenAuthority === AddressZero) { startingIndex -= 2; channelNames.push('deployTokenAuthority'); channelNames.push('setTokenAuthority'); channelNames.push('setOwner'); } } /* * This is an optional step, but since we run through this flow, we can also * manually start it, to provide the user with a better overall colony experience */ const oneTxExtensionAddress = yield networkClient.getExtensionInstallation( getExtensionHash(Extension.OneTxPayment), colonyAddress, ); /* * The OneTxPayment extension is not set up, we add it to the flow */ if (oneTxExtensionAddress === AddressZero) { startingIndex -= 3; channelNames.push('deployOneTx'); channelNames.push('setOneTxRoleAdministration'); channelNames.push('setOneTxRoleFunding'); } else { /* * OneTxPayment **is** set up, so we just need to check if we can, and need * to set its roles */ if ( yield colonyClient.hasUserRole( oneTxExtensionAddress, ROOT_DOMAIN_ID, ColonyRole.Administration, ) ) { startingIndex -= 1; channelNames.push('setOneTxRoleAdministration'); } if ( yield colonyClient.hasUserRole( oneTxExtensionAddress, ROOT_DOMAIN_ID, ColonyRole.Funding, ) ) { startingIndex -= 1; channelNames.push('setOneTxRoleFunding'); } } const channels: { [id: string]: ChannelDefinition; } = yield call( createTransactionChannels, meta.id, channelNames, startingIndex, ); const { deployTokenAuthority, setTokenAuthority, deployOneTx, setOneTxRoleAdministration, setOneTxRoleFunding, setOwner, } = channels; const createGroupedTransaction = ( { id, index }: $Values<typeof channels>, config: TxConfig, ) => fork(createTransaction, id, { ...config, group: { key: 'restartColonyDeployment', id: meta.id, index, }, }); if (deployTokenAuthority) { yield createGroupedTransaction(deployTokenAuthority, { context: ClientType.ColonyClient, methodName: 'deployTokenAuthority', identifier: colonyAddress, ready: false, }); yield createGroupedTransaction(setTokenAuthority, { context: ClientType.TokenClient, methodName: 'setAuthority', identifier: colonyAddress, ready: false, }); yield createGroupedTransaction(setOwner, { context: ClientType.TokenClient, methodName: 'setOwner', identifier: colonyAddress, ready: false, }); } if (deployOneTx) { yield createGroupedTransaction(deployOneTx, { context: ClientType.ColonyClient, methodName: 'installExtension', identifier: colonyAddress, ready: false, }); } if (setOneTxRoleAdministration) { yield createGroupedTransaction(setOneTxRoleAdministration, { context: ClientType.ColonyClient, methodContext: 'setOneTxRoles', methodName: 'setAdministrationRoleWithProofs', identifier: colonyAddress, ready: false, }); } if (setOneTxRoleFunding) { yield createGroupedTransaction(setOneTxRoleFunding, { context: ClientType.ColonyClient, methodContext: 'setOneTxRoles', methodName: 'setFundingRoleWithProofs', identifier: colonyAddress, ready: false, }); } /* * Wait until all transactions are created. */ yield all( Object.keys(channels).map((id) => takeFrom(channels[id].channel, ActionTypes.TRANSACTION_CREATED), ), ); if (deployTokenAuthority) { /* * Deploy Token Authority */ const tokenLockingAddress = yield networkClient.getTokenLocking(); yield put( transactionAddParams(deployTokenAuthority.id, [ tokenClient.address, [tokenLockingAddress], ]), ); yield put(transactionReady(deployTokenAuthority.id)); const { payload: { deployedContractAddress }, } = yield takeFrom( deployTokenAuthority.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); /* * Set Token authority (to deployed Token Authority) */ yield put( transactionAddParams(setTokenAuthority.id, [deployedContractAddress]), ); yield put(transactionReady(setTokenAuthority.id)); yield takeFrom( setTokenAuthority.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); /* * Set the Token's owner */ yield put(transactionAddParams(setOwner.id, [colonyAddress])); yield put(transactionReady(setOwner.id)); yield takeFrom(setOwner.channel, ActionTypes.TRANSACTION_SUCCEEDED); } /* * Deploy OneTx */ if (deployOneTx) { const { data: { networkExtensionVersion }, } = yield apolloClient.query< NetworkExtensionVersionQuery, NetworkExtensionVersionQueryVariables >({ query: NetworkExtensionVersionDocument, variables: { extensionId: Extension.OneTxPayment, }, fetchPolicy: 'network-only', }); const [latestOneTxDepoyment] = networkExtensionVersion; yield put( transactionAddParams(deployOneTx.id, [ getExtensionHash(Extension.OneTxPayment), latestOneTxDepoyment?.version || 0, ]), ); yield put(transactionReady(deployOneTx.id)); yield takeFrom(deployOneTx.channel, ActionTypes.TRANSACTION_SUCCEEDED); /* * Set OneTx administration role */ yield put(transactionPending(setOneTxRoleAdministration.id)); const oneTxPaymentExtension = yield poll( async () => { try { const client = await colonyManager.getClient( ClientType.OneTxPaymentClient, colonyAddress, ); return client; } catch (err) { return undefined; } }, { timeout: 30000, }, ); const extensionAddress = oneTxPaymentExtension.address; yield put( transactionAddParams(setOneTxRoleAdministration.id, [ extensionAddress, ROOT_DOMAIN_ID, true, ]), ); yield put(transactionReady(setOneTxRoleAdministration.id)); yield takeFrom( setOneTxRoleAdministration.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); /* * Set OneTx funding role */ yield put( transactionAddParams(setOneTxRoleFunding.id, [ extensionAddress, ROOT_DOMAIN_ID, true, ]), ); yield put(transactionReady(setOneTxRoleFunding.id)); yield colonyManager.setColonyClient(colonyAddress); yield takeFrom( setOneTxRoleFunding.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); } yield apolloClient.query< ProcessedColonyQuery, ProcessedColonyQueryVariables >({ query: ProcessedColonyDocument, variables: { address: colonyAddress, }, fetchPolicy: 'network-only', }); yield apolloClient.mutate< SubscribeToColonyMutation, SubscribeToColonyMutationVariables >({ mutation: SubscribeToColonyDocument, variables: { input: { colonyAddress }, }, update: cacheUpdates.subscribeToColony(colonyAddress), }); yield put<AllActions>({ type: ActionTypes.COLONY_DEPLOYMENT_RESTART_SUCCESS, meta, }); } catch (error) { yield putError(ActionTypes.COLONY_DEPLOYMENT_RESTART_ERROR, error, meta); console.error('saga err', error); } } export default function* colonyFinishDeploymentSaga() { yield takeLatest( ActionTypes.COLONY_DEPLOYMENT_RESTART, colonyRestartDeployment, ); }
the_stack
import { checkEqual } from '../check.ts'; import { Profile } from '../config.ts'; import { GraphqlQuery } from './graphql.ts'; export class CfGqlClient { static DEBUG = false; static URL_TRANSFORMER: (url: string) => string = v => v; readonly profile: Profile; constructor(profile: Profile) { this.profile = profile; } async getDurableObjectPeriodicMetricsByDate(startDateInclusive: string, endDateInclusive: string): Promise<CfGqlResult<GetDurableObjectPeriodicMetricsByDateRow>> { return await _getDurableObjectPeriodicMetricsByDate(this.profile, startDateInclusive, endDateInclusive); } async getDurableObjectStorageByDate(startDateInclusive: string, endDateInclusive: string): Promise<CfGqlResult<GetDurableObjectStorageByDateRow>> { return await _getDurableObjectStorageByDate(this.profile, startDateInclusive, endDateInclusive); } async getDurableObjectInvocationsByDate(startDateInclusive: string, endDateInclusive: string): Promise<CfGqlResult<GetDurableObjectInvocationsByDateRow>> { return await _getDurableObjectInvocationsByDate(this.profile, startDateInclusive, endDateInclusive); } } export interface CfGqlResultInfo { readonly fetchMillis: number; readonly cost: number; readonly budget: number; } export interface CfGqlResult<T> { readonly info: CfGqlResultInfo; readonly rows: readonly T[]; } // // deno-lint-ignore no-explicit-any async function query(profile: Profile, queryFn: (q: GraphqlQuery) => void, variables: Record<string, unknown>): Promise<any> { const { accountId, apiToken } = profile; const q = GraphqlQuery.create() .scalar('cost') .object('viewer') .scalar('budget') .object('accounts').argObject('filter', 'accountTag', accountId) .scalar('accountTag'); queryFn(q); const query = q.top().toString(); if (CfGqlClient.DEBUG) console.log(query); const reqObj = { query, variables }; const body = JSON.stringify(reqObj); const start = Date.now(); const url = CfGqlClient.URL_TRANSFORMER('https://api.cloudflare.com/client/v4/graphql'); const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json; charset=utf-8', 'Authorization': `Bearer ${apiToken}` }, body }); const fetchMillis = Date.now() - start; if (CfGqlClient.DEBUG) console.log(res); if (res.status !== 200) throw new Error(`Bad res.status: ${res.status}, expected 200, text=${await res.text()}`); const contentType = res.headers.get('content-type'); if (contentType !== 'application/json') throw new Error(`Bad res.contentType: ${contentType}, expected application/json, found ${contentType}, text=${await res.text()}`); const resObj = await res.json(); resObj.fetchMillis = fetchMillis; if (CfGqlClient.DEBUG) console.log(JSON.stringify(resObj, undefined, 2)); if (isGqlErrorResponse(resObj)) { throw new Error(resObj.errors.map(computeGqlErrorString).join(', ')); } return resObj; } interface GqlError { readonly message: string; readonly path: readonly string[] | null; readonly extensions: Record<string, string>; } interface GqlErrorResponse { readonly data: null, readonly errors: readonly GqlError[]; } // deno-lint-ignore no-explicit-any function isGqlErrorResponse(obj: any): obj is GqlErrorResponse { return typeof obj === 'object' && obj.data === null && Array.isArray(obj.errors); } function computeGqlErrorString(error: GqlError) { const pieces = [ error.message ]; if (error.path) pieces.push(`(${error.path.join('/')})`); if (error.extensions.code) pieces.push(`(code=${error.extensions.code})`); return pieces.join(' '); } //#region GetDurableObjectPeriodicMetricsByDate export interface GetDurableObjectPeriodicMetricsByDateRow { readonly date: string, readonly namespaceId: string, readonly maxActiveWebsocketConnections: number, /** Sum of active time - microseconds */ readonly sumActiveTime: number, readonly sumCpuTime: number, readonly sumExceededCpuErrors: number, readonly sumExceededMemoryErrors: number, readonly sumFatalInternalErrors: number, readonly sumInboundWebsocketMsgCount: number, readonly sumOutboundWebsocketMsgCount: number, readonly sumStorageDeletes: number, readonly sumStorageReadUnits: number, readonly sumStorageWriteUnits: number, readonly sumSubrequests: number, } async function _getDurableObjectPeriodicMetricsByDate(profile: Profile, startDateInclusive: string, endDateInclusive: string): Promise<CfGqlResult<GetDurableObjectPeriodicMetricsByDateRow>> { const resObj = await query(profile, q => q.object('durableObjectsPeriodicGroups') .argLong('limit', 10000) .argRaw('filter', `{date_geq: $start, date_leq: $end}`) .argRaw('orderBy', `[date_ASC]`) .object('dimensions') .scalar('date') .scalar('namespaceId') .end() .object('max') .scalar('activeWebsocketConnections') .end() .object('sum') .scalar('activeTime') .scalar('cpuTime') .scalar('exceededCpuErrors') .scalar('exceededMemoryErrors') .scalar('fatalInternalErrors') .scalar('inboundWebsocketMsgCount') .scalar('outboundWebsocketMsgCount') .scalar('storageDeletes') .scalar('storageReadUnits') .scalar('storageWriteUnits') .scalar('subrequests'), { start: startDateInclusive, end: endDateInclusive }); interface GqlResponse { data: { cost: number, viewer: { budget: number, accounts: { accountTag: string, durableObjectsPeriodicGroups: { dimensions: { date: string, namespaceId: string, }, max: { activeWebsocketConnections: number, }, sum: { activeTime: number, cpuTime: number, exceededCpuErrors: number, exceededMemoryErrors: number, fatalInternalErrors: number, inboundWebsocketMsgCount: number, outboundWebsocketMsgCount: number, storageDeletes: number, storageReadUnits: number, storageWriteUnits: number, subrequests: number, }, }[], }[], }, }, } const fetchMillis = resObj.fetchMillis; const res = resObj as GqlResponse; const cost = res.data.cost; const budget = res.data.viewer.budget; const rows: GetDurableObjectPeriodicMetricsByDateRow[] = []; for (const account of res.data.viewer.accounts) { checkEqual('account.accountTag', account.accountTag, profile.accountId); for (const group of account.durableObjectsPeriodicGroups) { const date = group.dimensions.date; const namespaceId = group.dimensions.namespaceId; const maxActiveWebsocketConnections = group.max.activeWebsocketConnections; const sumActiveTime = group.sum.activeTime; const sumCpuTime = group.sum.cpuTime; const sumExceededCpuErrors = group.sum.exceededCpuErrors; const sumExceededMemoryErrors = group.sum.exceededMemoryErrors; const sumFatalInternalErrors = group.sum.fatalInternalErrors; const sumInboundWebsocketMsgCount = group.sum.inboundWebsocketMsgCount; const sumOutboundWebsocketMsgCount = group.sum.outboundWebsocketMsgCount; const sumStorageDeletes = group.sum.storageDeletes; const sumStorageReadUnits = group.sum.storageReadUnits; const sumStorageWriteUnits = group.sum.storageWriteUnits; const sumSubrequests = group.sum.subrequests; rows.push({ date, namespaceId, maxActiveWebsocketConnections, sumActiveTime, sumCpuTime, sumExceededCpuErrors, sumExceededMemoryErrors, sumFatalInternalErrors, sumInboundWebsocketMsgCount, sumOutboundWebsocketMsgCount, sumStorageDeletes, sumStorageReadUnits, sumStorageWriteUnits, sumSubrequests, }); } } return { info: { fetchMillis, cost, budget }, rows }; } //#endregion //#region GetDurableObjectStorageByDate export interface GetDurableObjectStorageByDateRow { readonly date: string, readonly maxStoredBytes: number, } async function _getDurableObjectStorageByDate(profile: Profile, startDateInclusive: string, endDateInclusive: string): Promise<CfGqlResult<GetDurableObjectStorageByDateRow>> { const resObj = await query(profile, q => q.object('durableObjectsStorageGroups') .argLong('limit', 10000) .argRaw('filter', `{date_geq: $start, date_leq: $end}`) .argRaw('orderBy', `[date_ASC]`) .object('dimensions') .scalar('date') .end() .object('max') .scalar('storedBytes') .end(), { start: startDateInclusive, end: endDateInclusive }); interface GqlResponse { data: { cost: number, viewer: { budget: number, accounts: { accountTag: string, durableObjectsStorageGroups: { dimensions: { date: string, }, max: { storedBytes: number, }, }[], }[], }, }, } const fetchMillis = resObj.fetchMillis; const res = resObj as GqlResponse; const cost = res.data.cost; const budget = res.data.viewer.budget; const rows: GetDurableObjectStorageByDateRow[] = []; for (const account of res.data.viewer.accounts) { checkEqual('account.accountTag', account.accountTag, profile.accountId); for (const group of account.durableObjectsStorageGroups) { const date = group.dimensions.date; const maxStoredBytes = group.max.storedBytes; rows.push({ date, maxStoredBytes }); } } return { info: { fetchMillis, cost, budget }, rows }; } //#endregion //#region GetDurableObjectInvocationsByDate export interface GetDurableObjectInvocationsByDateRow { readonly date: string, readonly namespaceId: string, readonly avgSampleInterval: number, readonly sumRequests: number, } async function _getDurableObjectInvocationsByDate(profile: Profile, startDateInclusive: string, endDateInclusive: string): Promise<CfGqlResult<GetDurableObjectInvocationsByDateRow>> { const resObj = await query(profile, q => q.object('durableObjectsInvocationsAdaptiveGroups') .argLong('limit', 10000) .argRaw('filter', `{date_geq: $start, date_leq: $end}`) .argRaw('orderBy', `[date_ASC]`) .object('dimensions') .scalar('date') .scalar('namespaceId') .end() .object('avg') .scalar('sampleInterval') .end() .object('sum') .scalar('requests') .end(), { start: startDateInclusive, end: endDateInclusive }); interface GqlResponse { data: { cost: number, viewer: { budget: number, accounts: { accountTag: string, durableObjectsInvocationsAdaptiveGroups: { dimensions: { date: string, namespaceId: string, }, avg: { sampleInterval: number, }, sum: { requests: number, }, }[], }[], }, }, } const fetchMillis = resObj.fetchMillis; const res = resObj as GqlResponse; const cost = res.data.cost; const budget = res.data.viewer.budget; const rows: GetDurableObjectInvocationsByDateRow[] = []; for (const account of res.data.viewer.accounts) { checkEqual('account.accountTag', account.accountTag, profile.accountId); for (const group of account.durableObjectsInvocationsAdaptiveGroups) { const date = group.dimensions.date; const namespaceId = group.dimensions.namespaceId; const avgSampleInterval = group.avg.sampleInterval; const sumRequests = group.sum.requests; rows.push({ date, namespaceId, avgSampleInterval, sumRequests }); } } return { info: { fetchMillis, cost, budget }, rows }; } //#endregion
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [ram](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsresourceaccessmanager.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Ram extends PolicyStatement { public servicePrefix = 'ram'; /** * Statement provider for service [ram](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsresourceaccessmanager.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); } /** * Grants permission to accept the specified resource share invitation * * Access Level: Write * * Possible conditions: * - .ifShareOwnerAccountId() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_AcceptResourceShareInvitation.html */ public toAcceptResourceShareInvitation() { return this.to('AcceptResourceShareInvitation'); } /** * Grants permission to associate resource(s) and/or principal(s) to a resource share * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * - .ifResourceShareName() * - .ifAllowsExternalPrincipals() * - .ifPrincipal() * - .ifRequestedResourceType() * - .ifResourceArn() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_AssociateResourceShare.html */ public toAssociateResourceShare() { return this.to('AssociateResourceShare'); } /** * Grants permission to associate a Permission with a Resource Share * * Access Level: Write * * https://docs.aws.amazon.com/ram/latest/APIReference/API_AssociateResourceSharePermission.html */ public toAssociateResourceSharePermission() { return this.to('AssociateResourceSharePermission'); } /** * Grants permission to create a resource share with provided resource(s) and/or principal(s) * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifRequestedResourceType() * - .ifResourceArn() * - .ifRequestedAllowsExternalPrincipals() * - .ifPrincipal() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_CreateResourceShare.html */ public toCreateResourceShare() { return this.to('CreateResourceShare'); } /** * Grants permission to delete resource share * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * - .ifResourceShareName() * - .ifAllowsExternalPrincipals() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_DeleteResourceShare.html */ public toDeleteResourceShare() { return this.to('DeleteResourceShare'); } /** * Grants permission to disassociate resource(s) and/or principal(s) from a resource share * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * - .ifResourceShareName() * - .ifAllowsExternalPrincipals() * - .ifPrincipal() * - .ifRequestedResourceType() * - .ifResourceArn() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_DisassociateResourceShare.html */ public toDisassociateResourceShare() { return this.to('DisassociateResourceShare'); } /** * Grants permission to disassociate a Permission from a Resource Share * * Access Level: Write * * https://docs.aws.amazon.com/ram/latest/APIReference/API_DisassociateResourceSharePermission.html */ public toDisassociateResourceSharePermission() { return this.to('DisassociateResourceSharePermission'); } /** * Grants permission to access customer's organization and create a SLR in the customer's account * * Access Level: Permissions management * * https://docs.aws.amazon.com/ram/latest/APIReference/API_EnableSharingWithAwsOrganization.html */ public toEnableSharingWithAwsOrganization() { return this.to('EnableSharingWithAwsOrganization'); } /** * Grants permission to get the contents of an AWS RAM permission * * Access Level: Read * * Possible conditions: * - .ifPermissionArn() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_GetPermission.html */ public toGetPermission() { return this.to('GetPermission'); } /** * Grants permission to get the policies for the specified resources that you own and have shared * * Access Level: Read * * https://docs.aws.amazon.com/ram/latest/APIReference/API_GetResourcePolicies.html */ public toGetResourcePolicies() { return this.to('GetResourcePolicies'); } /** * Grants permission to get a set of resource share associations from a provided list or with a specified status of the specified type * * Access Level: Read * * https://docs.aws.amazon.com/ram/latest/APIReference/API_GetResourceShareAssociations.html */ public toGetResourceShareAssociations() { return this.to('GetResourceShareAssociations'); } /** * Grants permission to get resource share invitations by the specified invitation arn or those for the resource share * * Access Level: Read * * https://docs.aws.amazon.com/ram/latest/APIReference/API_GetResourceShareInvitations.html */ public toGetResourceShareInvitations() { return this.to('GetResourceShareInvitations'); } /** * Grants permission to get a set of resource shares from a provided list or with a specified status * * Access Level: Read * * https://docs.aws.amazon.com/ram/latest/APIReference/API_GetResourceShares.html */ public toGetResourceShares() { return this.to('GetResourceShares'); } /** * Grants permission to list the resources in a resource share that is shared with you but that the invitation is still pending for * * Access Level: Read * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ListPendingInvitationResources.html */ public toListPendingInvitationResources() { return this.to('ListPendingInvitationResources'); } /** * Grants permission to list the AWS RAM permissions * * Access Level: List * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ListPermissions.html */ public toListPermissions() { return this.to('ListPermissions'); } /** * Grants permission to list the principals that you have shared resources with or that have shared resources with you * * Access Level: List * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ListPrincipals.html */ public toListPrincipals() { return this.to('ListPrincipals'); } /** * Grants permission to list the Permissions associated with a Resource Share * * Access Level: List * * Possible conditions: * - .ifAwsResourceTag() * - .ifResourceShareName() * - .ifAllowsExternalPrincipals() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ListResourceSharePermissions.html */ public toListResourceSharePermissions() { return this.to('ListResourceSharePermissions'); } /** * Grants permission to list the shareable resource types supported by AWS RAM * * Access Level: List * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ListResourceTypes.html */ public toListResourceTypes() { return this.to('ListResourceTypes'); } /** * Grants permission to list the resources that you added to resource shares or the resources that are shared with you * * Access Level: List * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ListResources.html */ public toListResources() { return this.to('ListResources'); } /** * Grants permission to promote the specified resource share * * Access Level: Write * * https://docs.aws.amazon.com/ram/latest/APIReference/API_PromoteResourceShareCreatedFromPolicy.html */ public toPromoteResourceShareCreatedFromPolicy() { return this.to('PromoteResourceShareCreatedFromPolicy'); } /** * Grants permission to reject the specified resource share invitation * * Access Level: Write * * Possible conditions: * - .ifShareOwnerAccountId() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_RejectResourceShareInvitation.html */ public toRejectResourceShareInvitation() { return this.to('RejectResourceShareInvitation'); } /** * Grants permission to tag the specified resource share * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to untag the specified resource share * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update attributes of the resource share * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * - .ifResourceShareName() * - .ifAllowsExternalPrincipals() * - .ifRequestedAllowsExternalPrincipals() * * https://docs.aws.amazon.com/ram/latest/APIReference/API_UpdateResourceShare.html */ public toUpdateResourceShare() { return this.to('UpdateResourceShare'); } protected accessLevelList: AccessLevelList = { "Write": [ "AcceptResourceShareInvitation", "AssociateResourceShare", "AssociateResourceSharePermission", "CreateResourceShare", "DeleteResourceShare", "DisassociateResourceShare", "DisassociateResourceSharePermission", "PromoteResourceShareCreatedFromPolicy", "RejectResourceShareInvitation", "UpdateResourceShare" ], "Permissions management": [ "EnableSharingWithAwsOrganization" ], "Read": [ "GetPermission", "GetResourcePolicies", "GetResourceShareAssociations", "GetResourceShareInvitations", "GetResourceShares", "ListPendingInvitationResources" ], "List": [ "ListPermissions", "ListPrincipals", "ListResourceSharePermissions", "ListResourceTypes", "ListResources" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type resource-share to the statement * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ResourceShare.html * * @param resourcePath - Identifier for the resourcePath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifAllowsExternalPrincipals() * - .ifResourceShareName() */ public onResourceShare(resourcePath: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ram:${Region}:${Account}:resource-share/${ResourcePath}'; arn = arn.replace('${ResourcePath}', resourcePath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type resource-share-invitation to the statement * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ResourceShareInvitation.html * * @param resourcePath - Identifier for the resourcePath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifShareOwnerAccountId() */ public onResourceShareInvitation(resourcePath: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ram:${Region}:${Account}:resource-share-invitation/${ResourcePath}'; arn = arn.replace('${ResourcePath}', resourcePath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type permission to the statement * * https://docs.aws.amazon.com/ram/latest/APIReference/API_ResourceSharePermissionDetail.html * * @param resourcePath - Identifier for the resourcePath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifPermissionArn() * - .ifPermissionResourceType() */ public onPermission(resourcePath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:ram::${Account}:permission/${ResourcePath}'; arn = arn.replace('${ResourcePath}', resourcePath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access based on resource shares that allow or deny sharing with external principals. For example, specify true if the action can only be performed on resource shares that allow sharing with external principals. External principals are AWS accounts that are outside of its AWS organization * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to actions: * - .toAssociateResourceShare() * - .toDeleteResourceShare() * - .toDisassociateResourceShare() * - .toListResourceSharePermissions() * - .toUpdateResourceShare() * * Applies to resource types: * - resource-share * * @param value `true` or `false`. **Default:** `true` */ public ifAllowsExternalPrincipals(value?: boolean) { return this.if(`AllowsExternalPrincipals`, (typeof value !== 'undefined' ? value : true), 'Bool'); } /** * Filters access based on the specified Permission ARN * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to actions: * - .toGetPermission() * * Applies to resource types: * - permission * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifPermissionArn(value: string | string[], operator?: Operator | string) { return this.if(`PermissionArn`, value, operator || 'ArnLike'); } /** * Filters access based on permissions of specified resource type * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to resource types: * - permission * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifPermissionResourceType(value: string | string[], operator?: Operator | string) { return this.if(`PermissionResourceType`, value, operator || 'StringLike'); } /** * Filters access based on the format of the specified principal * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to actions: * - .toAssociateResourceShare() * - .toCreateResourceShare() * - .toDisassociateResourceShare() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifPrincipal(value: string | string[], operator?: Operator | string) { return this.if(`Principal`, value, operator || 'StringLike'); } /** * Filters access based on the specified value for 'allowExternalPrincipals'. External principals are AWS accounts that are outside of its AWS Organization * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to actions: * - .toCreateResourceShare() * - .toUpdateResourceShare() * * @param value `true` or `false`. **Default:** `true` */ public ifRequestedAllowsExternalPrincipals(value?: boolean) { return this.if(`RequestedAllowsExternalPrincipals`, (typeof value !== 'undefined' ? value : true), 'Bool'); } /** * Filters access based on the specified resource type * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to actions: * - .toAssociateResourceShare() * - .toCreateResourceShare() * - .toDisassociateResourceShare() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifRequestedResourceType(value: string | string[], operator?: Operator | string) { return this.if(`RequestedResourceType`, value, operator || 'StringLike'); } /** * Filters access based on a resource with the specified ARN * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to actions: * - .toAssociateResourceShare() * - .toCreateResourceShare() * - .toDisassociateResourceShare() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifResourceArn(value: string | string[], operator?: Operator | string) { return this.if(`ResourceArn`, value, operator || 'ArnLike'); } /** * Filters access based on a resource share with the specified name * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to actions: * - .toAssociateResourceShare() * - .toDeleteResourceShare() * - .toDisassociateResourceShare() * - .toListResourceSharePermissions() * - .toUpdateResourceShare() * * Applies to resource types: * - resource-share * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifResourceShareName(value: string | string[], operator?: Operator | string) { return this.if(`ResourceShareName`, value, operator || 'StringLike'); } /** * Filters access based on resource shares owned by a specific account. For example, you can use this condition key to specify which resource share invitations can be accepted or rejected based on the resource share owner’s account ID * * https://docs.aws.amazon.com/ram/latest/userguide/iam-policies.html#iam-policies-condition * * Applies to actions: * - .toAcceptResourceShareInvitation() * - .toRejectResourceShareInvitation() * * Applies to resource types: * - resource-share-invitation * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifShareOwnerAccountId(value: string | string[], operator?: Operator | string) { return this.if(`ShareOwnerAccountId`, value, operator || 'StringLike'); } }
the_stack
import { vec3 } from "gl-matrix"; import { AttenuationRolloff } from "./AttenuationRolloff"; import { Dimension } from "./Dimension"; import { Direction } from "./Direction"; import type { ReflectionCoefficients } from "./ReflectionCoefficients"; import type { RoomDimensions } from "./RoomDimensions"; import type { RoomMaterials } from "./RoomMaterials"; /** * Default input gain (linear). */ export const DEFAULT_SOURCE_GAIN = 1; /** * Maximum outside-the-room distance to attenuate far-field listener by. */ export const LISTENER_MAX_OUTSIDE_ROOM_DISTANCE = 1; /** * Maximum outside-the-room distance to attenuate far-field sources by. */ export const SOURCE_MAX_OUTSIDE_ROOM_DISTANCE = 1; /** * Default distance from listener when setting angle. */ export const DEFAULT_SOURCE_DISTANCE = 1; export const DEFAULT_POSITION = vec3.zero(vec3.create()); export const DEFAULT_FORWARD = vec3.set(vec3.create(), 0, 0, -1); export const DEFAULT_UP = vec3.set(vec3.create(), 0, 1, 0); export const DEFAULT_RIGHT = vec3.set(vec3.create(), 1, 0, 0); export const DEFAULT_SPEED_OF_SOUND = 343; /** * Default rolloff model ('logarithmic'). */ export const DEFAULT_ATTENUATION_ROLLOFF = AttenuationRolloff.Logarithmic; /** * Default mode for rendering ambisonics. */ export const DEFAULT_RENDERING_MODE = 'ambisonic'; export const DEFAULT_MIN_DISTANCE = 1; export const DEFAULT_MAX_DISTANCE = 1000; /** * The default alpha (i.e. microphone pattern). */ export const DEFAULT_DIRECTIVITY_ALPHA = 0; /** * The default pattern sharpness (i.e. pattern exponent). */ export const DEFAULT_DIRECTIVITY_SHARPNESS = 1; /** * Default azimuth (in degrees). Suitable range is 0 to 360. * @type {Number} */ export const DEFAULT_AZIMUTH = 0; /** * Default elevation (in degres). * Suitable range is from -90 (below) to 90 (above). */ export const DEFAULT_ELEVATION = 0; /** * The default ambisonic order. */ export const DEFAULT_AMBISONIC_ORDER = 1; /** * The default source width. */ export const DEFAULT_SOURCE_WIDTH = 0; /** * The maximum delay (in seconds) of a single wall reflection. */ export const DEFAULT_REFLECTION_MAX_DURATION = 2; /** * The -12dB cutoff frequency (in Hertz) for the lowpass filter applied to * all reflections. */ export const DEFAULT_REFLECTION_CUTOFF_FREQUENCY = 6400; // Uses -12dB cutoff. /** * The default reflection coefficients (where 0 = no reflection, 1 = perfect * reflection, -1 = mirrored reflection (180-degrees out of phase)). */ export const DEFAULT_REFLECTION_COEFFICIENTS: ReflectionCoefficients = { [Direction.Left]: 0, [Direction.Right]: 0, [Direction.Front]: 0, [Direction.Back]: 0, [Direction.Down]: 0, [Direction.Up]: 0, }; /** * The minimum distance we consider the listener to be to any given wall. */ export const DEFAULT_REFLECTION_MIN_DISTANCE = 1; /** * Default room dimensions (in meters). */ export const DEFAULT_ROOM_DIMENSIONS: RoomDimensions = { [Dimension.Width]: 0, [Dimension.Height]: 0, [Dimension.Depth]: 0, }; /** * The multiplier to apply to distances from the listener to each wall. */ export const DEFAULT_REFLECTION_MULTIPLIER = 1; /** The default bandwidth (in octaves) of the center frequencies. */ export const DEFAULT_REVERB_BANDWIDTH = 1; /** The default multiplier applied when computing tail lengths. */ export const DEFAULT_REVERB_DURATION_MULTIPLIER = 1; /** * The late reflections pre-delay (in milliseconds). */ export const DEFAULT_REVERB_PREDELAY = 1.5; /** * The length of the beginning of the impulse response to apply a * half-Hann window to. */ export const DEFAULT_REVERB_TAIL_ONSET = 3.8; /** * The default gain (linear). */ export const DEFAULT_REVERB_GAIN = 0.01; /** * The maximum impulse response length (in seconds). */ export const DEFAULT_REVERB_MAX_DURATION = 3; /** * Center frequencies of the multiband late reflections. * Nine bands are computed by: 31.25 * 2^(0:8). */ export const DEFAULT_REVERB_FREQUENCY_BANDS = [ 31.25, 62.5, 125, 250, 500, 1000, 2000, 4000, 8000, ]; /** * The number of frequency bands. */ export const NUMBER_REVERB_FREQUENCY_BANDS = DEFAULT_REVERB_FREQUENCY_BANDS.length; /** * The default multiband RT60 durations (in seconds). */ export const DEFAULT_REVERB_DURATIONS = new Float32Array(NUMBER_REVERB_FREQUENCY_BANDS); export enum Material { Transparent = "transparent", AcousticCeilingTiles = "acoustic-ceiling-tiles", BrickBare = "brick-bare", BrickPainted = "brick-painted", ConcreteBlockCoarse = "concrete-block-coarse", ConcreteBlockPainted = "concrete-block-painted", CurtainHeavy = "curtain-heavy", FiberGlassInsulation = "fiber-glass-insulation", GlassThin = "glass-thin", GlassThick = "glass-thick", Grass = "grass", LinoleumOnConcrete = "linoleum-on-concrete", Marble = "marble", Metal = "metal", ParquetOnConcrete = "parquet-on-concrete", PlasterRough = "plaster-rough", PlasterSmooth = "plaster-smooth", PlywoodPanel = "plywood-panel", PolishedConcreteOrTile = "polished-concrete-or-tile", Sheetrock = "sheetrock", WaterOrIceSurface = "water-or-ice-surface", WoodCeiling = "wood-ceiling", WoodPanel = "wood-panel", Uniform = "uniform" } /** * Pre-defined frequency-dependent absorption coefficients for listed materials. * Currently supported materials are: * <ul> * <li>'transparent'</li> * <li>'acoustic-ceiling-tiles'</li> * <li>'brick-bare'</li> * <li>'brick-painted'</li> * <li>'concrete-block-coarse'</li> * <li>'concrete-block-painted'</li> * <li>'curtain-heavy'</li> * <li>'fiber-glass-insulation'</li> * <li>'glass-thin'</li> * <li>'glass-thick'</li> * <li>'grass'</li> * <li>'linoleum-on-concrete'</li> * <li>'marble'</li> * <li>'metal'</li> * <li>'parquet-on-concrete'</li> * <li>'plaster-smooth'</li> * <li>'plywood-panel'</li> * <li>'polished-concrete-or-tile'</li> * <li>'sheetrock'</li> * <li>'water-or-ice-surface'</li> * <li>'wood-ceiling'</li> * <li>'wood-panel'</li> * <li>'uniform'</li> * </ul> * @type {Object} */ export const ROOM_MATERIAL_COEFFICIENTS = { [Material.Transparent]: [1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000], [Material.AcousticCeilingTiles]: [0.672, 0.675, 0.700, 0.660, 0.720, 0.920, 0.880, 0.750, 1.000], [Material.BrickBare]: [0.030, 0.030, 0.030, 0.030, 0.030, 0.040, 0.050, 0.070, 0.140], [Material.BrickPainted]: [0.006, 0.007, 0.010, 0.010, 0.020, 0.020, 0.020, 0.030, 0.060], [Material.ConcreteBlockCoarse]: [0.360, 0.360, 0.360, 0.440, 0.310, 0.290, 0.390, 0.250, 0.500], [Material.ConcreteBlockPainted]: [0.092, 0.090, 0.100, 0.050, 0.060, 0.070, 0.090, 0.080, 0.160], [Material.CurtainHeavy]: [0.073, 0.106, 0.140, 0.350, 0.550, 0.720, 0.700, 0.650, 1.000], [Material.FiberGlassInsulation]: [0.193, 0.220, 0.220, 0.820, 0.990, 0.990, 0.990, 0.990, 1.000], [Material.GlassThin]: [0.180, 0.169, 0.180, 0.060, 0.040, 0.030, 0.020, 0.020, 0.040], [Material.GlassThick]: [0.350, 0.350, 0.350, 0.250, 0.180, 0.120, 0.070, 0.040, 0.080], [Material.Grass]: [0.050, 0.050, 0.150, 0.250, 0.400, 0.550, 0.600, 0.600, 0.600], [Material.LinoleumOnConcrete]: [0.020, 0.020, 0.020, 0.030, 0.030, 0.030, 0.030, 0.020, 0.040], [Material.Marble]: [0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.020, 0.020, 0.040], [Material.Metal]: [0.030, 0.035, 0.040, 0.040, 0.050, 0.050, 0.050, 0.070, 0.090], [Material.ParquetOnConcrete]: [0.028, 0.030, 0.040, 0.040, 0.070, 0.060, 0.060, 0.070, 0.140], [Material.PlasterRough]: [0.017, 0.018, 0.020, 0.030, 0.040, 0.050, 0.040, 0.030, 0.060], [Material.PlasterSmooth]: [0.011, 0.012, 0.013, 0.015, 0.020, 0.030, 0.040, 0.050, 0.100], [Material.PlywoodPanel]: [0.400, 0.340, 0.280, 0.220, 0.170, 0.090, 0.100, 0.110, 0.220], [Material.PolishedConcreteOrTile]: [0.008, 0.008, 0.010, 0.010, 0.015, 0.020, 0.020, 0.020, 0.040], [Material.Sheetrock]: [0.290, 0.279, 0.290, 0.100, 0.050, 0.040, 0.070, 0.090, 0.180], [Material.WaterOrIceSurface]: [0.006, 0.006, 0.008, 0.008, 0.013, 0.015, 0.020, 0.025, 0.050], [Material.WoodCeiling]: [0.150, 0.147, 0.150, 0.110, 0.100, 0.070, 0.060, 0.070, 0.140], [Material.WoodPanel]: [0.280, 0.280, 0.280, 0.220, 0.170, 0.090, 0.100, 0.110, 0.220], [Material.Uniform]: [0.500, 0.500, 0.500, 0.500, 0.500, 0.500, 0.500, 0.500, 0.500], }; /** * Default materials that use strings from * {@linkcode Utils.MATERIAL_COEFFICIENTS MATERIAL_COEFFICIENTS} */ export const DEFAULT_ROOM_MATERIALS: RoomMaterials = { [Direction.Left]: Material.Transparent, [Direction.Right]: Material.Transparent, [Direction.Front]: Material.Transparent, [Direction.Back]: Material.Transparent, [Direction.Down]: Material.Transparent, [Direction.Up]: Material.Transparent, }; /** * The number of bands to average over when computing reflection coefficients. */ export const NUMBER_REFLECTION_AVERAGING_BANDS = 3; /** * The starting band to average over when computing reflection coefficients. */ export const ROOM_STARTING_AVERAGING_BAND = 4; /** * The minimum threshold for room volume. * Room model is disabled if volume is below this value. */ export const ROOM_MIN_VOLUME = 1e-4; /** * Air absorption coefficients per frequency band. */ export const ROOM_AIR_ABSORPTION_COEFFICIENTS = [0.0006, 0.0006, 0.0007, 0.0008, 0.0010, 0.0015, 0.0026, 0.0060, 0.0207]; /** * A scalar correction value to ensure Sabine and Eyring produce the same RT60 * value at the cross-over threshold. */ export const ROOM_EYRING_CORRECTION_COEFFICIENT = 1.38; export const TWO_PI = 6.28318530717959; export const TWENTY_FOUR_LOG10 = 55.2620422318571; export const LOG1000 = 6.90775527898214; export const LOG2_DIV2 = 0.346573590279973; export const DEGREES_TO_RADIANS = 0.017453292519943; export const RADIANS_TO_DEGREES = 57.295779513082323; export const EPSILON_FLOAT = 1e-8; /** * ResonanceAudio library logging function. */ export const log = function (...args: any[]): void { window.console.log.apply(window.console, [ '%c[ResonanceAudio]%c ' + args.join(' ') + ' %c(@' + performance.now().toFixed(2) + 'ms)', 'background: #BBDEFB; color: #FF5722; font-weight: 700', 'font-weight: 400', 'color: #AAA', ]); }; export const DirectionToDimension = { [Direction.Left]: Dimension.Width, [Direction.Right]: Dimension.Width, [Direction.Front]: Dimension.Depth, [Direction.Back]: Dimension.Depth, [Direction.Up]: Dimension.Height, [Direction.Down]: Dimension.Height }; export const DirectionToAxis = { [Direction.Left]: 0, [Direction.Right]: 0, [Direction.Front]: 2, [Direction.Back]: 2, [Direction.Up]: 1, [Direction.Down]: 1 }; export const DirectionSign = { [Direction.Left]: 1, [Direction.Right]: -1, [Direction.Front]: 1, [Direction.Back]: -1, [Direction.Up]: -1, [Direction.Down]: 1 };
the_stack
import { expectByte, expectFloat32, expectInt32, expectLong, expectNonNull, expectObject, expectShort, expectUnion, limitedParseDouble, limitedParseFloat32, parseBoolean, strictParseByte, strictParseDouble, strictParseFloat32, strictParseInt32, strictParseLong, strictParseShort, } from "./parse-utils"; import { expectBoolean, expectNumber, expectString } from "./parse-utils"; describe("parseBoolean", () => { it('Returns true for "true"', () => { expect(parseBoolean("true")).toEqual(true); }); it('Returns false for "false"', () => { expect(parseBoolean("false")).toEqual(false); }); describe("Throws an error on invalid input", () => { it.each([ // These are valid booleans in YAML "y", "Y", "yes", "Yes", "YES", "n", "N", "no", "No", "NO", "True", "TRUE", "False", "FALSE", "on", "On", "ON", "off", "Off", "OFF", // These would be resolve to false using Boolean 0, null, "", false, // These would resolve to true using Boolean true, "Su Lin", [], {}, ])("rejects %s", (value) => { expect(() => parseBoolean(value as any)).toThrowError(); }); }); }); describe("expectBoolean", () => { it.each([true, false])("accepts %s", (value) => { expect(expectBoolean(value)).toEqual(value); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectBoolean(value)).toEqual(undefined); }); describe("rejects non-booleans", () => { it.each(["true", "false", 0, 1, 1.1, Infinity, -Infinity, NaN, {}, []])("rejects %s", (value) => { expect(() => expectBoolean(value)).toThrowError(); }); }); }); describe("expectNumber", () => { describe("accepts numbers", () => { it.each([1, 1.1, Infinity, -Infinity])("accepts %s", (value) => { expect(expectNumber(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectNumber(value)).toEqual(undefined); }); describe("rejects non-numbers", () => { it.each(["1", "1.1", "Infinity", "-Infinity", "NaN", true, false, [], {}])("rejects %s", (value) => { expect(() => expectNumber(value)).toThrowError(); }); }); }); describe("expectFloat32", () => { describe("accepts numbers", () => { it.each([ 1, 1.1, Infinity, -Infinity, // Smallest positive subnormal number 2 ** -149, // Largest subnormal number 2 ** -126 * (1 - 2 ** -23), // Smallest positive normal number 2 ** -126, // Largest normal number 2 ** 127 * (2 - 2 ** -23), // Largest number less than one 1 - 2 ** -24, // Smallest number larger than one 1 + 2 ** -23, ])("accepts %s", (value) => { expect(expectNumber(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectNumber(value)).toEqual(undefined); }); describe("rejects non-numbers", () => { it.each(["1", "1.1", "Infinity", "-Infinity", "NaN", true, false, [], {}])("rejects %s", (value) => { expect(() => expectNumber(value)).toThrowError(); }); }); describe("rejects doubles", () => { it.each([2 ** 128, -(2 ** 128)])("rejects %s", (value) => { expect(() => expectFloat32(value)).toThrowError(); }); }); }); describe("expectLong", () => { describe("accepts 64-bit integers", () => { it.each([ 1, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, 2 ** 31 - 1, -(2 ** 31), 2 ** 15 - 1, -(2 ** 15), 127, -128, ])("accepts %s", (value) => { expect(expectLong(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectLong(value)).toEqual(undefined); }); describe("rejects non-integers", () => { it.each([1.1, "1", "1.1", NaN, true, [], {}])("rejects %s", (value) => { expect(() => expectLong(value)).toThrowError(); }); }); }); describe("expectInt32", () => { describe("accepts 32-bit integers", () => { it.each([1, 2 ** 31 - 1, -(2 ** 31), 2 ** 15 - 1, -(2 ** 15), 127, -128])("accepts %s", (value) => { expect(expectInt32(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectInt32(value)).toEqual(undefined); }); describe("rejects non-integers", () => { it.each([ 1.1, "1", "1.1", NaN, true, [], {}, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, 2 ** 31, -(2 ** 31 + 1), ])("rejects %s", (value) => { expect(() => expectInt32(value)).toThrowError(); }); }); }); describe("expectShort", () => { describe("accepts 16-bit integers", () => { it.each([1, 2 ** 15 - 1, -(2 ** 15), 127, -128])("accepts %s", (value) => { expect(expectShort(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectShort(value)).toEqual(undefined); }); describe("rejects non-integers", () => { it.each([ 1.1, "1", "1.1", NaN, true, [], {}, 2 ** 63 - 1, -(2 ** 63 + 1), 2 ** 31 - 1, -(2 ** 31 + 1), 2 ** 15, -(2 ** 15 + 1), ])("rejects %s", (value) => { expect(() => expectShort(value)).toThrowError(); }); }); }); describe("expectByte", () => { describe("accepts 8-bit integers", () => { it.each([1, 127, -128])("accepts %s", (value) => { expect(expectByte(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectByte(value)).toEqual(undefined); }); describe("rejects non-integers", () => { it.each([ 1.1, "1", "1.1", NaN, true, [], {}, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, 2 ** 31 - 1, -(2 ** 31 + 1), 2 ** 15 - 1, -(2 ** 15 + 1), 128, -129, ])("rejects %s", (value) => { expect(() => expectByte(value)).toThrowError(); }); }); }); describe("expectNonNull", () => { it.each([1, 1.1, "1", NaN, true, [], ["a", 123], { a: 123 }, [{ a: 123 }], "{ a : 123 }", '{"a":123}'])( "accepts %s", (value) => { expect(expectNonNull(value)).toEqual(value); } ); it.each([null, undefined])("rejects %s", (value) => { expect(() => expectNonNull(value)).toThrowError(); }); }); describe("expectObject", () => { it("accepts objects", () => { expect(expectObject({ a: 123 })).toEqual({ a: 123 }); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectObject(value)).toEqual(undefined); }); describe("rejects non-objects", () => { it.each([1, 1.1, "1", NaN, true, [], ["a", 123], [{ a: 123 }], "{ a : 123 }", '{"a":123}'])( "rejects %s", (value) => { expect(() => expectObject(value)).toThrowError(); } ); }); }); describe("expectString", () => { it("accepts strings", () => { expect(expectString("foo")).toEqual("foo"); }); it.each([null, undefined])("accepts %s", (value) => { expect(expectString(value)).toEqual(undefined); }); describe("rejects non-strings", () => { it.each([1, NaN, Infinity, -Infinity, true, false, [], {}])("rejects %s", (value) => { expect(() => expectString(value)).toThrowError(); }); }); }); describe("expectUnion", () => { it.each([null, undefined])("accepts %s", (value) => { expect(expectUnion(value)).toEqual(undefined); }); describe("rejects non-objects", () => { it.each([1, NaN, Infinity, -Infinity, true, false, [], "abc"])("%s", (value) => { expect(() => expectUnion(value)).toThrowError(); }); }); describe("rejects malformed unions", () => { it.each([{}, { a: null }, { a: undefined }, { a: 1, b: 2 }])("%s", (value) => { expect(() => expectUnion(value)).toThrowError(); }); }); describe("accepts unions", () => { it.each([{ a: 1 }, { a: 1, b: null }])("%s", (value) => { expect(expectUnion(value)).toEqual(value); }); }); }); describe("strictParseDouble", () => { describe("accepts non-numeric floats as strings", () => { expect(strictParseDouble("Infinity")).toEqual(Infinity); expect(strictParseDouble("-Infinity")).toEqual(-Infinity); expect(strictParseDouble("NaN")).toEqual(NaN); }); describe("rejects implicit NaN", () => { it.each([ "foo", "123ABC", "ABC123", "12AB3C", "1.A", "1.1A", "1.1A1", "0xFF", "0XFF", "0b1111", "0B1111", "0777", "0o777", "0O777", "1n", "1N", "1_000", "e", "e1", ".1", ])("rejects %s", (value) => { expect(() => strictParseDouble(value)).toThrowError(); }); }); it("accepts numeric strings", () => { expect(strictParseDouble("1")).toEqual(1); expect(strictParseDouble("-1")).toEqual(-1); expect(strictParseDouble("1.1")).toEqual(1.1); expect(strictParseDouble("1e1")).toEqual(10); expect(strictParseDouble("-1e1")).toEqual(-10); expect(strictParseDouble("1e+1")).toEqual(10); expect(strictParseDouble("1e-1")).toEqual(0.1); expect(strictParseDouble("1E1")).toEqual(10); expect(strictParseDouble("1E+1")).toEqual(10); expect(strictParseDouble("1E-1")).toEqual(0.1); }); describe("accepts numbers", () => { it.each([1, 1.1, Infinity, -Infinity, NaN])("accepts %s", (value) => { expect(strictParseDouble(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(strictParseDouble(value)).toEqual(undefined); }); }); describe("strictParseFloat32", () => { describe("accepts non-numeric floats as strings", () => { expect(strictParseFloat32("Infinity")).toEqual(Infinity); expect(strictParseFloat32("-Infinity")).toEqual(-Infinity); expect(strictParseFloat32("NaN")).toEqual(NaN); }); describe("rejects implicit NaN", () => { it.each([ "foo", "123ABC", "ABC123", "12AB3C", "1.A", "1.1A", "1.1A1", "0xFF", "0XFF", "0b1111", "0B1111", "0777", "0o777", "0O777", "1n", "1N", "1_000", "e", "e1", ".1", ])("rejects %s", (value) => { expect(() => strictParseFloat32(value)).toThrowError(); }); }); describe("rejects doubles", () => { it.each([2 ** 128, -(2 ** 128)])("rejects %s", (value) => { expect(() => strictParseFloat32(value)).toThrowError(); }); }); it("accepts numeric strings", () => { expect(strictParseFloat32("1")).toEqual(1); expect(strictParseFloat32("-1")).toEqual(-1); expect(strictParseFloat32("1.1")).toEqual(1.1); expect(strictParseFloat32("1e1")).toEqual(10); expect(strictParseFloat32("-1e1")).toEqual(-10); expect(strictParseFloat32("1e+1")).toEqual(10); expect(strictParseFloat32("1e-1")).toEqual(0.1); expect(strictParseFloat32("1E1")).toEqual(10); expect(strictParseFloat32("1E+1")).toEqual(10); expect(strictParseFloat32("1E-1")).toEqual(0.1); }); describe("accepts numbers", () => { it.each([1, 1.1, Infinity, -Infinity, NaN])("accepts %s", (value) => { expect(strictParseFloat32(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(strictParseFloat32(value)).toEqual(undefined); }); }); describe("limitedParseDouble", () => { it("accepts non-numeric floats as strings", () => { expect(limitedParseDouble("Infinity")).toEqual(Infinity); expect(limitedParseDouble("-Infinity")).toEqual(-Infinity); expect(limitedParseDouble("NaN")).toEqual(NaN); }); it("rejects implicit NaN", () => { expect(() => limitedParseDouble("foo")).toThrowError(); }); describe("rejects numeric strings", () => { it.each(["1", "1.1"])("rejects %s", (value) => { expect(() => limitedParseDouble(value)).toThrowError(); }); }); describe("accepts numbers", () => { it.each([ 1, 1.1, Infinity, -Infinity, NaN, // Smallest positive subnormal number 2 ** -1074, // Largest subnormal number 2 ** -1022 * (1 - 2 ** -52), // Smallest positive normal number 2 ** -1022, // Largest number 2 ** 1023 * (1 + (1 - 2 ** -52)), // Largest number less than one 1 - 2 ** -53, // Smallest number larger than one 1 + 2 ** -52, ])("accepts %s", (value) => { expect(limitedParseDouble(value)).toEqual(value); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(limitedParseDouble(value)).toEqual(undefined); }); }); describe("limitedParseFloat32", () => { it("accepts non-numeric floats as strings", () => { expect(limitedParseFloat32("Infinity")).toEqual(Infinity); expect(limitedParseFloat32("-Infinity")).toEqual(-Infinity); expect(limitedParseFloat32("NaN")).toEqual(NaN); }); it("rejects implicit NaN", () => { expect(() => limitedParseFloat32("foo")).toThrowError(); }); describe("rejects numeric strings", () => { it.each(["1", "1.1"])("rejects %s", (value) => { expect(() => limitedParseFloat32(value)).toThrowError(); }); }); describe("accepts numbers", () => { it.each([ 1, 1.1, Infinity, -Infinity, NaN, // Smallest positive subnormal number 2 ** -149, // Largest subnormal number 2 ** -126 * (1 - 2 ** -23), // Smallest positive normal number 2 ** -126, // Largest normal number 2 ** 127 * (2 - 2 ** -23), // Largest number less than one 1 - 2 ** -24, // Smallest number larger than one 1 + 2 ** -23, ])("accepts %s", (value) => { expect(limitedParseFloat32(value)).toEqual(value); }); }); describe("rejects doubles", () => { it.each([2 ** 128, -(2 ** 128)])("rejects %s", (value) => { expect(() => limitedParseFloat32(value)).toThrowError(); }); }); it.each([null, undefined])("accepts %s", (value) => { expect(limitedParseFloat32(value)).toEqual(undefined); }); }); describe("strictParseLong", () => { describe("accepts integers", () => { describe("accepts 64-bit integers", () => { it.each([1, 2 ** 63 - 1, -(2 ** 63), 2 ** 31 - 1, -(2 ** 31), 2 ** 15 - 1, -(2 ** 15), 127, -128])( "accepts %s", (value) => { expect(strictParseLong(value)).toEqual(value); } ); }); expect(strictParseLong("1")).toEqual(1); }); it.each([null, undefined])("accepts %s", (value) => { expect(strictParseLong(value)).toEqual(undefined); }); describe("rejects non-integers", () => { it.each([ 1.1, "1.1", "NaN", "Infinity", "-Infinity", NaN, Infinity, -Infinity, true, false, [], {}, "foo", "123ABC", "ABC123", "12AB3C", ])("rejects %s", (value) => { expect(() => strictParseLong(value as any)).toThrowError(); }); }); }); describe("strictParseInt32", () => { describe("accepts integers", () => { describe("accepts 32-bit integers", () => { it.each([1, 2 ** 31 - 1, -(2 ** 31), 2 ** 15 - 1, -(2 ** 15), 127, -128])("accepts %s", (value) => { expect(strictParseInt32(value)).toEqual(value); }); }); expect(strictParseInt32("1")).toEqual(1); }); it.each([null, undefined])("accepts %s", (value) => { expect(strictParseInt32(value)).toEqual(undefined); }); describe("rejects non-integers", () => { it.each([ 1.1, "1.1", "NaN", "Infinity", "-Infinity", NaN, Infinity, -Infinity, true, false, [], {}, 2 ** 63 - 1, -(2 ** 63 + 1), 2 ** 31, -(2 ** 31 + 1), "foo", "123ABC", "ABC123", "12AB3C", ])("rejects %s", (value) => { expect(() => strictParseInt32(value as any)).toThrowError(); }); }); }); describe("strictParseShort", () => { describe("accepts integers", () => { describe("accepts 16-bit integers", () => { it.each([1, 2 ** 15 - 1, -(2 ** 15), 127, -128])("accepts %s", (value) => { expect(strictParseShort(value)).toEqual(value); }); }); expect(strictParseShort("1")).toEqual(1); }); it.each([null, undefined])("accepts %s", (value) => { expect(strictParseShort(value)).toEqual(undefined); }); describe("rejects non-integers", () => { it.each([ 1.1, "1.1", "NaN", "Infinity", "-Infinity", NaN, Infinity, -Infinity, true, false, [], {}, 2 ** 63 - 1, -(2 ** 63 + 1), 2 ** 31 - 1, -(2 ** 31 + 1), 2 ** 15, -(2 ** 15 + 1), "foo", "123ABC", "ABC123", "12AB3C", ])("rejects %s", (value) => { expect(() => strictParseShort(value as any)).toThrowError(); }); }); }); describe("strictParseByte", () => { describe("accepts integers", () => { describe("accepts 8-bit integers", () => { it.each([1, 127, -128])("accepts %s", (value) => { expect(strictParseByte(value)).toEqual(value); }); }); expect(strictParseByte("1")).toEqual(1); }); it.each([null, undefined])("accepts %s", (value) => { expect(strictParseByte(value)).toEqual(undefined); }); describe("rejects non-integers", () => { it.each([ 1.1, "1.1", "NaN", "Infinity", "-Infinity", NaN, Infinity, -Infinity, true, false, [], {}, 2 ** 63 - 1, -(2 ** 63 + 1), 2 ** 31 - 1, -(2 ** 31 + 1), 2 ** 15, -(2 ** 15 + 1), 128, -129, "foo", "123ABC", "ABC123", "12AB3C", ])("rejects %s", (value) => { expect(() => strictParseByte(value as any)).toThrowError(); }); }); });
the_stack
declare namespace GoogleAdsScripts { namespace AdsApp { /** * Access to ad group-level video criteria. For example, to access all video keywords in an ad group: * * var videoKeywordIterator = videoAdGroup.videoTargeting().keywords().get(); * while (videoKeywordIterator.hasNext()) { * var videoKeyword = videoKeywordIterator.next(); * } */ interface AdGroupVideoTargeting { /** Returns the selector of all ages in the ad group. */ ages(): VideoAgeSelector; /** Returns the selector of all audiences in the ad group. */ audiences(): VideoAudienceSelector; /** Returns the selector of all excluded ages in the ad group. */ excludedAges(): ExcludedVideoAgeSelector; /** Returns the selector of all excluded audiences in the ad group. */ excludedAudiences(): ExcludedVideoAudienceSelector; /** Returns the selector of all excluded genders in the ad group. */ excludedGenders(): ExcludedVideoGenderSelector; /** Returns the selector of all excluded keywords in the ad group. */ excludedKeywords(): ExcludedVideoKeywordSelector; /** Returns the selector of all excluded mobile application categories in the ad group. */ excludedMobileAppCategories(): ExcludedVideoMobileAppCategorySelector; /** Returns the selector of all excluded mobile applications in the ad group. */ excludedMobileApplications(): ExcludedVideoMobileApplicationSelector; /** Returns the selector of all excluded parental statuses in the ad group. */ excludedParentalStatuses(): ExcludedVideoParentalStatusSelector; /** Returns the selector of all excluded placements in the ad group. */ excludedPlacements(): ExcludedVideoPlacementSelector; /** Returns the selector of all excluded topics in the ad group. */ excludedTopics(): ExcludedVideoTopicSelector; /** Returns the selector of all excluded YouTube channels in the ad group. */ excludedYouTubeChannels(): ExcludedVideoYouTubeChannelSelector; /** Returns the selector of all excluded YouTube videos in the ad group. */ excludedYouTubeVideos(): ExcludedVideoYouTubeVideoSelector; /** Returns the selector of all genders in the ad group. */ genders(): VideoGenderSelector; /** Returns the selector of all keywords in the ad group. */ keywords(): VideoKeywordSelector; /** Returns the selector of all mobile application categories in the ad group. */ mobileAppCategories(): VideoMobileAppCategorySelector; /** Returns the selector of all mobile applications in the ad group. */ mobileApplications(): VideoMobileApplicationSelector; /** Returns a new age builder for this ad group. */ newAgeBuilder(): VideoAgeBuilder; /** Returns a new audience builder for this ad group. */ newAudienceBuilder(): VideoAudienceBuilder; /** Returns a new age gender for this ad group. */ newGenderBuilder(): VideoGenderBuilder; /** Returns a new keyword builder for this ad group. */ newKeywordBuilder(): VideoKeywordBuilder; /** Returns a new mobile application category builder for this ad group. */ newMobileAppCategoryBuilder(): VideoMobileAppCategoryBuilder; /** Returns a new mobile application builder for this ad group. */ newMobileApplicationBuilder(): VideoMobileApplicationBuilder; /** Returns a new parental status builder for this ad group. */ newParentalStatusBuilder(): VideoParentalStatusBuilder; /** Returns a new placement builder for this ad group. */ newPlacementBuilder(): VideoPlacementBuilder; /** Returns a new video topic builder for this ad group. */ newTopicBuilder(): VideoTopicBuilder; /** Returns a new YouTube channel builder for this ad group. */ newYouTubeChannelBuilder(): VideoYouTubeChannelBuilder; /** Returns a new YouTube video builder for this ad group. */ newYouTubeVideoBuilder(): VideoYouTubeVideoBuilder; /** Returns the selector of all parental statuses in the ad group. */ parentalStatuses(): VideoParentalStatusSelector; /** Returns the selector of all placements in the ad group. */ placements(): VideoPlacementSelector; /** Returns the selector of all topics in the ad group. */ topics(): VideoTopicSelector; /** Returns the selector of all YouTube channels in the ad group. */ youTubeChannels(): VideoYouTubeChannelSelector; /** Returns the selector of all YouTube videos in the ad group. */ youTubeVideos(): VideoYouTubeVideoSelector; } /** * Access to aggregated ad group-level video criteria for a campaign and campaign-level excluded video criteria for a campaign. * For example, to access all video keywords in all ad groups in this campaign: * * var videoKeywordIterator = videoCampaign.videoTargeting().keywords().get(); * while (videoKeywordIterator.hasNext()) { * var videoKeyword = videoKeywordIterator.next(); * } */ interface CampaignVideoTargeting { /** Returns the selector of all ages in the campaign. */ ages(): VideoAgeSelector; /** Returns the selector of all audiences in the campaign. */ audiences(): VideoAudienceSelector; /** Returns the selector of all excluded ages in the campaign. */ excludedAges(): ExcludedVideoAgeSelector; /** Returns the selector of all excluded audiences in the campaign. */ excludedAudiences(): ExcludedVideoAudienceSelector; /** Returns the selector of all excluded genders in the campaign. */ excludedGenders(): ExcludedVideoGenderSelector; /** Returns the selector of all excluded keywords in the campaign. */ excludedKeywords(): ExcludedVideoKeywordSelector; /** Returns the selector of all excluded mobile application categories in the campaign. */ excludedMobileAppCategories(): ExcludedVideoMobileAppCategorySelector; /** Returns the selector of all excluded mobile applications in the campaign. */ excludedMobileApplications(): ExcludedVideoMobileApplicationSelector; /** Returns the selector of all excluded parental statuses in the campaign. */ excludedParentalStatuses(): ExcludedVideoParentalStatusSelector; /** Returns the selector of all excluded placements in the campaign. */ excludedPlacements(): ExcludedVideoPlacementSelector; /** Returns the selector of all excluded topics in the campaign. */ excludedTopics(): ExcludedVideoTopicSelector; /** Returns the selector of all excluded YouTube channels in the campaign. */ excludedYouTubeChannels(): ExcludedVideoYouTubeChannelSelector; /** Returns the selector of all excluded YouTube videos in the campaign. */ excludedYouTubeVideos(): ExcludedVideoYouTubeVideoSelector; /** Returns the selector of all genders in the campaign. */ genders(): VideoGenderSelector; /** Returns the selector of all keywords in the campaign. */ keywords(): VideoKeywordSelector; /** Returns the selector of all mobile application categories in the campaign. */ mobileAppCategories(): VideoMobileAppCategorySelector; /** Returns the selector of all mobile applications in the campaign. */ mobileApplications(): VideoMobileApplicationSelector; /** Returns a new age builder for this campaign. */ newAgeBuilder(): VideoAgeBuilder; /** Returns a new audience builder for this campaign. */ newAudienceBuilder(): VideoAudienceBuilder; /** Returns a new age gender for this campaign. */ newGenderBuilder(): VideoGenderBuilder; /** Returns a new keyword builder for this campaign. */ newKeywordBuilder(): VideoKeywordBuilder; /** Returns a new mobile application category builder for this campaign. */ newMobileAppCategoryBuilder(): VideoMobileAppCategoryBuilder; /** Returns a new mobile application builder for this campaign. */ newMobileApplicationBuilder(): VideoMobileApplicationBuilder; /** Returns a new parental status builder for this campaign. */ newParentalStatusBuilder(): VideoParentalStatusBuilder; /** Returns a new placement builder for this campaign. */ newPlacementBuilder(): VideoPlacementBuilder; /** Returns a new video topic builder for this campaign. */ newTopicBuilder(): VideoTopicBuilder; /** Returns a new YouTube channel builder for this campaign. */ newYouTubeChannelBuilder(): VideoYouTubeChannelBuilder; /** Returns a new YouTube video builder for this campaign. */ newYouTubeVideoBuilder(): VideoYouTubeVideoBuilder; /** Returns the selector of all parental statuses in the campaign. */ parentalStatuses(): VideoParentalStatusSelector; /** Returns the selector of all placements in the campaign. */ placements(): VideoPlacementSelector; /** Returns the selector of all topics in the campaign. */ topics(): VideoTopicSelector; /** Returns the selector of all YouTube channels in the campaign. */ youTubeChannels(): VideoYouTubeChannelSelector; /** Returns the selector of all YouTube videos in the campaign. */ youTubeVideos(): VideoYouTubeVideoSelector; } /** Access to video criteria that have been added to ad groups in this account. */ interface VideoTargeting { /** Returns the selector of all ages in the account. */ ages(): VideoAgeSelector; /** Returns the selector of all audiences in the account. */ audiences(): VideoAudienceSelector; /** Returns the selector of all genders in the account. */ genders(): VideoGenderSelector; /** Returns the selector of all keywords in the account. */ keywords(): VideoKeywordSelector; /** Returns the selector of all mobile application categories in the account. */ mobileAppCategories(): VideoMobileAppCategorySelector; /** Returns the selector of all mobile applications in the account. */ mobileApplications(): VideoMobileApplicationSelector; /** Returns the selector of all parental statuses in the account. */ parentalStatuses(): VideoParentalStatusSelector; /** Returns the selector of all placements in the account. */ placements(): VideoPlacementSelector; /** Returns the selector of all topics in the account. */ topics(): VideoTopicSelector; /** Returns the selector of all YouTube channels in the account. */ youTubeChannels(): VideoYouTubeChannelSelector; /** Returns the selector of all YouTube videos in the account. */ youTubeVideos(): VideoYouTubeVideoSelector; } } }
the_stack
import { sp } from '@pnp/sp'; import * as strings from 'ColumnFormatterWebPartStrings'; import { DefaultButton, PrimaryButton } from 'office-ui-fabric-react/lib/Button'; import { CommandBar } from 'office-ui-fabric-react/lib/CommandBar'; import { IContextualMenuItem } from 'office-ui-fabric-react/lib/ContextualMenu'; import { Dialog, DialogFooter, DialogType } from 'office-ui-fabric-react/lib/Dialog'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import { Toggle } from 'office-ui-fabric-react/lib/Toggle'; import { autobind } from 'office-ui-fabric-react/lib/Utilities'; import * as React from 'react'; import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { textForType, typeForTypeAsString } from '../helpers/ColumnTypeHelpers'; import { loadJSOM } from '../helpers/jsomLoader'; import { changeUIState, disconnectWizard, loadedJSOM } from '../state/Actions'; import { columnTypes, IApplicationState, IContext, ISaveDetails, saveMethod, uiState } from '../state/State'; import styles from './ColumnFormatter.module.scss'; var fileDownload = require('js-file-download'); export interface IColumnFormatterEditorCommandsProps { context?: IContext; changeUIState?: (state:uiState) => void; disconnectWizard?: () => void; wizardTabVisible?: boolean; editorString?: string; fieldName?: string; fieldType?: columnTypes; viewTab?: number; saveDetailsFromLoad?: ISaveDetails; jsomLoaded?: boolean; loadedJSOM?: (jsomLoaded:boolean) => void; } export interface IColumnFormatterEditorCommandsState { newConfirmationDialogVisible: boolean; customizeConfirmationDialogVisible: boolean; saveToLibraryDialogVisible: boolean; librariesLoaded: boolean; libraries: Array<any>; selectedLibraryUrl?: string; libraryFolderPath: string; libraryFileName: string; libraryIsSaving: boolean; librarySaveError?: string; applyToListDialogVisible: boolean; listsLoaded: boolean; lists: Array<any>; selectedList?: string; selectedField?: string; listIsApplying: boolean; listSaveError?: string; applyToSiteColumnDialogVisible: boolean; siteColumnsLoaded: boolean; siteColumns: Array<any>; selectedSiteColumnGroup?: string; selectedSiteColumn?: string; siteColumnIsApplying: boolean; siteColumnSaveError?: string; siteColumnPushToLists: boolean; activeSaveMethod?: saveMethod; } class ColumnFormatterEditorCommands_ extends React.Component<IColumnFormatterEditorCommandsProps, IColumnFormatterEditorCommandsState> { public constructor(props:IColumnFormatterEditorCommandsProps) { super(props); this.state = { newConfirmationDialogVisible: false, customizeConfirmationDialogVisible: false, saveToLibraryDialogVisible: false, librariesLoaded: false, libraries: new Array<any>(), selectedLibraryUrl: (props.saveDetailsFromLoad.activeSaveMethod == saveMethod.Library ? props.saveDetailsFromLoad.libraryUrl : undefined), libraryFolderPath: (props.saveDetailsFromLoad.activeSaveMethod == saveMethod.Library ? props.saveDetailsFromLoad.libraryFolderPath : ''), libraryFileName: (props.saveDetailsFromLoad.activeSaveMethod == saveMethod.Library ? props.saveDetailsFromLoad.libraryFilename : props.fieldName + '.json'), libraryIsSaving: false, applyToListDialogVisible: false, listsLoaded: false, lists: new Array<any>(), listIsApplying: false, selectedList: (props.saveDetailsFromLoad.activeSaveMethod == saveMethod.ListField ? props.saveDetailsFromLoad.list : undefined), selectedField: (props.saveDetailsFromLoad.activeSaveMethod == saveMethod.ListField ? props.saveDetailsFromLoad.field : undefined), applyToSiteColumnDialogVisible: false, siteColumnsLoaded: false, siteColumns: new Array<any>(), siteColumnIsApplying: false, siteColumnPushToLists: true, selectedSiteColumnGroup: (props.saveDetailsFromLoad.activeSaveMethod == saveMethod.SiteColumn ? props.saveDetailsFromLoad.siteColumnGroup : undefined), selectedSiteColumn: (props.saveDetailsFromLoad.activeSaveMethod == saveMethod.SiteColumn ? props.saveDetailsFromLoad.siteColumn : undefined), activeSaveMethod: props.saveDetailsFromLoad.activeSaveMethod }; } public render(): React.ReactElement<IColumnFormatterEditorCommandsProps> { return ( <div> <CommandBar items={this.getCommandBarItems()} farItems={this.getCommandBarFarItems()} /> <Dialog hidden={!this.state.newConfirmationDialogVisible} onDismiss={this.closeDialog} dialogContentProps={{ type: DialogType.normal, title: strings.NewConfirmationDialog_Title, subText: strings.NewConfirmationDialog_Text }}> <DialogFooter> <PrimaryButton text={strings.Dialog_Yes} onClick={this.onNewConfirmationClick}/> <DefaultButton text={strings.Dialog_Cancel} onClick={this.closeDialog}/> </DialogFooter> </Dialog> <Dialog hidden={!this.state.customizeConfirmationDialogVisible} onDismiss={this.closeDialog} dialogContentProps={{ type: DialogType.normal, title: strings.CustomizeConfirmationDialog_Title, subText: strings.CustomizeConfirmationDialog_Text }}> <DialogFooter> <PrimaryButton text={strings.Dialog_Yes} onClick={this.onCustomizeConfirmationClick}/> <DefaultButton text={strings.Dialog_Cancel} onClick={this.closeDialog}/> </DialogFooter> </Dialog> <Dialog hidden={!this.state.saveToLibraryDialogVisible} onDismiss={this.closeDialog} dialogContentProps={{ type: DialogType.largeHeader, title: strings.Library_SaveDialogTitle }}> {!this.props.context.isOnline && ( <span>{strings.FeatureUnavailableFromLocalWorkbench}</span> )} {!this.state.librariesLoaded && this.props.context.isOnline && !this.state.libraryIsSaving && this.state.librarySaveError == undefined && ( <Spinner size={SpinnerSize.large} label={strings.Library_LoadingLibraries}/> )} {this.state.librariesLoaded && this.props.context.isOnline && !this.state.libraryIsSaving && this.state.librarySaveError == undefined && ( <div> <Dropdown label={strings.Library_Library} selectedKey={this.state.selectedLibraryUrl} onChanged={(item:IDropdownOption)=> {this.setState({selectedLibraryUrl: item.key.toString()});}} required={true} options={this.librariesToOptions()} /> <TextField label={strings.Library_FolderPath} value={this.state.libraryFolderPath} onChanged={(value:string) => {this.setState({libraryFolderPath: value});}}/> <TextField label={strings.Library_Filename} required={true} value={this.state.libraryFileName} onChanged={(value:string) => {this.setState({libraryFileName: value});}}/> </div> )} {this.state.libraryIsSaving && this.state.librarySaveError == undefined &&( <Spinner size={SpinnerSize.large} label={strings.Library_Saving}/> )} {this.state.librarySaveError !== undefined && ( <span className={styles.errorMessage}>{this.state.librarySaveError}</span> )} <DialogFooter> <PrimaryButton text={strings.Dialog_Save} disabled={!this.saveToLibrarySaveButtonEnabled()} onClick={this.onSaveToLibrarySaveButtonClick}/> <DefaultButton text={strings.Dialog_Cancel} onClick={this.closeDialog}/> </DialogFooter> </Dialog> <Dialog hidden={!this.state.applyToSiteColumnDialogVisible} onDismiss={this.closeDialog} dialogContentProps={{ type: DialogType.largeHeader, title: strings.SiteColumn_SaveDialogTitle }}> {!this.props.context.isOnline && ( <span>{strings.FeatureUnavailableFromLocalWorkbench}</span> )} {!this.state.siteColumnsLoaded && this.props.context.isOnline && !this.state.siteColumnIsApplying && this.state.siteColumnSaveError == undefined && ( <Spinner size={SpinnerSize.large} label={strings.SiteColumn_LoadingSiteColumns}/> )} {this.state.siteColumnsLoaded && this.props.context.isOnline && !this.state.siteColumnIsApplying && this.state.siteColumnSaveError == undefined && ( <div> <Dropdown label={strings.SiteColumn_Group} selectedKey={this.state.selectedSiteColumnGroup} onChanged={(item:IDropdownOption)=> {this.setState({selectedSiteColumnGroup: item.key.toString(),selectedSiteColumn: undefined});}} required={true} options={this.siteColumnGroupsToOptions()} /> <Dropdown label={strings.SiteColumn_Field} selectedKey={this.state.selectedSiteColumn} disabled={this.state.selectedSiteColumnGroup == undefined} onChanged={(item:IDropdownOption)=> {this.setState({selectedSiteColumn: item.key.toString()});}} required={true} options={this.siteColumnsToOptions()} /> <Toggle checked={this.state.siteColumnPushToLists} onChanged={()=> {this.setState({siteColumnPushToLists:!this.state.siteColumnPushToLists});}} onText={strings.SiteColumn_PushToListsOn} offText={strings.SiteColumn_PushToListsOff} /> </div> )} {this.state.siteColumnIsApplying && this.state.siteColumnSaveError == undefined &&( <Spinner size={SpinnerSize.large} label={strings.SiteColumn_Saving}/> )} {this.state.siteColumnSaveError !== undefined && ( <span className={styles.errorMessage}>{this.state.siteColumnSaveError}</span> )} <DialogFooter> <PrimaryButton text={strings.Dialog_Save} disabled={!this.applyToSiteColumnSaveButtonEnabled()} onClick={this.onApplyToSiteColumnSaveButtonClick}/> <DefaultButton text={strings.Dialog_Cancel} onClick={this.closeDialog}/> </DialogFooter> </Dialog> <Dialog hidden={!this.state.applyToListDialogVisible} onDismiss={this.closeDialog} dialogContentProps={{ type: DialogType.largeHeader, title: strings.ListField_SaveDialogTitle }}> {!this.props.context.isOnline && ( <span>{strings.FeatureUnavailableFromLocalWorkbench}</span> )} {!this.state.listsLoaded && this.props.context.isOnline && !this.state.listIsApplying && this.state.listSaveError == undefined && ( <Spinner size={SpinnerSize.large} label={strings.ListField_LoadingLists}/> )} {this.state.listsLoaded && this.props.context.isOnline && !this.state.listIsApplying && this.state.listSaveError == undefined && ( <div> <Dropdown label={strings.ListField_List} selectedKey={this.state.selectedList} onChanged={(item:IDropdownOption)=> {this.setState({selectedList: item.key.toString(),selectedField: undefined});}} required={true} options={this.listsToOptions()} /> <Dropdown label={strings.ListField_Field} selectedKey={this.state.selectedField} disabled={this.state.selectedList == undefined} onChanged={(item:IDropdownOption)=> {this.setState({selectedField: item.key.toString()});}} required={true} options={this.fieldsToOptions()} /> </div> )} {this.state.listIsApplying && this.state.listSaveError == undefined &&( <Spinner size={SpinnerSize.large} label={strings.ListField_Saving}/> )} {this.state.listSaveError !== undefined && ( <span className={styles.errorMessage}>{this.state.listSaveError}</span> )} <DialogFooter> <PrimaryButton text={strings.Dialog_Save} disabled={!this.applyToListSaveButtonEnabled()} onClick={this.onApplyToListSaveButtonClick}/> <DefaultButton text={strings.Dialog_Cancel} onClick={this.closeDialog}/> </DialogFooter> </Dialog> </div> ); } private getCommandBarItems(): Array<IContextualMenuItem> { let items:Array<IContextualMenuItem> = [ { key: 'new', name: strings.Command_New, iconProps: {iconName: 'Add'}, onClick: this.onNewClick } ]; if(this.props.wizardTabVisible) { items.push({ key: 'customize', name: strings.Command_Customize, iconProps: {iconName: 'Fingerprint'}, onClick: this.onCustomizeClick }); } return items; } private getCommandBarFarItems(): Array<IContextualMenuItem> { let items:Array<IContextualMenuItem> = []; items.push( { key: 'saveas', name: strings.Command_SaveAs, iconProps: {iconName: 'SaveAs'}, subMenuProps: { items: [ { key: 'saveas-download', name: this.saveMethodTitle(saveMethod.Download), iconProps: { iconName: this.saveMethodIcon(saveMethod.Download) }, onClick: this.onDownloadClick }, { key: 'saveas-copy', name: this.saveMethodTitle(saveMethod.Copy), iconProps: { iconName: this.saveMethodIcon(saveMethod.Copy) }, onClick: this.onCopyClick }, { key: 'saveas-library', name: this.saveMethodTitle(saveMethod.Library), iconProps: { iconName: this.saveMethodIcon(saveMethod.Library) }, onClick: this.onSaveToLibraryClick }, { key: 'saveas-sitecolumn', name: this.saveMethodTitle(saveMethod.SiteColumn), iconProps: { iconName: this.saveMethodIcon(saveMethod.SiteColumn) }, onClick: this.onApplyToSiteColumnClick }, { key: 'saveas-listfield', name: this.saveMethodTitle(saveMethod.ListField), iconProps: { iconName: this.saveMethodIcon(saveMethod.ListField) }, onClick: this.onApplyToListClick } ] } } ); if(this.state.activeSaveMethod !== undefined && ((this.state.activeSaveMethod == saveMethod.Library && this.saveToLibrarySaveButtonEnabled()) || this.state.activeSaveMethod !== saveMethod.Library) && ((this.state.activeSaveMethod == saveMethod.ListField && this.applyToListSaveButtonEnabled()) || this.state.activeSaveMethod !== saveMethod.ListField) && ((this.state.activeSaveMethod == saveMethod.SiteColumn && this.applyToSiteColumnSaveButtonEnabled()) || this.state.activeSaveMethod !== saveMethod.SiteColumn)) { items.push({ key: 'save', name: strings.Command_Save, iconProps: { iconName: this.saveMethodIcon(this.state.activeSaveMethod)}, title: this.saveMethodTitle(this.state.activeSaveMethod), onClick: this.onSaveClick }); } return items; } private saveMethodIcon(method:saveMethod): string { switch (method) { case saveMethod.Download: return 'CloudDownload'; case saveMethod.Copy: return 'Copy'; case saveMethod.Library: return 'DocLibrary'; case saveMethod.SiteColumn: return 'Redeploy'; case saveMethod.ListField: return 'Deploy'; default: return 'Save'; } } private saveMethodTitle(method:saveMethod): string { switch (method) { case saveMethod.Download: return strings.Command_Download; case saveMethod.Copy: return strings.Command_Copy; case saveMethod.Library: return strings.Command_SaveToLibrary; case saveMethod.SiteColumn: return strings.Command_ApplyToSiteColumn; case saveMethod.ListField: return strings.Command_ApplyToList; default: return strings.Command_Save; } } @autobind private onNewClick(ev?:React.MouseEvent<HTMLElement>, item?:IContextualMenuItem): void { this.setState({ newConfirmationDialogVisible: true }); } @autobind private onNewConfirmationClick(): void { this.props.changeUIState(uiState.welcome); } @autobind private onCustomizeClick(ev?:React.MouseEvent<HTMLElement>, item?:IContextualMenuItem): void { this.setState({ customizeConfirmationDialogVisible: true }); } @autobind private onCustomizeConfirmationClick(): void { this.props.disconnectWizard(); this.setState({ customizeConfirmationDialogVisible: false }); } @autobind private closeDialog(): void { this.setState({ newConfirmationDialogVisible: false, customizeConfirmationDialogVisible: false, saveToLibraryDialogVisible: false, librarySaveError: undefined, applyToListDialogVisible: false, applyToSiteColumnDialogVisible: false }); } @autobind private onSaveClick(ev?:React.MouseEvent<HTMLElement>, item?:IContextualMenuItem): void { switch(this.state.activeSaveMethod) { case saveMethod.Download: this.onDownloadClick(ev, item); break; case saveMethod.Copy: this.onCopyClick(ev, item); break; case saveMethod.Library: this.onSaveToLibrarySaveButtonClick(); break; case saveMethod.ListField: this.onApplyToListSaveButtonClick(); break; } } @autobind private onDownloadClick(ev?:React.MouseEvent<HTMLElement>, item?:IContextualMenuItem): void { fileDownload(this.props.editorString, this.props.fieldName + '.json'); this.setState({ activeSaveMethod: saveMethod.Download }); } @autobind private onCopyClick(ev?:React.MouseEvent<HTMLElement>, item?:IContextualMenuItem): void { var textArea = document.createElement("textarea"); textArea.style.position = 'fixed'; textArea.style.top = '0'; textArea.style.left = '0'; textArea.style.width = '2em'; textArea.style.height = '2em'; textArea.style.padding = '0'; textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; textArea.style.background = 'transparent'; textArea.value = this.props.editorString; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); } catch (err) { if(window.console && window.console.log) { console.log(strings.CopyToClipboardError); } } document.body.removeChild(textArea); this.setState({ activeSaveMethod: saveMethod.Copy }); } @autobind private onSaveToLibraryClick(ev?:React.MouseEvent<HTMLElement>, item?:IContextualMenuItem): void { if(!this.state.librariesLoaded) { if(this.props.context.isOnline) { sp.site.getDocumentLibraries(this.props.context.webAbsoluteUrl) .then((data:any) => { this.setState({ librariesLoaded: true, libraries: data }); }) .catch((error:any) => { this.setState({ librarySaveError: strings.Library_LibrariesLoadError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } } this.setState({ saveToLibraryDialogVisible: true }); } private librariesToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var library of this.state.libraries) { items.push({ key: library.ServerRelativeUrl, text: library.Title }); } return items; } private saveToLibrarySaveButtonEnabled(): boolean{ return ( this.props.context.isOnline && this.state.selectedLibraryUrl !== undefined && this.state.libraryFileName.length > 0 && this.state.librarySaveError == undefined ); } @autobind private onSaveToLibrarySaveButtonClick(): void { this.setState({ libraryIsSaving: true, librarySaveError: undefined, saveToLibraryDialogVisible: true }); sp.web.getFolderByServerRelativeUrl(this.state.selectedLibraryUrl + (this.state.libraryFolderPath.length > 0 ? '/' + this.state.libraryFolderPath : '')) .files.add(this.state.libraryFileName, this.props.editorString, true) .then(()=>{ this.setState({ libraryIsSaving: false, saveToLibraryDialogVisible: false, activeSaveMethod: saveMethod.Library }); }) .catch((error:any) => { this.setState({ libraryIsSaving: false, librarySaveError: strings.Library_SaveError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message, activeSaveMethod: undefined }); }); } @autobind private onApplyToSiteColumnClick(ev?:React.MouseEvent<HTMLElement>, item?:IContextualMenuItem): void { if(!this.state.siteColumnsLoaded) { if(this.props.context.isOnline) { sp.web.fields.filter('ReadOnlyField eq false and Hidden eq false').select('Id','Group','Title','InternalName','TypeAsString','DisplayFormat').orderBy('Group').get() .then((data:any) => { let groupdata:Array<any> = new Array<any>(); var curGroupName:string; for(var i=0; i<data.length; i++){ let ftype = typeForTypeAsString(data[i].TypeAsString, data[i].DisplayFormat); if(ftype !== undefined) { if(curGroupName != data[i].Group) { groupdata.push({ Group: data[i].Group, Fields: [] }); curGroupName = data[i].Group; } groupdata[groupdata.length-1].Fields.push({ Id: data[i].Id, Title: data[i].Title, InternalName: data[i].InternalName, Type: ftype, FieldType: data[i]["odata.type"] }); } } this.setState({ siteColumnsLoaded: true, siteColumns: groupdata }); }) .catch((error:any) => { this.setState({ siteColumnSaveError: strings.SiteColumn_SiteColumnsLoadError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } } this.setState({ applyToSiteColumnDialogVisible: true }); } private siteColumnGroupsToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var group of this.state.siteColumns) { items.push({ key: group.Group, text: group.Group }); } return items; } private siteColumnsToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var group of this.state.siteColumns) { if(group.Group == this.state.selectedSiteColumnGroup) { for(var field of group.Fields) { items.push({ key: field.InternalName, text: field.Title + ' [' + textForType(field.Type) + ']' }); } } } return items; } private applyToSiteColumnSaveButtonEnabled(): boolean{ return ( this.props.context.isOnline && this.state.selectedSiteColumnGroup !== undefined && this.state.selectedSiteColumn !== undefined && this.state.siteColumnSaveError == undefined ); } @autobind private onApplyToSiteColumnSaveButtonClick(): void { this.setState({ siteColumnIsApplying: true, siteColumnSaveError: undefined, applyToSiteColumnDialogVisible: true }); //Save to site column (no way to push changes to lists in REST directly) sp.web.fields.getByInternalNameOrTitle(this.state.selectedSiteColumn).update({ CustomFormatter: this.props.editorString }) .then(()=>{ if(this.state.siteColumnPushToLists) { //if push to lists, then JSOM is used to just load the field (with the saves from above) and push it down if(!this.props.jsomLoaded) { loadJSOM().then(() => { this.props.loadedJSOM(true); return this.applyToSiteColumnAndPushChanges(); }); } else { return this.applyToSiteColumnAndPushChanges(); } } else { return; } }) .then(() => { this.setState({ siteColumnIsApplying: false, applyToSiteColumnDialogVisible: false, activeSaveMethod: saveMethod.SiteColumn }); }) .catch((error:any) => { this.setState({ siteColumnIsApplying: false, siteColumnSaveError: strings.SiteColumn_SaveError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message, activeSaveMethod: undefined }); }); } private applyToSiteColumnAndPushChanges(): Promise<any> { return new Promise<any>((resolve:() => void, reject: (error:any) => void): void => { let ctx: SP.ClientContext = SP.ClientContext.get_current(); let web: SP.Web = ctx.get_web(); let field = web.get_fields().getByInternalNameOrTitle(this.state.selectedSiteColumn); field.updateAndPushChanges(true); ctx.executeQueryAsync(():void => { resolve(); }, (sender:any,args:SP.ClientRequestFailedEventArgs):void => { reject(args.get_errorValue()); }); }); } @autobind private onApplyToListClick(ev?:React.MouseEvent<HTMLElement>, item?:IContextualMenuItem): void { if(!this.state.listsLoaded) { if(this.props.context.isOnline) { sp.web.lists.filter('Hidden eq false').select('Id','Title','Fields/InternalName','Fields/TypeAsString','Fields/Hidden','Fields/Title','Fields/DisplayFormat').expand('Fields').get() .then((data:any) => { let listdata:Array<any> = new Array<any>(); for(var i=0; i<data.length; i++){ listdata.push({ Id: data[i].Id, Title: data[i].Title, Fields: data[i].Fields.map((field:any, index:number) => { if(!field.Hidden) { let ftype = typeForTypeAsString(field.TypeAsString, field.DisplayFormat); if(ftype !== undefined) { return { Title: field.Title, InternalName: field.InternalName, Type: ftype }; } } }).filter((field:any, index:number) => {return field !== undefined;}) }); } this.setState({ listsLoaded: true, lists: listdata }); }) .catch((error:any) => { this.setState({ listSaveError: strings.ListField_ListLoadError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } } this.setState({ applyToListDialogVisible: true }); } private listsToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var list of this.state.lists) { items.push({ key: list.Id, text: list.Title }); } return items; } private fieldsToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var list of this.state.lists) { if(list.Id == this.state.selectedList) { for(var field of list.Fields) { if((this.props.fieldType == columnTypes.lookup && field.Type == columnTypes.lookup) || (this.props.fieldType == columnTypes.person && field.Type == columnTypes.person) || (this.props.fieldType !== columnTypes.person && field.Type !== columnTypes.person && this.props.fieldType !== columnTypes.lookup && field.Type !== columnTypes.lookup)) { //formats for lookups can only be applied to lookups //formats for users can only be applied to users //the others are mostly interchangable (because @currentField works without subprops required) items.push({ key: field.InternalName, text: field.Title + ' [' + textForType(field.Type) + ']' }); } } break; } } return items; } private applyToListSaveButtonEnabled(): boolean{ return ( this.props.context.isOnline && this.state.selectedList !== undefined && this.state.selectedField !== undefined && this.state.listSaveError == undefined ); } @autobind private onApplyToListSaveButtonClick(): void { this.setState({ listIsApplying: true, listSaveError: undefined, applyToListDialogVisible: true }); sp.web.lists.getById(this.state.selectedList) .fields.getByInternalNameOrTitle(this.state.selectedField).update({ CustomFormatter: this.props.editorString }) .then(()=>{ this.setState({ listIsApplying: false, applyToListDialogVisible: false, activeSaveMethod: saveMethod.ListField }); }) .catch((error:any) => { this.setState({ listIsApplying: false, listSaveError: strings.ListField_SaveError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message, activeSaveMethod: undefined }); }); } } function mapStateToProps(state: IApplicationState): IColumnFormatterEditorCommandsProps{ return { context: state.context, wizardTabVisible: state.ui.tabs.wizardTabVisible, editorString: state.code.editorString, fieldName: state.data.columns[0].name, fieldType: state.data.columns[0].type, viewTab: state.ui.tabs.viewTab, saveDetailsFromLoad: state.ui.saveDetails, jsomLoaded: state.context.jsomLoaded }; } function mapDispatchToProps(dispatch: Dispatch<IColumnFormatterEditorCommandsProps>): IColumnFormatterEditorCommandsProps{ return { changeUIState: (state:uiState) => { dispatch(changeUIState(state)); }, disconnectWizard: () => { dispatch(disconnectWizard()); }, loadedJSOM: (jsomLoaded:boolean) => { dispatch(loadedJSOM(jsomLoaded)); } }; } export const ColumnFormatterEditorCommands = connect(mapStateToProps, mapDispatchToProps)(ColumnFormatterEditorCommands_);
the_stack
import cm = require('./common'); import ctxm = require('./context'); import agentifm = require('vso-node-api/interfaces/TaskAgentInterfaces'); import buildifm = require('vso-node-api/interfaces/BuildInterfaces'); import fcifm = require('vso-node-api/interfaces/FileContainerInterfaces'); import testifm = require('vso-node-api/interfaces/TestInterfaces'); import ifm = require('./interfaces'); import vssifm = require('vso-node-api/interfaces/common/VSSInterfaces'); import agentm = require('vso-node-api/TaskAgentApi'); import buildm = require('vso-node-api/BuildApi'); import fcm = require('vso-node-api/FileContainerApi'); import taskm = require('vso-node-api/TaskApi'); import testm = require('vso-node-api/TestApi'); import webapim = require('vso-node-api/WebApi'); import zlib = require('zlib'); import fs = require('fs'); import tm = require('./tracing'); import cq = require('./concurrentqueue'); import Q = require('q'); import events = require('events'); var async = require('async'); var CONSOLE_DELAY = 373; var TIMELINE_DELAY = 487; var LOG_DELAY = 1137; var LOCK_DELAY = 29323; var CHECK_INTERVAL = 1000; var MAX_DRAIN_WAIT = 60 * 1000; // 1 min export class Events { static Abandoned = "abandoned"; } export class TimedWorker extends events.EventEmitter { constructor(msDelay: number) { super(); this._msDelay = msDelay; this.enabled = true; this._waitAndSend(); } private _msDelay: number; public enabled: boolean; //------------------------------------------------------------------ // Work //------------------------------------------------------------------ public end(): void { this.enabled = false; } // need to override public doWork(): Q.Promise<any> { return Q.reject(new Error('Abstract. Must override.')); } // should likely override public shouldDoWork(): boolean { return this.enabled; } private _waitAndSend(): void { setTimeout(() => { if (this.shouldDoWork()) { this.doWork().fin(() => { this.continueSending(); }); } else { this.continueSending(); } }, this._msDelay); } public continueSending(): void { if (this.enabled) { this._waitAndSend(); } } } //---------------------------------------------------------------------------------------- // Feedback Channels // - All customer feedback funnels through this point // - Feedback channels are pluggable for development and testing // - The service channel is a timed worker and creates timed queues for logs and console //---------------------------------------------------------------------------------------- var trace: tm.Tracing; function ensureTrace(writer: cm.ITraceWriter) { if (!trace) { trace = new tm.Tracing(__filename, writer); } } export class ServiceChannel extends events.EventEmitter implements cm.IServiceChannel { constructor(agentUrl: string, collectionUrl: string, jobInfo: cm.IJobInfo, hostContext: ctxm.HostContext) { super(); ensureTrace(hostContext); trace.enter('ServiceChannel'); this.agentUrl = agentUrl; this.collectionUrl = collectionUrl; this.jobInfo = jobInfo; this.hostContext = hostContext; this._recordCount = 0; this._issues = {}; // service apis var webapi: webapim.WebApi = this.getWebApi(); this._agentApi = webapi.getTaskAgentApi(agentUrl); this.taskApi = webapi.getTaskApi(); this._fileContainerApi = webapi.getQFileContainerApi(); this._buildApi = webapi.getQBuildApi(); this._totalWaitTime = 0; this._lockRenewer = new LockRenewer(jobInfo, hostContext.config.poolId); // pass the Abandoned event up to the owner this._lockRenewer.on(Events.Abandoned, () => { this.emit(Events.Abandoned); }); // timelines this._timelineRecordQueue = new cq.ConcurrentBatch<agentifm.TimelineRecord>( (key: string) => { return <agentifm.TimelineRecord>{ id: key }; }, (values: agentifm.TimelineRecord[], callback: (err: any) => void) => { if (values.length === 0) { callback(0); } else { this.taskApi.updateRecords( { value: values, count: values.length }, this.jobInfo.variables[cm.vars.systemTeamProjectId], this.jobInfo.description, this.jobInfo.planId, this.jobInfo.timelineId, (err, status, records) => { callback(err); }); } }, (err: any) => { trace.write(err); }, TIMELINE_DELAY); // console lines this._consoleQueue = new WebConsoleQueue(this, this.hostContext, CONSOLE_DELAY); // log pages this._logPageQueue = new LogPageQueue(this, this.hostContext, LOG_DELAY); this._timelineRecordQueue.startProcessing(); this._consoleQueue.startProcessing(); this._logPageQueue.startProcessing(); } public enabled: boolean; public agentUrl: string; public collectionUrl: string; public hostContext: ctxm.HostContext; public jobInfo: cm.IJobInfo; private _totalWaitTime: number; private _logQueue: LogPageQueue; private _lockRenewer: LockRenewer; private _buildApi: buildm.IQBuildApi; private _agentApi: agentm.ITaskAgentApi; private _fileContainerApi: fcm.IQFileContainerApi; public taskApi: taskm.ITaskApi; public _testApi: testm.IQTestApi; public _projectName: string; private _issues: any; private _recordCount: number; private _timelineRecordQueue: cq.ConcurrentBatch<agentifm.TimelineRecord>; private _consoleQueue: WebConsoleQueue; private _logPageQueue: LogPageQueue; public getWebApi(): webapim.WebApi { return new webapim.WebApi(this.collectionUrl, this.jobInfo.systemAuthHandler); } // wait till all the queues are empty and not processing. public drain(): Q.Promise<any> { trace.enter('servicechannel:drain'); var consoleFinished = this._consoleQueue.waitForEmpty(); var logFinished = this._logPageQueue.waitForEmpty(); var timelineFinished = this._timelineRecordQueue.waitForEmpty(); // no more console lines or log pages should be generated this._consoleQueue.finishAdding(); this._logPageQueue.finishAdding(); // don't complete the timeline queue until the log queue is done logFinished.then(() => { this._timelineRecordQueue.finishAdding(); }); return Q.all([consoleFinished, logFinished, timelineFinished]); } //------------------------------------------------------------------ // Queue Items //------------------------------------------------------------------ public queueLogPage(page: cm.ILogPageInfo): void { trace.enter('servicechannel:queueLogPage'); this._logPageQueue.push(page); } public queueConsoleLine(line: string): void { line = this.jobInfo.mask(line); if (line.length > 512) { line = line.substring(0, 509) + '...'; } trace.write('qline: ' + line); this._consoleQueue.push(line); } public queueConsoleSection(line: string): void { line = this.jobInfo.mask(line); trace.enter('servicechannel:queueConsoleSection: ' + line); this._consoleQueue.section(line); } private updateJobRequest(poolId: number, lockToken: string, jobRequest: agentifm.TaskAgentJobRequest): Q.Promise<any> { trace.enter('servicechannel:updateJobRequest'); trace.write('poolId: ' + poolId); trace.write('lockToken: ' + lockToken); process.send({ messageType: 'updateJobRequest', poolId: poolId, lockToken: lockToken, jobRequest: jobRequest }); return Q.resolve(null); } public finishJobRequest(poolId: number, lockToken: string, jobRequest: agentifm.TaskAgentJobRequest): Q.Promise<any> { trace.enter('servicechannel:finishJobRequest'); // end the lock renewer. if it's currently waiting on its timeout, .finished will be a previously resolved promise trace.write('shutting down lock renewer...'); this._lockRenewer.end(); // wait for the lock renewer to finish. this is only really meaningful if it's actually in the middle of an HTTP request return this._lockRenewer.finished.then(() => { trace.write('lock renewer shut down'); return this.updateJobRequest(poolId, lockToken, jobRequest); }); } // Factory for scriptrunner to create a queue per task script execution // This also allows agent tests to create a queue that doesn't process to a real server (just print out work it would do) public createAsyncCommandQueue(executionContext: cm.IExecutionContext): cm.IAsyncCommandQueue { return new AsyncCommandQueue(executionContext, 1000); } //------------------------------------------------------------------ // Timeline APIs //------------------------------------------------------------------ public addError(recordId: string, category: string, message: string, data: any): void { var current = this._getIssues(recordId); var record = this._getFromBatch(recordId); if (current.errorCount < process.env.VSO_ERROR_COUNT ? process.env.VSO_ERROR_COUNT : 10) { var error = <agentifm.Issue>{}; error.category = category; error.type = agentifm.IssueType.Error; error.message = message; error.data = data; current.issues.push(error); record.issues = current.issues; } current.errorCount++; record.errorCount = current.errorCount; } public addWarning(recordId: string, category: string, message: string, data: any): void { var current = this._getIssues(recordId); var record = this._getFromBatch(recordId); if (current.warningCount < process.env.VSO_WARNING_COUNT ? process.env.VSO_WARNING_COUNT : 10) { var warning = <agentifm.Issue>{}; warning.category = category; warning.type = agentifm.IssueType.Error; warning.message = message; warning.data = data; current.issues.push(warning); record.issues = current.issues; } current.warningCount++; record.warningCount = current.warningCount; } public setCurrentOperation(recordId: string, operation: string): void { trace.state('operation', operation); this._getFromBatch(recordId).currentOperation = operation; } public setName(recordId: string, name: string): void { trace.state('name', name); this._getFromBatch(recordId).name = name; } public setStartTime(recordId: string, startTime: Date): void { trace.state('startTime', startTime); this._getFromBatch(recordId).startTime = startTime; } public setFinishTime(recordId: string, finishTime: Date): void { trace.state('finishTime', finishTime); this._getFromBatch(recordId).finishTime = finishTime; } public setState(recordId: string, state: agentifm.TimelineRecordState): void { trace.state('state', state); this._getFromBatch(recordId).state = state; } public setResult(recordId: string, result: agentifm.TaskResult): void { trace.state('result', result); this._getFromBatch(recordId).result = result; } public setType(recordId: string, type: string): void { trace.state('type', type); this._getFromBatch(recordId).type = type; } public setParentId(recordId: string, parentId: string): void { trace.state('parentId', parentId); this._getFromBatch(recordId).parentId = parentId; } public setWorkerName(recordId: string, workerName: string): void { trace.state('workerName', workerName); this._getFromBatch(recordId).workerName = workerName; } public setLogId(recordId: string, logRef: agentifm.TaskLogReference): void { trace.state('logRef', logRef); this._getFromBatch(recordId).log = logRef; } public setOrder(recordId: string, order: number): void { trace.state('order', order); this._getFromBatch(recordId).order = order; } public uploadFileToContainer(containerId: number, containerItemTuple: ifm.FileContainerItemInfo): Q.Promise<any> { trace.state('containerItemTuple', containerItemTuple); var contentStream: NodeJS.ReadableStream = fs.createReadStream(containerItemTuple.fullPath); var options = { isGzipped: containerItemTuple.isGzipped, compressedLength: containerItemTuple.compressedLength }; return this._fileContainerApi.createItem(contentStream, containerItemTuple.uncompressedLength, containerId, containerItemTuple.containerItem.path, this.jobInfo.variables[cm.vars.systemTeamProjectId], options); } public postArtifact(projectId: string, buildId: number, artifact: buildifm.BuildArtifact): Q.Promise<buildifm.BuildArtifact> { trace.state('artifact', artifact); return this._buildApi.createArtifact(artifact, buildId, projectId); } //------------------------------------------------------------------ // Timeline internal batching //------------------------------------------------------------------ private _getFromBatch(recordId: string): agentifm.TimelineRecord { trace.enter('servicechannel:_getFromBatch'); return this._timelineRecordQueue.getOrAdd(recordId); } private _getIssues(recordId: string) { if (!this._issues.hasOwnProperty(recordId)) { this._issues[recordId] = { errorCount: 0, warningCount: 0, issues: [] }; } return this._issues[recordId]; } //------------------------------------------------------------------ // Code coverage items //------------------------------------------------------------------ public publishCodeCoverageSummary(coverageData: testifm.CodeCoverageData, project: string, buildId: number): Q.Promise<any> { this._testApi = new webapim.WebApi(this.jobInfo.variables[cm.AutomationVariables.systemTfCollectionUri], this.jobInfo.systemAuthHandler).getQTestApi(); return this._testApi.updateCodeCoverageSummary(coverageData, project, buildId); } //------------------------------------------------------------------ // Test publishing Items //------------------------------------------------------------------ public initializeTestManagement(projectName: string): void { trace.enter('servicechannel:initializeTestManagement'); this._testApi = new webapim.WebApi(this.jobInfo.variables[cm.AutomationVariables.systemTfCollectionUri], this.jobInfo.systemAuthHandler).getQTestApi(); this._projectName = projectName; } public createTestRun(testRun: testifm.RunCreateModel): Q.Promise<testifm.TestRun> { trace.enter('servicechannel:createTestRun'); return this._testApi.createTestRun(testRun, this._projectName); } public endTestRun(testRunId: number): Q.Promise<testifm.TestRun> { trace.enter('servicechannel:endTestRun'); var endedRun: testifm.RunUpdateModel = <testifm.RunUpdateModel>{ state: "Completed" }; return this._testApi.updateTestRun(endedRun, this._projectName, testRunId); } public createTestRunResult(testRunId: number, testRunResults: testifm.TestResultCreateModel[]): Q.Promise<testifm.TestCaseResult[]> { trace.enter('servicechannel:createTestRunResult'); return this._testApi.addTestResultsToTestRun(testRunResults, this._projectName, testRunId); } public createTestRunAttachment(testRunId: number, fileName: string, contents: string): Q.Promise<any> { trace.enter('servicechannel:createTestRunAttachment'); var attachmentData = <testifm.TestAttachmentRequestModel>{ attachmentType: "GeneralAttachment", comment: "", fileName: fileName, stream: contents } return this._testApi.createTestRunAttachment(attachmentData, this._projectName, testRunId); } } //------------------------------------------------------------------------------------ // Server Feedback Queues //------------------------------------------------------------------------------------ export class BaseQueue<T> { private _queue: cq.ConcurrentArray<T>; private _outputChannel: cm.IOutputChannel; private _msDelay: number; constructor(outputChannel: cm.IOutputChannel, msDelay: number) { this._outputChannel = outputChannel; this._msDelay = msDelay; } public push(value: T) { this._queue.push(value); } public finishAdding() { this._queue.finishAdding(); } public waitForEmpty(): Q.Promise<any> { return this._queue.waitForEmpty(); } public startProcessing() { if (!this._queue) { this._queue = new cq.ConcurrentArray<T>( (values: T[], callback: (err: any) => void) => { this._processQueue(values, callback); }, (err: any) => { this._outputChannel.error(err); }, this._msDelay); this._queue.startProcessing(); } } public _processQueue(values: T[], callback: (err: any) => void) { throw new Error("abstract"); } } export class WebConsoleQueue extends BaseQueue<string> { private _jobInfo: cm.IJobInfo; private _taskApi: taskm.ITaskApi; constructor(feedback: cm.IServiceChannel, hostContext: ctxm.HostContext, msDelay: number) { super(hostContext, msDelay); this._jobInfo = feedback.jobInfo; this._taskApi = feedback.getWebApi().getTaskApi(); } public section(line: string): void { this.push('[section] ' + line); } public push(line: string): void { super.push(line); } public _processQueue(values: string[], callback: (err: any) => void) { if (values.length === 0) { callback(null); } else { this._taskApi.appendTimelineRecordFeed( { value: values, count: values.length }, this._jobInfo.variables[cm.vars.systemTeamProjectId], this._jobInfo.description, this._jobInfo.planId, this._jobInfo.timelineId, this._jobInfo.jobId, (err, status) => { trace.write('done writing lines'); if (err) { trace.write('err: ' + err.message); } callback(err); }); } } } export class AsyncCommandQueue extends BaseQueue<cm.IAsyncCommand> implements cm.IAsyncCommandQueue { constructor(executionContext: cm.IExecutionContext, msDelay: number) { super(executionContext, msDelay); this.failed = false; } public failed: boolean; public errorMessage: string; private _service: cm.IServiceChannel; public _processQueue(commands: cm.IAsyncCommand[], callback: (err: any) => void) { if (commands.length === 0) { callback(null); } else { async.forEachSeries(commands, (asyncCmd: cm.IAsyncCommand, done: (err: any) => void) => { if (this.failed) { done(null); return; } var outputLines = function(asyncCmd: cm.IAsyncCommand) { asyncCmd.executionContext.info(' '); asyncCmd.executionContext.info('Start: ' + asyncCmd.description); asyncCmd.command.lines.forEach(function(line) { asyncCmd.executionContext.info(line); }); asyncCmd.executionContext.info('End: ' + asyncCmd.description); asyncCmd.executionContext.info(' '); } asyncCmd.runCommandAsync() .then(() => { outputLines(asyncCmd); }) .fail((err) => { this.failed = true; this.errorMessage = err.message; outputLines(asyncCmd); asyncCmd.executionContext.error(this.errorMessage); asyncCmd.executionContext.info('Failing task since command failed.') }) .fin(function() { done(null); }) }, (err: any) => { // queue never fails - we simply don't process items once one has failed. callback(null); }); } } } export class LogPageQueue extends BaseQueue<cm.ILogPageInfo> { private _recordToLogIdMap: { [recordId: string]: number } = {}; private _jobInfo: cm.IJobInfo; private _taskApi: taskm.ITaskApi; private _hostContext: ctxm.HostContext; private _service: cm.IServiceChannel; constructor(service: cm.IServiceChannel, hostContext: ctxm.HostContext, msDelay: number) { super(hostContext, msDelay); this._service = service; this._jobInfo = service.jobInfo; this._taskApi = service.getWebApi().getTaskApi(); this._hostContext = hostContext; } public _processQueue(logPages: cm.ILogPageInfo[], callback: (err: any) => void): void { trace.enter('LogQueue:processQueue: ' + logPages.length + ' pages to process'); if (logPages.length === 0) { callback(null); } else { for (var i = 0; i < logPages.length; i++) { trace.write('page: ' + logPages[i].pagePath); } var planId: string = this._jobInfo.planId; async.forEachSeries(logPages, (logPageInfo: cm.ILogPageInfo, done: (err: any) => void) => { var pagePath: string = logPageInfo.pagePath; trace.write('process:logPagePath: ' + pagePath); var recordId: string = logPageInfo.logInfo.recordId; trace.write('logRecordId: ' + recordId); var serverLogPath: string; var logId: number; var pageUploaded = false; async.series( [ (doneStep) => { trace.write('creating log record'); // // we only want to create the log metadata record once per // timeline record Id. So, create and put it in a map // if (!this._recordToLogIdMap.hasOwnProperty(logPageInfo.logInfo.recordId)) { serverLogPath = 'logs\\' + recordId; // FCS expects \ this._taskApi.createLog( <agentifm.TaskLog>{ path: serverLogPath }, this._jobInfo.variables[cm.vars.systemTeamProjectId], this._jobInfo.description, planId, (err: any, statusCode: number, log: agentifm.TaskLog) => { if (err) { trace.write('error creating log record: ' + err.message); doneStep(err); return; } // associate log with timeline recordId this._recordToLogIdMap[recordId] = log.id; trace.write('added log id to map: ' + log.id); doneStep(null); }); } else { doneStep(null); } }, (doneStep) => { // check logId in map first logId = this._recordToLogIdMap[recordId]; if (logId) { trace.write('uploading log page: ' + pagePath); fs.stat(pagePath, (err, stats) => { if (err) { trace.write('Error reading log file: ' + err.message); return; } var pageStream: NodeJS.ReadableStream = fs.createReadStream(pagePath); this._taskApi.appendLogContent( { "Content-Length": stats.size }, pageStream, this._jobInfo.variables[cm.vars.systemTeamProjectId], this._jobInfo.description, planId, logId, (err: any, statusCode: number, obj: any) => { if (err) { trace.write('error uploading log file: ' + err.message); } fs.unlink(pagePath, (err) => { // we're going to continue here so we can get the next logs // TODO: we should consider requeueing? doneStep(null); }); }); }); } else { this._hostContext.error('Skipping log upload. Log record does not exist.') doneStep(null); } }, (doneStep) => { var logRef = <agentifm.TaskLogReference>{}; logRef.id = logId; this._service.setLogId(recordId, logRef); doneStep(null); } ], (err: any) => { if (err) { this._hostContext.error(err.message); this._hostContext.error(JSON.stringify(logPageInfo)); } done(err); }); }, (err) => { callback(err); }); } } } // Job Renewal export class LockRenewer extends TimedWorker { constructor(jobInfo: cm.IJobInfo, poolId: number) { super(LOCK_DELAY); trace.enter('LockRenewer'); // finished is initially a resolved promise, because a renewal is not in progress this.finished = Q(null); this._jobInfo = jobInfo; this._poolId = poolId; trace.write('_poolId: ' + this._poolId); } private _poolId: number; private _agentApi: agentm.ITaskAgentApi; private _jobInfo: cm.IJobInfo; // consumers can use this promise to wait for the lock renewal to finish public finished: Q.Promise<any>; public doWork(): Q.Promise<any> { return this._renewLock(); } private _renewLock(): Q.Promise<any> { var jobRequest: agentifm.TaskAgentJobRequest = <agentifm.TaskAgentJobRequest>{}; jobRequest.requestId = this._jobInfo.requestId; // create a new, unresolved "finished" promise var deferred: Q.Deferred<any> = Q.defer(); this.finished = deferred.promise; process.send({ messageType: 'updateJobRequest', poolId: this._poolId, lockToken: this._jobInfo.lockToken, jobRequest: jobRequest }); deferred.resolve(null); return deferred.promise; } }
the_stack
import * as Clutter from 'clutter'; import * as GnomeDesktop from 'gnomedesktop'; import * as GObject from 'gobject'; import * as Shell from 'shell'; import { MsWorkspace } from 'src/layout/msWorkspace/msWorkspace'; import { PrimaryBorderEffect } from 'src/layout/msWorkspace/tilingLayouts/baseResizeableTiling'; import { AppsManager } from 'src/manager/appsManager'; import { Allocate, SetAllocation } from 'src/utils/compatibility'; import { registerGObjectClass } from 'src/utils/gjs'; import { ShellVersionMatch } from 'src/utils/shellVersionMatch'; import { SignalHandle } from 'src/utils/signal'; import { MatButton } from 'src/widget/material/button'; import * as St from 'st'; import { main as Main } from 'ui'; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); /* exported MsApplicationLauncher */ const BUTTON_SIZE = 124; @registerGObjectClass export class MsApplicationLauncher extends St.Widget { static metaInfo: GObject.MetaInfo = { GTypeName: 'MsApplicationLauncher', CssName: 'MsApplicationLauncher', }; appListContainer: MsApplicationButtonContainer; msWorkspace: MsWorkspace; focusEffects?: { dimmer: Clutter.BrightnessContrastEffect; border?: PrimaryBorderEffect; }; launcherChangedSignal: SignalHandle; installedChangedSignal: SignalHandle; constructor(msWorkspace: MsWorkspace) { super({ reactive: true, style: 'padding:64px', }); this.msWorkspace = msWorkspace; this.add_style_class_name('surface-darker'); this.appListContainer = new MsApplicationButtonContainer( this.msWorkspace ); this.initAppListContainer(); this.launcherChangedSignal = SignalHandle.connect( Me.msThemeManager, 'clock-app-launcher-changed', () => { this.restartAppListContainer(); } ); this.installedChangedSignal = SignalHandle.connect( Shell.AppSystem.get_default(), 'installed-changed', () => { this.restartAppListContainer(); } ); this.connect('key-focus-in', () => { this.appListContainer.inputContainer.grab_key_focus(); }); this.connect('parent-set', () => { if (this.msWorkspace.tileableFocused === this) { this.grab_key_focus(); } }); this.connect('key-focus-out', () => { //this._searchResults.highlightDefault(false); }); } onDestroy() { this.launcherChangedSignal.disconnect(); this.installedChangedSignal.disconnect(); } get dragged() { return false; } restartAppListContainer() { this.appListContainer.destroy(); this.appListContainer = new MsApplicationButtonContainer( this.msWorkspace ); this.initAppListContainer(); } initAppListContainer() { this.add_child(this.appListContainer); AppsManager.getApps().forEach((app) => { const button = new MsApplicationButton({ app, buttonSize: this.appListContainer.buttonSize, }); button.connect('notify::hover', () => { this.appListContainer.highlightButton(button); }); button.connect('clicked', () => { const { msWindow } = Me.msWindowManager.createNewMsWindow(app, { msWorkspace: this.msWorkspace, focus: true, insert: false, }); Me.msWindowManager.openAppForMsWindow(msWindow); this.appListContainer.reset(); }); this.appListContainer.addAppButton(button); }); this.appListContainer.initFilteredAppButtonList(); } vfunc_allocate(box: Clutter.ActorBox, flags?: Clutter.AllocationFlags) { SetAllocation(this, box, flags); const themeNode = this.get_theme_node(); const contentBox = themeNode.get_content_box(box); const containerBox = new Clutter.ActorBox(); const minSize = Math.min( contentBox.get_width(), contentBox.get_height() ); const workArea = Main.layoutManager.getWorkAreaForMonitor( this.msWorkspace.monitor.index ); const containerWidth = Math.min( contentBox.get_width() * 0.8, workArea.width / 2 ); containerBox.x1 = Math.round( contentBox.x1 + (contentBox.get_width() - containerWidth) / 2 ); containerBox.x2 = Math.round( contentBox.x2 - (contentBox.get_width() - containerWidth) / 2 ); containerBox.y1 = Math.round(contentBox.y1 + 0.1 * minSize); containerBox.y2 = Math.round(contentBox.y2 - 0.1 * minSize); // Prevent odd number size to have proper font aliasing containerBox.x2 = containerBox.get_width() % 2 != 0 ? containerBox.x2 + 1 : containerBox.x2; containerBox.y2 = containerBox.get_height() % 2 != 0 ? containerBox.y2 + 1 : containerBox.y2; Allocate(this.appListContainer, containerBox, flags); } } @registerGObjectClass export class MsApplicationButtonContainer extends St.Widget { appButtonList: MsApplicationButton[]; currentButtonFocused: MsApplicationButton | null; clockLabel: St.Label | undefined; dateLabel: St.Label | undefined; clockBin: St.BoxLayout | undefined; private _wallClock: any; signalClock: any; inputLayout: St.BoxLayout; searchIcon: St.Icon; inputContainer: St.Entry; private _text: Clutter.Text; filteredAppButtonListBuffer: MsApplicationButton[]; container: St.Widget; msWorkspace: MsWorkspace; filteredAppButtonList: MsApplicationButton[]; startIndex: number; numberOfColumn: number; numberOfRow: number; maxIndex: number; constructor(msWorkspace: MsWorkspace) { super({}); this.msWorkspace = msWorkspace; this.appButtonList = []; this.filteredAppButtonList = []; this.filteredAppButtonListBuffer = []; this.currentButtonFocused = null; this.startIndex = 0; // These will be updated to more accurate values // when vfunc_allocate runs this.numberOfRow = 1; this.numberOfColumn = 1; this.maxIndex = 1; if (Me.msThemeManager.clockAppLauncher) { this.clockLabel = new St.Label({ style_class: 'headline-6 text-medium-emphasis margin-right-x2', y_align: Clutter.ActorAlign.CENTER, }); this.dateLabel = new St.Label({ style_class: 'headline-6 text-medium-emphasis', y_align: Clutter.ActorAlign.CENTER, }); this.clockBin = new St.BoxLayout({ x_align: Clutter.ActorAlign.CENTER, }); this.clockBin.add_child(this.clockLabel); this.clockBin.add_child(this.dateLabel); this._wallClock = new GnomeDesktop.WallClock({ time_only: true, }); const updateClock = () => { if (this.clockLabel!.mapped) { this.clockLabel!.text = this._wallClock.clock; const date = new Date(); const dateFormat = Shell.util_translate_time_string( N_('%A %B %-d') ); // TODO: toLocaleFormat is deprecated this.dateLabel!.text = date.toLocaleFormat(dateFormat); } }; this.signalClock = this._wallClock.connect( 'notify::clock', updateClock ); // There was a bug when updating the clock while the clock was not in the stage which didn't update the time correct this.clockLabel.connect('notify::mapped', () => { if (this.clockLabel!.mapped) { updateClock(); this.clockLabel!.queue_relayout(); } }); this.clockLabel.connect('destroy', () => { this._wallClock.disconnect(this.signalClock); delete this._wallClock; }); this.add_child(this.clockBin); } this.inputLayout = new St.BoxLayout({}); this.searchIcon = new St.Icon({ style_class: 'search-entry-icon', icon_name: 'edit-find-symbolic', }); this.inputContainer = new St.Entry({ style_class: 'search-entry', /* Translators: this is the text displayed in the search entry when no search is active; it should not exceed ~30 characters. */ hint_text: _('Type to search…'), track_hover: true, can_focus: true, }); this.inputContainer.set_primary_icon(this.searchIcon); this._text = this.inputContainer.clutter_text; this._text.connect('text-changed', () => { this.updateFilteredAppButtonList(); this.highlightInitialButton(); }); this._text.connect('key-press-event', (entry, event) => { const symbol = event.get_key_symbol(); if (ShellVersionMatch('3.34')) { switch (symbol) { case Clutter.KEY_Escape: this.reset(); // Reset both this.removeHighlightButton(); return Clutter.EVENT_STOP; case Clutter.KEY_Tab: this.highlightNextButton(); return Clutter.EVENT_STOP; case Clutter.KEY_ISO_Left_Tab: this.highlightPreviousButton(); return Clutter.EVENT_STOP; case Clutter.KEY_Down: this.highlightButtonBelow(); return Clutter.EVENT_STOP; case Clutter.KEY_Up: this.highlightButtonAbove(); return Clutter.EVENT_STOP; case Clutter.KEY_Right: if (this._text.cursor_position === -1) { this.highlightNextButton(); return Clutter.EVENT_STOP; } else { return Clutter.EVENT_PROPAGATE; } case Clutter.KEY_Left: if ( this.filteredAppButtonList.length > 0 && this.currentButtonFocused != this.filteredAppButtonList[0] ) { this.highlightPreviousButton(); return Clutter.EVENT_STOP; } else { return Clutter.EVENT_PROPAGATE; } case Clutter.KEY_Return: case Clutter.KEY_KP_Enter: if (this.currentButtonFocused) this.currentButtonFocused.emit('clicked', 0); return Clutter.EVENT_STOP; } } else { switch (symbol) { case Clutter.KEY_Escape: this.reset(); // Reset both this.removeHighlightButton(); return Clutter.EVENT_STOP; case Clutter.KEY_Tab: this.highlightNextButton(); return Clutter.EVENT_STOP; case Clutter.KEY_ISO_Left_Tab: this.highlightPreviousButton(); return Clutter.EVENT_STOP; case Clutter.KEY_Down: this.highlightButtonBelow(); return Clutter.EVENT_STOP; case Clutter.KEY_Up: this.highlightButtonAbove(); return Clutter.EVENT_STOP; case Clutter.KEY_Right: if (this._text.cursor_position === -1) { this.highlightNextButton(); return Clutter.EVENT_STOP; } else { return Clutter.EVENT_PROPAGATE; } case Clutter.KEY_Left: if ( this.currentButtonFocused != this.filteredAppButtonListBuffer[0] && this.getCurrentIndex() > -1 ) { this.highlightPreviousButton(); return Clutter.EVENT_STOP; } else { return Clutter.EVENT_PROPAGATE; } case Clutter.KEY_Return: case Clutter.KEY_KP_Enter: if (this.currentButtonFocused) this.currentButtonFocused.emit('clicked', 0); return Clutter.EVENT_STOP; } } return Clutter.EVENT_PROPAGATE; }); this.add_child(this.inputContainer); this.container = new St.Widget(); this.container.add_style_class_name('surface'); this.container.set_style('border-radius:16px;'); this.add_child(this.container); } get monitorScale() { return global.display.get_monitor_scale(this.msWorkspace.monitor.index); } get buttonSize() { return BUTTON_SIZE * this.monitorScale; } reset() { //Go back to the previous window if ESC is pressed and nothing is selected if ( this.inputContainer.get_text() === '' && this.currentButtonFocused === null ) { this.msWorkspace.focusPrecedentTileable(); return; } if (this.inputContainer.get_text().length) { this.inputContainer.set_text(''); this._text.cursor_position = -1; return; } this.updateFilteredAppButtonList(); } initFilteredAppButtonList() { this.filteredAppButtonList = this.appButtonList; this.filteredAppButtonListBuffer = this.appButtonList; this.startIndex = 0; } updateFilteredAppButtonList() { this.filteredAppButtonListBuffer = this.appButtonList.filter( (button) => { const stringToSearch = `${button.app.get_name()}${button.app.get_id()}${button.app.get_description()}`; const regex = new RegExp(this.inputContainer.get_text(), 'i'); if (regex.test(stringToSearch)) { button.visible = true; return true; } else { button.visible = false; return false; } } ); this.filteredAppButtonList = []; const maxButtons = this.numberOfColumn * this.numberOfRow; let index = 0; while ( index < maxButtons && index < this.filteredAppButtonListBuffer.length ) { this.filteredAppButtonList.push( this.filteredAppButtonListBuffer[index] ); index++; } this.startIndex = 0; } scrollFilteredAppButtonListUp() { const maxButtons = this.numberOfColumn * this.numberOfRow; if ( this.startIndex + maxButtons > this.filteredAppButtonListBuffer.length - 1 ) { return false; } const maxColumns = this.numberOfColumn; let index = 0; let showIndex: number; this.startIndex += maxColumns; while (index < this.startIndex) { if ( this.filteredAppButtonListBuffer && this.filteredAppButtonListBuffer[index] ) { this.filteredAppButtonListBuffer[index].visible = false; } index++; } this.filteredAppButtonList = []; index = 0; while ( index < maxButtons && index < this.filteredAppButtonListBuffer.length ) { showIndex = this.startIndex + index; if ( this.filteredAppButtonListBuffer && this.filteredAppButtonListBuffer[showIndex] ) { this.filteredAppButtonListBuffer[showIndex].visible = true; this.filteredAppButtonList.push( this.filteredAppButtonListBuffer[showIndex] ); } index++; } return true; } scrollFilteredAppButtonListDown() { const maxColumns = this.numberOfColumn; if (this.startIndex - maxColumns < 0) { return false; } let index = 0; let showIndex: number; const maxButtons = this.numberOfColumn * this.numberOfRow; this.startIndex -= maxColumns; this.filteredAppButtonList = []; while ( index < maxButtons && index < this.filteredAppButtonListBuffer.length ) { showIndex = this.startIndex + index; if ( this.filteredAppButtonListBuffer && this.filteredAppButtonListBuffer[showIndex] ) { this.filteredAppButtonListBuffer[showIndex].visible = true; this.filteredAppButtonList.push( this.filteredAppButtonListBuffer[showIndex] ); } index++; } return true; } // Get current focused button index, highlights the initial button if current button is invalid (but returns -1 in that case) getCurrentIndex() { const index = this.currentButtonFocused ? this.filteredAppButtonList.indexOf(this.currentButtonFocused) : -1; if (index < 0 || index > this.maxIndex) { this.highlightInitialButton(); } return index; } highlightNextButton() { let currentIndex = this.getCurrentIndex(); if (currentIndex < 0) { return; } else if (currentIndex == this.maxIndex) { if (this.scrollFilteredAppButtonListUp()) { currentIndex -= this.numberOfColumn; } else { return; } } if (currentIndex < this.filteredAppButtonList.length - 1) { this.highlightButton(this.filteredAppButtonList[currentIndex + 1]); } } highlightPreviousButton() { let currentIndex = this.getCurrentIndex(); if (currentIndex > 0) { this.highlightButton(this.filteredAppButtonList[currentIndex - 1]); } else if (currentIndex === 0) { if (this.scrollFilteredAppButtonListDown()) { currentIndex += this.numberOfColumn - 1; this.highlightButton(this.filteredAppButtonList[currentIndex]); } } } highlightButtonAbove() { let currentIndex = this.getCurrentIndex(); if (currentIndex < this.numberOfColumn) { if (this.scrollFilteredAppButtonListDown()) { currentIndex += this.numberOfColumn; } } const nextButton = this.filteredAppButtonList[currentIndex - this.numberOfColumn]; if (nextButton) { this.highlightButton(nextButton); } } highlightButtonBelow() { let currentIndex = this.getCurrentIndex(); if (currentIndex < 0) { return; } else if (currentIndex + this.numberOfColumn > this.maxIndex) { if (this.scrollFilteredAppButtonListUp()) { currentIndex -= this.numberOfColumn; } else { return; } } const nextButton = this.filteredAppButtonList[currentIndex + this.numberOfColumn]; if (nextButton) { this.highlightButton(nextButton); } } highlightButton(button: MsApplicationButton) { if (button) { if (this.currentButtonFocused) { this.currentButtonFocused.remove_style_class_name( 'highlighted' ); } this.currentButtonFocused = button; this.currentButtonFocused.add_style_class_name('highlighted'); } } // Set starting button as focused highlightInitialButton() { if ( this.filteredAppButtonList && this.filteredAppButtonList.length > 0 ) { this.highlightButton(this.filteredAppButtonList[0]); } } // Remove focus removeHighlightButton() { if (this.currentButtonFocused) { this.currentButtonFocused.remove_style_class_name('highlighted'); } if (this.filteredAppButtonList) { this.currentButtonFocused = null; } } addAppButton(button: MsApplicationButton) { this.appButtonList.push(button); this.add_child(button); } vfunc_allocate(box: Clutter.ActorBox, flags?: Clutter.AllocationFlags) { SetAllocation(this, box, flags); const themeNode = this.get_theme_node(); const contentBox = themeNode.get_content_box(box); const containerPadding = 16 * this.monitorScale; const clockHeight = (Me.msThemeManager.clockAppLauncher ? 64 : 0) * this.monitorScale; const searchHeight = 48 * this.monitorScale; const searchMargin = 24 * this.monitorScale; const availableWidth = contentBox.get_width() - containerPadding * 2; const availableHeight = contentBox.get_height() - containerPadding * 2 - searchHeight - searchMargin - clockHeight; const numberOfButtons = this.filteredAppButtonList.length; this.numberOfColumn = Math.floor(availableWidth / this.buttonSize); this.numberOfRow = Math.floor(availableHeight / this.buttonSize); const numberOfRowNeeded = Math.ceil( numberOfButtons / this.numberOfColumn ); this.maxIndex = this.numberOfColumn * Math.min(this.numberOfRow, numberOfRowNeeded) - 1; const horizontalOffset = (contentBox.get_width() - (this.buttonSize * this.numberOfColumn + containerPadding * 2)) / 2; const verticalOffset = (contentBox.get_height() - (this.buttonSize * this.numberOfRow + containerPadding * 2 + searchHeight + searchMargin + clockHeight)) / 2; if (this.clockBin) { const clockBox = new Clutter.ActorBox(); clockBox.x1 = contentBox.x1 + horizontalOffset + containerPadding; clockBox.x2 = contentBox.x2 - horizontalOffset - containerPadding; clockBox.y1 = contentBox.y1 + verticalOffset; clockBox.y2 = clockBox.y1 + clockHeight; Allocate(this.clockBin, clockBox, flags); } const searchBox = new Clutter.ActorBox(); searchBox.x1 = contentBox.x1 + horizontalOffset; searchBox.x2 = contentBox.x2 - horizontalOffset; searchBox.y1 = contentBox.y1 + verticalOffset + clockHeight; searchBox.y2 = searchBox.y1 + searchHeight; Allocate(this.inputContainer, searchBox, flags); const containerBox = new Clutter.ActorBox(); containerBox.x1 = contentBox.x1 + horizontalOffset; containerBox.x2 = contentBox.x2 - horizontalOffset; containerBox.y1 = contentBox.y1 + verticalOffset + searchHeight + searchMargin + clockHeight; containerBox.y2 = contentBox.y2 - verticalOffset; Allocate(this.container, containerBox, flags); let index = 0; for (let y = 0; y < this.numberOfRow; y++) { for (let x = 0; x < this.numberOfColumn; x++) { index = x + this.numberOfColumn * y; if (index < this.filteredAppButtonList.length) { const button = this.filteredAppButtonList[index]; const buttonBox = new Clutter.ActorBox(); buttonBox.x1 = containerBox.x1 + this.buttonSize * x + containerPadding; buttonBox.x2 = buttonBox.x1 + this.buttonSize; buttonBox.y1 = containerBox.y1 + this.buttonSize * y + containerPadding; buttonBox.y2 = buttonBox.y1 + this.buttonSize; button.visible = true; Allocate(button, buttonBox, flags); } } } for (let i = index + 1; i < numberOfButtons; i++) { this.filteredAppButtonList[i].visible = false; } //hide other buttons this.appButtonList .filter((button) => { return !this.filteredAppButtonList.includes(button); }) .forEach((button) => { this.hideButton(button, contentBox, flags); }); // Reset focused button to position zero if hidden if (this.currentButtonFocused) { this.getCurrentIndex(); } } hideButton( button: MsApplicationButton, contentBox: Clutter.ActorBox, flags?: Clutter.AllocationFlags ) { const hiddenBox = new Clutter.ActorBox(); hiddenBox.x1 = contentBox.x1; hiddenBox.x2 = contentBox.x1; hiddenBox.y1 = contentBox.x1; hiddenBox.y2 = contentBox.x1; Allocate(button, hiddenBox, flags); button.visible = false; } } @registerGObjectClass export class MsApplicationButton extends MatButton { static metaInfo: GObject.MetaInfo = { GTypeName: 'MsApplicationButton', }; app: Shell.App; buttonSize: number; layout: St.BoxLayout; icon: any; title: St.Label | undefined; constructor({ app, buttonSize }: { app: Shell.App; buttonSize: number }) { super({}); this.app = app; this.buttonSize = buttonSize; this.layout = new St.BoxLayout({ vertical: true, width: this.buttonSize, height: this.buttonSize, clip_to_allocation: true, }); if (app) { this.icon = this.app.create_icon_texture(72); this.title = new St.Label({ text: this.app.get_name(), x_align: Clutter.ActorAlign.CENTER, style_class: 'subtitle-2', style: 'margin-top:12px', }); this.layout.add_child(this.icon); this.layout.add_child(this.title); Me.tooltipManager.add(this.title, { relativeActor: this }); } this.layout.set_style('padding:12px;'); this.set_child(this.layout); } }
the_stack
"use strict"; // // TGALoader // class TGALoader { static version = 1; gd : WebGLGraphicsDevice; src : string; data : Uint8Array; onload : { (data: Uint8Array, width: number, height: number, format: number, status : number): void; }; onerror : { (status: number): void; }; width : number; height : number; bytesPerPixel : number; horzRev : boolean; vertRev : boolean; format : number; colorMap : number[]; colorMapBytesPerPixel: number; TYPE_MAPPED : number; // prototype TYPE_COLOR : number; // prototype TYPE_GRAY : number; // prototype TYPE_MAPPED_RLE : number; // prototype TYPE_COLOR_RLE : number; // prototype TYPE_GRAY_RLE : number; // prototype DESC_ABITS : number; // prototype DESC_HORIZONTAL : number; // prototype DESC_VERTICAL : number; // prototype SIGNATURE : string; // prototype RLE_PACKETSIZE : number; // prototype processBytes(bytes) { var header = this.parseHeader(bytes); if (!this.isValidHeader(header)) { return; } var offset = 18; this.width = header.width; this.height = header.height; this.bytesPerPixel = Math.floor(header.bpp / 8); /*jshint bitwise: false*/ this.horzRev = <boolean><any>(header.descriptor & this.DESC_HORIZONTAL); this.vertRev = !(header.descriptor & this.DESC_VERTICAL); /*jshint bitwise: true*/ var rle = false; var gd = this.gd; switch (header.imageType) { case this.TYPE_MAPPED_RLE: rle = true; if (header.colorMapSize > 24) { this.format = gd.PIXELFORMAT_R8G8B8A8; } else if (header.colorMapSize > 16) { this.format = gd.PIXELFORMAT_R8G8B8; } else { this.format = gd.PIXELFORMAT_R5G5B5A1; } break; case this.TYPE_MAPPED: if (header.colorMapSize > 24) { this.format = gd.PIXELFORMAT_R8G8B8A8; } else if (header.colorMapSize > 16) { this.format = gd.PIXELFORMAT_R8G8B8; } else { this.format = gd.PIXELFORMAT_R5G5B5A1; } break; case this.TYPE_GRAY_RLE: rle = true; this.format = gd.PIXELFORMAT_L8; break; case this.TYPE_GRAY: this.format = gd.PIXELFORMAT_L8; break; case this.TYPE_COLOR_RLE: rle = true; switch (this.bytesPerPixel) { case 4: this.format = gd.PIXELFORMAT_R8G8B8A8; break; case 3: this.format = gd.PIXELFORMAT_R8G8B8; break; case 2: this.format = gd.PIXELFORMAT_R5G5B5A1; break; default: return; } break; case this.TYPE_COLOR: switch (this.bytesPerPixel) { case 4: this.format = gd.PIXELFORMAT_R8G8B8A8; break; case 3: this.format = gd.PIXELFORMAT_R8G8B8; break; case 2: this.format = gd.PIXELFORMAT_R5G5B5A1; break; default: return; } break; default: return; } // Skip the image ID field. if (header.idLength) { offset += header.idLength; if (offset > bytes.length) { return; } } if (this.TYPE_MAPPED_RLE === header.imageType || this.TYPE_MAPPED === header.imageType) { if (header.colorMapType !== 1) { return; } } else if (header.colorMapType !== 0) { return; } if (header.colorMapType === 1) { var index = header.colorMapIndex; var length = header.colorMapLength; if (length === 0) { return; } var pelbytes = Math.floor(header.colorMapSize / 8); var numColors = (length + index); var colorMap = []; colorMap.length = (numColors * pelbytes); this.colorMap = colorMap; this.colorMapBytesPerPixel = pelbytes; // Zero the entries up to the beginning of the map var j; for (j = 0; j < (index * pelbytes); j += 1) { colorMap[j] = 0; } // Read in the rest of the colormap for (j = (index * pelbytes); j < (index * pelbytes); j += 1, offset += 1) { colorMap[j] = bytes[offset]; } offset += (length * pelbytes); if (offset > bytes.length) { return; } if (pelbytes >= 3) { // Rearrange the colors from BGR to RGB for (j = (index * pelbytes); j < (length * pelbytes); j += pelbytes) { var tmp = colorMap[j]; colorMap[j] = colorMap[j + 2]; colorMap[j + 2] = tmp; } } } var data = bytes.subarray(offset); bytes = null; if (rle) { data = this.expandRLE(data); } var size = (this.width * this.height * this.bytesPerPixel); if (data.length < size) { return; } if (this.horzRev) { this.flipHorz(data); } if (this.vertRev) { this.flipVert(data); } if (this.colorMap) { data = this.expandColorMap(data); } else if (2 < this.bytesPerPixel) { this.convertBGR2RGB(data); } else if (2 === this.bytesPerPixel) { data = this.convertARGB2RGBA(data); } this.data = data; } parseHeader(bytes) { /*jshint bitwise: false*/ var header = { idLength : bytes[0], colorMapType : bytes[1], imageType : bytes[2], colorMapIndex : ((bytes[4] << 8) | bytes[3]), colorMapLength : ((bytes[6] << 8) | bytes[5]), colorMapSize : bytes[7], xOrigin : ((bytes[9] << 8) | bytes[8]), yOrigin : ((bytes[11] << 8) | bytes[10]), width : ((bytes[13] << 8) | bytes[12]), height : ((bytes[15] << 8) | bytes[14]), bpp : bytes[16], // Image descriptor: // 3-0: attribute bpp // 4: left-to-right // 5: top-to-bottom // 7-6: zero descriptor : bytes[17] }; /*jshint bitwise: true*/ return header; } isValidHeader(header) { if (this.TYPE_MAPPED_RLE === header.imageType || this.TYPE_MAPPED === header.imageType) { if (header.colorMapType !== 1) { return false; } } else if (header.colorMapType !== 0) { return false; } if (header.colorMapType === 1) { if (header.colorMapLength === 0) { return false; } } switch (header.imageType) { case this.TYPE_MAPPED_RLE: case this.TYPE_MAPPED: break; case this.TYPE_GRAY_RLE: case this.TYPE_GRAY: break; case this.TYPE_COLOR_RLE: case this.TYPE_COLOR: switch (Math.floor(header.bpp / 8)) { case 4: case 3: case 2: break; default: return false; } break; default: return false; } if (16384 < header.width) { return false; } if (16384 < header.height) { return false; } return true; } expandRLE(data) { var pelbytes = this.bytesPerPixel; var width = this.width; var height = this.height; var datasize = pelbytes; var size = (width * height * pelbytes); var RLE_PACKETSIZE = this.RLE_PACKETSIZE; var dst = new Uint8Array(size); var src = 0, dest = 0, n, k; do { var count = data[src]; src += 1; /*jshint bitwise: false*/ var bytes = (((count & ~RLE_PACKETSIZE) + 1) * datasize); if (count & RLE_PACKETSIZE) { // Optimized case for single-byte encoded data if (datasize === 1) { var r = data[src]; src += 1; for (n = 0; n < bytes; n += 1) { dst[dest + k] = r; } } else { // Fill the buffer with the next value for (n = 0; n < datasize; n += 1) { dst[dest + n] = data[src + n]; } src += datasize; for (k = datasize; k < bytes; k += datasize) { for (n = 0; n < datasize; n += 1) { dst[dest + k + n] = dst[dest + n]; } } } } else { // Read in the buffer for (n = 0; n < bytes; n += 1) { dst[dest + n] = data[src + n]; } src += bytes; } /*jshint bitwise: true*/ dest += bytes; } while (dest < size); return dst; } expandColorMap(data) { // Unpack image var pelbytes = this.bytesPerPixel; var width = this.width; var height = this.height; var size = (width * height * pelbytes); var dst = new Uint8Array(size); var dest = 0, src = 0; var palette = this.colorMap; delete this.colorMap; if (pelbytes === 2 || pelbytes === 3 || pelbytes === 4) { do { var index = (data[src] * pelbytes); src += 1; for (var n = 0; n < pelbytes; n += 1) { dst[dest] = palette[index + n]; dest += 1; } } while (dest < size); } if (pelbytes === 2) { dst = this.convertARGB2RGBA(dst); } return dst; } flipHorz(data) { var pelbytes = this.bytesPerPixel; var width = this.width; var height = this.height; var halfWidth = Math.floor(width / 2); var pitch = (width * pelbytes); for (var i = 0; i < height; i += 1) { for (var j = 0; j < halfWidth; j += 1) { for (var k = 0; k < pelbytes; k += 1) { var tmp = data[j * pelbytes + k]; data[j * pelbytes + k] = data[(width - j - 1) * pelbytes + k]; data[(width - j - 1) * pelbytes + k] = tmp; } } data += pitch; } } flipVert(data) { var pelbytes = this.bytesPerPixel; var width = this.width; var height = this.height; var halfHeight = Math.floor(height / 2); var pitch = (width * pelbytes); for (var i = 0; i < halfHeight; i += 1) { var srcRow = (i * pitch); var destRow = ((height - i - 1) * pitch); for (var j = 0; j < pitch; j += 1) { var tmp = data[srcRow + j]; data[srcRow + j] = data[destRow + j]; data[destRow + j] = tmp; } } } convertBGR2RGB(data) { // Rearrange the colors from BGR to RGB var bytesPerPixel = this.bytesPerPixel; var width = this.width; var height = this.height; var size = (width * height * bytesPerPixel); var offset = 0; do { var tmp = data[offset]; data[offset] = data[offset + 2]; data[offset + 2] = tmp; offset += bytesPerPixel; } while (offset < size); } convertARGB2RGBA(data) { // Rearrange the colors from ARGB to RGBA (2 bytes) var bytesPerPixel = this.bytesPerPixel; if (bytesPerPixel === 2) { var width = this.width; var height = this.height; var size = (width * height * bytesPerPixel); var dst = new Uint16Array(width * height); var src = 0, dest = 0; var r, g, b, a; /*jshint bitwise: false*/ var mask = ((1 << 5) - 1); var blueMask = mask; var greenMask = (mask << 5); var redMask = (mask << 10); //var alphaMask = (1 << 15); do { var value = ((src[1] << 8) | src[0]); src += 2; b = (value & blueMask) << 1; g = (value & greenMask) << 1; r = (value & redMask) << 1; a = (value >> 15); dst[dest] = r | g | b | a; dest += 1; } while (src < size); /*jshint bitwise: true*/ return dst; } else { return data; } } static create(params: any) : TGALoader { var loader = new TGALoader(); loader.gd = params.gd; loader.onload = params.onload; loader.onerror = params.onerror; var src = params.src; if (src) { loader.src = src; var xhr; if (window.XMLHttpRequest) { xhr = new window.XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); } else { if (params.onerror) { params.onerror(0); } return null; } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (!TurbulenzEngine || !TurbulenzEngine.isUnloading()) { var xhrStatus = xhr.status; var xhrStatusText = xhr.status !== 0 && xhr.statusText || 'No connection'; // Fix for loading from file if (xhrStatus === 0 && (window.location.protocol === "file:" || window.location.protocol === "chrome-extension:")) { xhrStatus = 200; } // Sometimes the browser sets status to 200 OK when the connection is closed // before the message is sent (weird!). // In order to address this we fail any completely empty responses. // Hopefully, nobody will get a valid response with no headers and no body! if (xhr.getAllResponseHeaders() === "") { var noBody; if (xhr.responseType === "arraybuffer") { noBody = !xhr.response; } else if (xhr.mozResponseArrayBuffer) { noBody = !xhr.mozResponseArrayBuffer; } else { noBody = !xhr.responseText; } if (noBody) { if (loader.onerror) { loader.onerror(0); } // break circular reference xhr.onreadystatechange = null; xhr = null; return; } } if (xhrStatus === 200 || xhrStatus === 0) { var buffer; if (xhr.responseType === "arraybuffer") { buffer = xhr.response; } else if (xhr.mozResponseArrayBuffer) { buffer = xhr.mozResponseArrayBuffer; } else //if (xhr.responseText !== null) { /*jshint bitwise: false*/ var text = xhr.responseText; var numChars = text.length; buffer = []; buffer.length = numChars; for (var i = 0; i < numChars; i += 1) { buffer[i] = (text.charCodeAt(i) & 0xff); } /*jshint bitwise: true*/ } loader.processBytes(new Uint8Array(buffer)); if (loader.data) { if (loader.onload) { loader.onload(loader.data, loader.width, loader.height, loader.format, xhrStatus); } } else { if (loader.onerror) { loader.onerror(xhrStatus); } } } else { if (loader.onerror) { loader.onerror(xhrStatus); } } } // break circular reference xhr.onreadystatechange = null; xhr = null; } }; xhr.open("GET", params.src, true); if (typeof xhr.responseType === "string" || (xhr.hasOwnProperty && xhr.hasOwnProperty("responseType"))) { xhr.responseType = "arraybuffer"; } else if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain; charset=x-user-defined"); } else { xhr.setRequestHeader("Content-Type", "text/plain; charset=x-user-defined"); } xhr.send(null); } else { loader.processBytes(params.data); if (loader.data) { if (loader.onload) { loader.onload(loader.data, loader.width, loader.height, loader.format, 200); } } else { if (loader.onerror) { loader.onerror(0); } } } return loader; } } TGALoader.prototype.TYPE_MAPPED = 1; TGALoader.prototype.TYPE_COLOR = 2; TGALoader.prototype.TYPE_GRAY = 3; TGALoader.prototype.TYPE_MAPPED_RLE = 9; TGALoader.prototype.TYPE_COLOR_RLE = 10; TGALoader.prototype.TYPE_GRAY_RLE = 11; TGALoader.prototype.DESC_ABITS = 0x0f; TGALoader.prototype.DESC_HORIZONTAL = 0x10; TGALoader.prototype.DESC_VERTICAL = 0x20; TGALoader.prototype.SIGNATURE = "TRUEVISION-XFILE"; TGALoader.prototype.RLE_PACKETSIZE = 0x80;
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the MachineLearningWorkspacesManagementClient. */ export interface Operations { /** * Lists all of the available Azure Machine Learning Studio REST API * operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available Azure Machine Learning Studio REST API * operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; } /** * @class * Workspaces * __NOTE__: An instance of this class is automatically created for an * instance of the MachineLearningWorkspacesManagementClient. */ export interface Workspaces { /** * Gets the properties of the specified machine learning workspace. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Workspace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>; /** * Gets the properties of the specified machine learning workspace. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Workspace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Workspace} [result] - The deserialized result object if an error did not occur. * See {@link Workspace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>; get(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.Workspace>): void; get(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void; /** * Creates or updates a workspace with the specified parameters. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {object} parameters The parameters for creating or updating a machine * learning workspace. * * @param {string} parameters.userStorageAccountId The fully qualified arm id * of the storage account associated with this workspace. * * @param {string} [parameters.ownerEmail] The email id of the owner for this * workspace. * * @param {string} [parameters.keyVaultIdentifierId] The key vault identifier * used for encrypted workspaces. * * @param {string} parameters.location The location of the resource. This * cannot be changed after the resource is created. * * @param {object} [parameters.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Workspace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>; /** * Creates or updates a workspace with the specified parameters. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {object} parameters The parameters for creating or updating a machine * learning workspace. * * @param {string} parameters.userStorageAccountId The fully qualified arm id * of the storage account associated with this workspace. * * @param {string} [parameters.ownerEmail] The email id of the owner for this * workspace. * * @param {string} [parameters.keyVaultIdentifierId] The key vault identifier * used for encrypted workspaces. * * @param {string} parameters.location The location of the resource. This * cannot be changed after the resource is created. * * @param {object} [parameters.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Workspace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Workspace} [result] - The deserialized result object if an error did not occur. * See {@link Workspace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>; createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, callback: ServiceCallback<models.Workspace>): void; createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void; /** * Deletes a machine learning workspace. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a machine learning workspace. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Updates a machine learning workspace with the specified parameters. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {object} parameters The parameters for updating a machine learning * workspace. * * @param {object} [parameters.tags] The resource tags for the machine learning * workspace. * * @param {string} [parameters.workspaceState] The current state of workspace * resource. Possible values include: 'Deleted', 'Enabled', 'Disabled', * 'Migrated', 'Updated', 'Registered', 'Unregistered' * * @param {string} [parameters.keyVaultIdentifierId] The key vault identifier * used for encrypted workspaces. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Workspace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>; /** * Updates a machine learning workspace with the specified parameters. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {object} parameters The parameters for updating a machine learning * workspace. * * @param {object} [parameters.tags] The resource tags for the machine learning * workspace. * * @param {string} [parameters.workspaceState] The current state of workspace * resource. Possible values include: 'Deleted', 'Enabled', 'Disabled', * 'Migrated', 'Updated', 'Registered', 'Unregistered' * * @param {string} [parameters.keyVaultIdentifierId] The key vault identifier * used for encrypted workspaces. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Workspace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Workspace} [result] - The deserialized result object if an error did not occur. * See {@link Workspace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>; update(resourceGroupName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, callback: ServiceCallback<models.Workspace>): void; update(resourceGroupName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void; /** * Resync storage keys associated with this workspace. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ resyncStorageKeysWithHttpOperationResponse(workspaceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Resync storage keys associated with this workspace. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ resyncStorageKeys(workspaceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; resyncStorageKeys(workspaceName: string, resourceGroupName: string, callback: ServiceCallback<void>): void; resyncStorageKeys(workspaceName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * List the authorization keys associated with this workspace. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceKeysResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWorkspaceKeysWithHttpOperationResponse(workspaceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceKeysResponse>>; /** * List the authorization keys associated with this workspace. * * @param {string} workspaceName The name of the machine learning workspace. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceKeysResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceKeysResponse} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceKeysResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listWorkspaceKeys(workspaceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceKeysResponse>; listWorkspaceKeys(workspaceName: string, resourceGroupName: string, callback: ServiceCallback<models.WorkspaceKeysResponse>): void; listWorkspaceKeys(workspaceName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceKeysResponse>): void; /** * Lists all the available machine learning workspaces under the specified * resource group. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>; /** * Lists all the available machine learning workspaces under the specified * resource group. * * @param {string} resourceGroupName The name of the resource group to which * the machine learning workspace belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.WorkspaceListResult>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void; /** * Lists all the available machine learning workspaces under the specified * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>; /** * Lists all the available machine learning workspaces under the specified * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>; list(callback: ServiceCallback<models.WorkspaceListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void; /** * Lists all the available machine learning workspaces under the specified * resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>; /** * Lists all the available machine learning workspaces under the specified * resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.WorkspaceListResult>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void; /** * Lists all the available machine learning workspaces under the specified * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>; /** * Lists all the available machine learning workspaces under the specified * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.WorkspaceListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void; }
the_stack
import React from 'react'; import ReactDOM from 'react-dom'; import {StreamEvent} from '../Event/StreamEvent'; import {PrefCoverFragment} from './Pref/PrefCoverFragment'; import {LibraryStreamsFragment} from './Stream/LibraryStream/LibraryStreamsFragment'; import {SystemStreamsFragment} from './Stream/SystemStream/SystemStreamsFragment'; import {UserStreamsFragment} from './Stream/UserStream/UserStreamsFragment'; import {IssuesFragment} from './Issues/IssuesFragment'; import {BrowserFragment} from './Browser/BrowserFragment'; import {UserPrefRepo} from '../Repository/UserPrefRepo'; import {GARepo} from '../Repository/GARepo'; import {StreamPolling} from '../Repository/Polling/StreamPolling'; import {StreamSetup} from '../Repository/Setup/StreamSetup'; import {DBSetup} from '../Repository/Setup/DBSetup'; import {VersionPolling} from '../Repository/Polling/VersionPolling'; import {PrefSetupFragment} from './Pref/PrefSetupFragment'; import {UserPrefEntity} from '../Library/Type/UserPrefEntity'; import {MainWindowIPC} from '../../IPC/MainWindowIPC'; import {AboutFragment} from './Other/AboutFragment'; import {TimerUtil} from '../Library/Util/TimerUtil'; import styled, {createGlobalStyle} from 'styled-components'; import {View} from '../Library/View/View'; import {appTheme} from '../Library/Style/appTheme'; import {border, font} from '../Library/Style/layout'; import {NotificationFragment} from './Other/NotificationFragment'; import {KeyboardShortcutFragment} from './Other/KeyboardShortcutFragment'; import {UserPrefIPC} from '../../IPC/UserPrefIPC'; import {BadgeFragment} from './Other/BadgeFragment'; import {UserPrefEvent} from '../Event/UserPrefEvent'; import {StreamRepo} from '../Repository/StreamRepo'; import {AppEvent} from '../Event/AppEvent'; import {StreamIPC} from '../../IPC/StreamIPC'; import {JumpNavigationFragment} from './JumpNavigation/JumpNavigationFragment'; import {IssueRepo} from '../Repository/IssueRepo'; import {GitHubV4IssueClient} from '../Library/GitHub/V4/GitHubV4IssueClient'; import {PrefScopeErrorFragment} from './Pref/PrefScopeErrorFragment'; import {PrefNetworkErrorFragment} from './Pref/PrefNetworkErrorFragment'; import {IntroFragment} from './Other/IntroFragment'; import {GitHubNotificationPolling} from '../Repository/GitHubNotificationPolling'; import {SideFragment} from './Side/SideFragment'; import {PrefUnauthorizedFragment} from './Pref/PrefUnauthorizedFragment'; import {DB} from '../Library/Infra/DB'; import {ExportDataFragment} from './Other/ExportDataFragment'; import {Loading} from '../Library/View/Loading'; import {PlatformUtil} from '../Library/Util/PlatformUtil'; type Props = { } type State = { initStatus: 'loading' | 'error' | 'complete'; prefSwitchingStatus: 'loading' | 'error' | 'complete'; prefIndex: number; githubUrl: string; isPrefNetworkError: boolean; isPrefScopeError: boolean; isPrefNotFoundError: boolean; isUnauthorized: boolean; aboutShow: boolean; layout: 'one' | 'two' | 'three'; showJumpNavigation: boolean; initialKeywordForJumpNavigation: string; } class AppFragment extends React.Component<Props, State> { state: State = { initStatus: 'loading', prefSwitchingStatus: 'complete', prefIndex: 0, githubUrl: '', isPrefNetworkError: false, isPrefScopeError: false, isUnauthorized: false, isPrefNotFoundError: false, aboutShow: false, layout: 'three', showJumpNavigation: false, initialKeywordForJumpNavigation: '', } private libraryStreamsFragmentRef: LibraryStreamsFragment; private systemStreamsFragmentRef: SystemStreamsFragment; private userStreamsFragmentRef: UserStreamsFragment; async componentDidMount() { const eachPaths = await UserPrefIPC.getEachPaths(); console.table(eachPaths); await this.init(); AppEvent.onNextLayout(this, () => this.handleNextLayout()); AppEvent.onJumpNavigation(this, () => this.handleShowJumpNavigation()); AppEvent.onChangedTheme(this, () => { this.forceUpdate(() => { this.selectFirstStream(); StreamEvent.emitReloadAllStreams(); }); }); MainWindowIPC.onToggleLayout(layout => this.handleToggleLayout(layout)); MainWindowIPC.onShowAbout(() => this.setState({aboutShow: true})); MainWindowIPC.onPowerMonitorSuspend(() => this.handleStopPolling()); MainWindowIPC.onPowerMonitorResume(() => this.handleStartPolling()); MainWindowIPC.onShowJumpNavigation(() => this.handleShowJumpNavigation()); MainWindowIPC.onShowRecentlyReads(() => this.handleShowJumpNavigation('sort:read')); StreamIPC.onSelectNextStream(() => this.handleNextPrevStream(1)); StreamIPC.onSelectPrevStream(() => this.handleNextPrevStream(-1)); window.addEventListener('online', () => navigator.onLine === true && this.handleStartPolling()); window.addEventListener('offline', () => this.handleStopPolling()); } componentWillUnmount() { AppEvent.offAll(this); } // ここを変更する場合、this.switchPref()も見直すこと // todo: switchPref()と共通化する private async init() { this.setState({initStatus: 'loading'}); const {error, githubUrl, isPrefNotFoundError, isPrefScopeError, isPrefNetworkError, isUnauthorized} = await UserPrefRepo.init(); if (error) { this.setState({initStatus: 'error', githubUrl, isPrefNetworkError, isPrefNotFoundError, isPrefScopeError, isUnauthorized}); return console.error(error); } const dbPath = await UserPrefRepo.getDBPath(); const {error: dbError} = await DBSetup.exec(dbPath); if (dbError){ console.error(dbError); alert('The database is corrupted. Delete and initialize the database.'); await DB.deleteDBFile(); this.init(); return; } await StreamSetup.exec(); VersionPolling.startChecker(); // node_idのmigrationが走ったときだけ、直近のissueをv4対応させる // node_idのmigrationが走った = v0.9.3からv1.0.0へのアップデート if (DBSetup.isMigrationNodeId()) this.updateRecentlyIssues(); this.initGA(); GARepo.eventAppStart(); StreamPolling.start(); GitHubNotificationPolling.start(); this.setState({initStatus: 'complete', prefIndex: UserPrefRepo.getIndex()}, () => this.selectFirstStream()); } private initGA() { GARepo.init({ userAgent: navigator.userAgent, width: screen.width, height: screen.height, availableWidth: screen.availWidth, availableHeight: screen.availHeight, colorDepth: screen.colorDepth, }); } private async selectFirstStream() { let streamId; while (1) { const libRes = this.libraryStreamsFragmentRef.getStreamIds(); const sysRes = this.systemStreamsFragmentRef.getStreamIds(); const userRes = this.userStreamsFragmentRef.getStreamIds(); const streamIds = [...libRes.streamIds, ...sysRes.streamIds, ...userRes.streamIds]; if (streamIds.length) { streamId = streamIds[0]; break; } await TimerUtil.sleep(100); } const {error, stream} = await StreamRepo.getStream(streamId); if (error) return console.error(error); await StreamEvent.emitSelectStream(stream); } private async updateRecentlyIssues() { const {error, issues} = await IssueRepo.getRecentlyIssues(); if (error) return console.error(error); const nodeIds = issues.map(issue => issue.node_id); const github = UserPrefRepo.getPref().github; const client = new GitHubV4IssueClient(github.accessToken, github.host, github.https, UserPrefRepo.getGHEVersion()); const {error: e1, issues: v4Issues} = await client.getIssuesByNodeIds(nodeIds); if (e1) return console.error(e1); const {error: e2} = await IssueRepo.updateWithV4(v4Issues); if (e2) return console.error(e2); } private async handleSwitchPref(prefIndex: number) { this.setState({prefSwitchingStatus: 'loading', prefIndex}); await StreamPolling.stop(); GitHubNotificationPolling.stop(); const {error, isPrefNetworkError, isPrefScopeError, isUnauthorized, githubUrl} = await UserPrefRepo.switchPref(prefIndex); if (error) { this.setState({prefSwitchingStatus: 'error', githubUrl, isPrefNetworkError, isPrefScopeError, isUnauthorized}); return console.error(error); } const dbPath = await UserPrefRepo.getDBPath(); const {error: dbError} = await DBSetup.exec(dbPath); if (dbError){ console.error(dbError); alert('The database is corrupted. Delete and initialize the database.'); await DB.deleteDBFile(); this.handleSwitchPref(prefIndex); return; } await StreamSetup.exec(); if (DBSetup.isMigrationNodeId()) this.updateRecentlyIssues(); StreamPolling.start(); GitHubNotificationPolling.start(); StreamEvent.emitReloadAllStreams(); await TimerUtil.sleep(100); this.setState({prefSwitchingStatus: 'complete'}, () => this.selectFirstStream()); UserPrefEvent.emitSwitchPref(); } private handleNextPrevStream(direction: 1 | -1) { const libRes = this.libraryStreamsFragmentRef.getStreamIds(); const sysRes = this.systemStreamsFragmentRef.getStreamIds(); const userRes = this.userStreamsFragmentRef.getStreamIds(); const streamIds = [...libRes.streamIds, ...sysRes.streamIds, ...userRes.streamIds]; const selectedStreamId = libRes.selectedStreamId ?? sysRes.selectedStreamId ?? userRes.selectedStreamId; const currentIndex = streamIds.findIndex(streamId => streamId === selectedStreamId); const index = currentIndex + direction; const streamId = streamIds[index]; this.libraryStreamsFragmentRef.selectStream(streamId); this.systemStreamsFragmentRef.selectStream(streamId); this.userStreamsFragmentRef.selectStream(streamId); } private handleShowJumpNavigation(initialKeyword: string = '') { this.setState({showJumpNavigation: true, initialKeywordForJumpNavigation: initialKeyword}); } private handleNextLayout() { switch (this.state.layout) { case 'one': this.setState({layout: 'three'}); break; case 'two': this.setState({layout: 'one'}); break; case 'three': this.setState({layout: 'two'}); break; } AppEvent.emitChangedLayout(); } private handleToggleLayout(layout: State['layout']) { if (this.state.layout === layout) { this.setState({layout: 'three'}); } else { this.setState({layout}); } AppEvent.emitChangedLayout(); } private handleStopPolling() { StreamPolling.stop(); VersionPolling.stopChecker(); } private handleStartPolling() { StreamPolling.start(); VersionPolling.startChecker(); } private async handleClosePrefSetup(github: UserPrefEntity['github'], browser: UserPrefEntity['general']['browser']) { if (github) { const res = await UserPrefRepo.addPrefGitHub(github, browser); if (!res) return; await this.init(); } } render() { switch (this.state.initStatus) { case 'loading': return this.renderLoading(); case 'error': return this.renderError(); case 'complete': return this.renderComplete(); } } renderLoading() { return ( <Root style={{justifyContent: 'center'}}> <Loading show={true}/> <GlobalStyle/> </Root> ); } renderError() { if (this.state.initStatus !== 'error') return null; if (this.state.isPrefNotFoundError) { return ( <React.Fragment> <PrefSetupFragment show={true} showImportData={true} onClose={(github, browser) => this.handleClosePrefSetup(github, browser)}/> <KeyboardShortcutFragment/> <GlobalStyle/> </React.Fragment> ); } if (this.state.isPrefNetworkError) { return ( <React.Fragment> <PrefNetworkErrorFragment githubUrl={this.state.githubUrl} onRetry={() => this.init()}/> <KeyboardShortcutFragment/> <GlobalStyle/> </React.Fragment> ); } if (this.state.isPrefScopeError) { return ( <React.Fragment> <PrefScopeErrorFragment githubUrl={this.state.githubUrl} onRetry={() => this.init()}/> <GlobalStyle/> </React.Fragment> ); } if (this.state.isUnauthorized) { return ( <React.Fragment> <PrefUnauthorizedFragment githubUrl={this.state.githubUrl} onRetry={() => this.init()}/> <GlobalStyle/> </React.Fragment> ); } } renderComplete() { const layoutClassName = `app-layout-${this.state.layout}`; const prefSwitchingClassName = this.state.prefSwitchingStatus === 'loading' ? 'app-pref-switching-loading' : ''; return ( <Root className={`${layoutClassName} ${prefSwitchingClassName}`}> <Main> <SideFragment className='app-streams-column'> <PrefCoverFragment onSwitchPref={this.handleSwitchPref.bind(this)}/> <LibraryStreamsFragment ref={ref => this.libraryStreamsFragmentRef = ref}/> <SystemStreamsFragment ref={ref => this.systemStreamsFragmentRef = ref}/> <UserStreamsFragment ref={ref => this.userStreamsFragmentRef = ref}/> </SideFragment> <IssuesFragment className='app-issues-column'/> <BrowserFragment className='app-browser-column'/> </Main> <IntroFragment/> <AboutFragment show={this.state.aboutShow} onClose={() => this.setState({aboutShow: false})}/> <NotificationFragment/> <KeyboardShortcutFragment/> <BadgeFragment/> <JumpNavigationFragment show={this.state.showJumpNavigation} onClose={() => this.setState({showJumpNavigation: false})} initialKeyword={this.state.initialKeywordForJumpNavigation} /> {this.renderPrefSwitchingError()} <ExportDataFragment/> <GlobalStyle/> </Root> ); } private renderPrefSwitchingError() { if (this.state.prefSwitchingStatus !== 'error') return; if (this.state.isPrefNetworkError) { return ( <PrefNetworkErrorFragment githubUrl={this.state.githubUrl} onRetry={() => this.handleSwitchPref(this.state.prefIndex)}/> ); } if (this.state.isPrefScopeError) { return ( <PrefScopeErrorFragment githubUrl={this.state.githubUrl} onRetry={() => this.handleSwitchPref(this.state.prefIndex)}/> ); } if (this.state.isUnauthorized) { return ( <PrefUnauthorizedFragment githubUrl={this.state.githubUrl} onRetry={() => this.handleSwitchPref(this.state.prefIndex)}/> ); } } } const Root = styled(View)` width: 100vw; height: 100vh; border-top: solid ${PlatformUtil.isMac() ? 0 : border.medium}px ${() => appTheme().border.normal}; &.app-layout-one .app-streams-column, &.app-layout-one .app-issues-column { display: none; } &.app-layout-two .app-streams-column { display: none; } &.app-pref-switching-loading { opacity: 0.3; } `; const Main = styled(View)` flex-direction: row; flex: 1; `; const GlobalStyle = createGlobalStyle` * { outline: none; user-select: none; } body { margin: 0; font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji; font-size: ${font.medium}px; color: ${() => appTheme().text.normal}; line-height: 1.6; } `; export function mountAppFragment() { ReactDOM.render( <AppFragment/>, document.querySelector('#app') ); }
the_stack
const BG_VERSION = 17 const NEED_DROPPER_VERSION = 12 const DEFAULT_COLOR = '#b48484' interface BgSettings { autoClipboard: boolean autoClipboardNoGrid: boolean enableColorToolbox: boolean enableColorTooltip: boolean enableRightClickDeactivate: boolean dropperCursor: string plus: boolean plus_type: string } interface HistoryColorItem { h: string n: string s: number t: number f: number } interface Palette { name: string created: number colors: Array<string> } // base bg object var bg = { tab: null as chrome.tabs.Tab, tabs: [] as Array<chrome.tabs.Tab>, version: BG_VERSION, screenshotData: '', screenshotFormat: 'png', canvas: document.createElement('canvas'), canvasContext: null, debugImage: null, debugTab: 0, history: { version: BG_VERSION, last_color: DEFAULT_COLOR, current_palette: 'default', palettes: [] as Array<Palette>, }, defaultSettings: { autoClipboard: false, autoClipboardNoGrid: false, enableColorToolbox: true, enableColorTooltip: true, enableRightClickDeactivate: true, dropperCursor: 'default', plus: false, plus_type: null, }, defaultPalette: 'default', settings: {} as BgSettings, edCb: null, color_sources: { 1: 'Web Page', 2: 'Color Picker', 3: 'Old History', }, // use selected tab // need to null all tab-specific variables useTab: function (tab: chrome.tabs.Tab) { bg.tab = tab bg.screenshotData = '' bg.canvas = document.createElement('canvas') bg.canvasContext = null }, checkDropperScripts: function () { console.log('bg: checking dropper version') bg.sendMessage( { type: 'edropper-version', }, function (res: { version: number; tabid: number }) { console.log('bg: checking dropper version 2') if (chrome.runtime.lastError || !res) { bg.injectDropper() } else { if (res.version < NEED_DROPPER_VERSION) { bg.refreshDropper() } else { bg.pickupActivate() } } }, ) }, injectDropper: function () { console.log('bg: injecting dropper scripts') chrome.tabs.executeScript( bg.tab.id, { file: '/js/edropper2.js', }, function (_results: Array<any>) { console.log('bg: edropper2 injected') bg.pickupActivate() }, ) }, refreshDropper: function () { console.log('bg: refreshing dropper scripts') chrome.tabs.executeScript( bg.tab.id, { allFrames: true, file: '/js/edropper2.js', }, function (_results: Array<any>) { console.log('bg: edropper2 updated') bg.pickupActivate() }, ) }, sendMessage: function (message: any, callback?: (response: any) => void) { chrome.tabs.sendMessage(bg.tab.id, message, callback) }, shortcutListener: function () { chrome.commands.onCommand.addListener((command) => { console.log('bg: command: ', command) switch (command) { case 'activate': bg.activate2() break } }) }, messageListener: function () { // simple messages chrome.runtime.onMessage.addListener((req, _sender, sendResponse) => { switch (req.type) { case 'activate-from-hotkey': bg.activate2() sendResponse({}) break // Reload background script case 'reload-background': window.location.reload() break // Clear colors history case 'clear-history': bg.clearHistory(sendResponse) break } }) // longer connections chrome.runtime.onConnect.addListener((port) => { port.onMessage.addListener((req, sender) => { switch (req.type) { // Taking screenshot for content script case 'screenshot': ////console.log('received screenshot request') bg.capture() break // Creating debug tab case 'debug-tab': console.info('Received debug tab request') bg.debugImage = req.image bg.createDebugTab() break // Set color given in req // FIXME: asi lepší z inject scriptu posílat jen rgbhex, už to tak máme stejně skoro všude case 'set-color': console.log(sender.sender) console.log(req.color) bg.setColor('#' + req.color.rgbhex, true, 1, sender.sender.url) break } }) }) /** * When Eye Dropper is just installed, we want to display nice * page to user with some instructions */ chrome.runtime.onInstalled.addListener((object: chrome.runtime.InstalledDetails) => { if (object.reason === 'install') { chrome.tabs.create({ url: 'https://eyedropper.org/installed', selected: true, }) } }) }, setBadgeColor: function (color: string) { console.info('Setting badge color to ' + color) chrome.browserAction.setBadgeBackgroundColor({ color: [ parseInt(color.substr(1, 2), 16), parseInt(color.substr(3, 2), 16), parseInt(color.substr(5, 2), 16), 255, ], }) }, // method for setting color. It set bg color, update badge and save to history if possible // source - see historyColorItem for description setColor: function (color: string, history = true, source = 1, url?: string) { console.group('setColor') console.info('Received color ' + color + ', history: ' + history) if (!color || !color.match(/^#[0-9a-f]{6}$/)) { console.error('error receiving collor from dropper') console.groupEnd() return } // we are storing color with first # character bg.setBadgeColor(color) bg.history.last_color = color if (bg.settings.autoClipboard) { console.info('Copying color to clipboard') bg.copyToClipboard(color) } if (history) { console.info('Saving color to history') bg.saveToHistory(color, source, url) } console.groupEnd() }, saveToHistory: function (color: string, source = 1, url?: string) { var palette = bg.getPalette() if ( !palette.colors.find((x: HistoryColorItem) => { return x.h == color }) ) { palette.colors.push(bg.historyColorItem(color, Date.now(), source, false, url)) console.info('Color ' + color + ' saved to palette ' + bg.getPaletteName()) bg.saveHistory() } else { console.info('Color ' + color + ' already in palette ' + bg.getPaletteName()) } }, copyToClipboard: function (color: string) { bg.edCb.value = bg.settings.autoClipboardNoGrid ? color.substring(1) : color bg.edCb.select() document.execCommand('copy', false, null) }, // activate from content script activate2: function () { chrome.tabs.query({ active: true }, (tabs: Array<chrome.tabs.Tab>) => { bg.useTab(tabs[0]) bg.activate() }) }, // activate Pick activate: function () { console.log('bg: received pickup activate') // check scripts and activate pickup bg.checkDropperScripts() }, pickupActivate: function () { // activate picker bg.sendMessage({ type: 'pickup-activate', options: { cursor: bg.settings.dropperCursor, enableColorToolbox: bg.settings.enableColorToolbox, enableColorTooltip: bg.settings.enableColorTooltip, enableRightClickDeactivate: bg.settings.enableRightClickDeactivate, }, }) console.log('bg: activating pickup') }, // capture actual Screenshot capture: function () { ////console.log('capturing') try { chrome.tabs.captureVisibleTab( null, { format: 'png', }, bg.doCapture, ) // fallback for chrome before 5.0.372.0 } catch (e) { chrome.tabs.captureVisibleTab(null, bg.doCapture) } }, getColor: function () { return bg.history.last_color }, doCapture: function (data: string) { if (data) { console.log('bg: sending updated image') bg.sendMessage({ type: 'update-image', data: data, }) } else { console.error('bg: did not receive data from captureVisibleTab') } }, createDebugTab: function () { // DEBUG if (bg.debugTab != 0) { chrome.tabs.sendMessage(bg.debugTab, { type: 'update', }) } else chrome.tabs.create( { url: '/debug-tab.html', selected: false, }, function (tab) { bg.debugTab = tab.id }, ) }, tabOnChangeListener: function () { // deactivate dropper if tab changed chrome.tabs.onSelectionChanged.addListener((tabId, _selectInfo) => { if (bg.tab && bg.tab.id == tabId) bg.sendMessage({ type: 'pickup-deactivate', }) }) }, getPaletteName: function () { return bg.getPalette().name }, isPalette: function (name: string) { return bg.history.palettes.find((x: Palette) => { return x.name == name }) ? true : false }, getPalette: function (name?: string) { if (name === undefined) { name = bg.history.current_palette === undefined || !bg.isPalette(bg.history.current_palette) ? 'default' : bg.history.current_palette } return bg.history.palettes.find((x: Palette) => { return x.name == name }) }, changePalette: function (palette_name: string) { if (bg.history.current_palette === palette_name) { console.info('Not switching, already on palette ' + palette_name) } else if (bg.isPalette(palette_name)) { bg.history.current_palette = palette_name console.info('Switched current palette to ' + palette_name) bg.saveHistory() } else { console.error('Cannot switch to palette ' + palette_name + '. Palette not found.') } }, getPaletteNames: function () { return bg.history.palettes.map((x: Palette) => { return x.name }) }, uniquePaletteName: function (name: string) { // default name is palette if we receive empty or undefined name if (name === undefined || !name || name.length < 1) { console.info('uniquePaletteName: ' + name + " empty, trying 'palette'") return bg.uniquePaletteName('palette') // if there is already palette with same name } else if ( bg.getPaletteNames().find((x: string) => { return x == name }) ) { var matches = name.match(/^(.*[^\d]+)(\d+)?$/) // doesn't end with number, we will add 1 if (matches[2] === undefined) { console.info('uniquePaletteName: ' + name + " occupied, trying '" + name + "1'") return bg.uniquePaletteName(name + '1') // ends with number } else { var new_name = '' + matches[1] + (parseInt(matches[2]) + 1) console.info('uniquePaletteName: ' + name + " occupied, trying '" + new_name + "'") return bg.uniquePaletteName(new_name) } } else { console.info('uniquePaletteName: ' + name + " is free'") return name } }, createPalette: function (name: string) { var palette_name = bg.uniquePaletteName(name) console.info('Creating new palette ' + name + '. Unique name: ' + palette_name) bg.history.palettes.push({ name: palette_name, created: Date.now(), colors: [], }) bg.saveHistory() return bg.getPalette(palette_name) }, destroyPalette: function (name: string) { if (!bg.isPalette(name)) { return } if (name === 'default') { console.info("Can't destroy default palette. Clearing only.") bg.getPalette(name).colors = [] } else { console.info('Destroying palette ' + name) var destroying_current = name === bg.getPalette().name bg.history.palettes = bg.history.palettes.filter((obj: Palette) => { return obj.name !== name }) // if we are destroying current palette, switch to default one if (destroying_current) { bg.changePalette('default') } } bg.saveHistory(false) chrome.storage.sync.remove('palette.' + name) }, clearHistory: function (sendResponse: ({ state: string }) => void) { var palette = bg.getPalette() console.info('Clearing history for palette ' + palette.name) palette.colors = [] bg.saveHistory() if (sendResponse != undefined) { sendResponse({ state: 'OK', }) } }, /** * Load history from storage on extension start */ loadHistory: function () { console.info('Loading history from storage') chrome.storage.sync.get((items) => { if (items.history) { bg.history.current_palette = items.history.cp bg.history.last_color = items.history.lc console.info('History info loaded. Loading palettes.') console.info('Default palette before loading: ' + bg.defaultPalette) var count_default_1 = 0 var count_converted_1 = 0 Object.keys(items).forEach((key, _index) => { var matches = key.match(/^palette\.(.*)$/) if (matches) { var palette = items[key] bg.history.palettes.push({ name: matches[1], colors: palette.c, created: palette.t, }) if (matches[1] === 'default') { count_default_1 = palette.c.length } if (matches[1] === 'converted') { count_converted_1 = palette.c.length } } }) if (count_default_1 === 0 && count_converted_1 > 0) { bg.defaultPalette = 'converted' console.info('Default palette after loading: ' + bg.defaultPalette) } if (items.history.v < bg.history.version) { bg.checkHistoryUpgrades(items.history.v) } } else { console.log('No history in storage') bg.createPalette('default') } // in any case we will try to convert local history bg.tryConvertOldHistory() }) }, /** * Check if there are needed upgrades to history and exec if needed **/ checkHistoryUpgrades: function (version: number) { // Wrong timestamp saved before version 14 // // There was error in bg versions before 14 that caused saving // history color timestamp as link tu datenow function instead of // current date in some cases. // // We will check for such times and set them to start of epoch if (version < 14) { console.log('History version is pre 14: Fixing color times') for (var _i = 0, _a = bg.history.palettes; _i < _a.length; _i++) { var palette = _a[_i] for (var _b = 0, _c = palette.colors; _b < _c.length; _b++) { var color = _c[_b] if (typeof color.t !== 'number') { color.t = 0 } } } bg.saveHistory() } }, /** * Load settings from storage on extension start */ loadSettings: function () { console.info('Loading settings from storage') chrome.storage.sync.get('settings', function (items) { if (items.settings) { console.info('Settings loaded') bg.settings = items.settings } else { console.log('No settings in storage') bg.tryConvertOldSettings() } }) }, /** * sources: * 1: eye dropper * 2: color picker * 3: converted from old history * * FIXME: * url is not saved now because of quotas * favorite not implemented yet * * h = hex * n = name * s = source * t = timestamp when taken * f = favorite */ historyColorItem: function ( color: string, timestamp = Date.now(), source = 1, favorite = false, _url?: string, ) { return { h: color, n: '', s: source, t: timestamp, f: favorite ? 1 : 0, } }, /** * Convert pre 0.4 Eye Dropper local history to synced storage * * Backup of old history is stored in local storage in _history_backup * in case something goes south. */ tryConvertOldHistory: function () { if (window.localStorage.history) { var oldHistory = JSON.parse(window.localStorage.history) var converted_palette = bg.createPalette('converted') console.warn(converted_palette) // add every color from old history to new schema with current timestamp var timestamp = Date.now() for (var key in oldHistory) { var color = oldHistory[key] // in versions before 0.3.0 colors were stored without # in front if (color[0] != '#') { color = '#' + color } // push color to our converted palette converted_palette.colors.push(bg.historyColorItem(color, timestamp, 3)) // set this color as last bg.history.last_color = color } // make backup of old history window.localStorage._history_backup = window.localStorage.history // remove old history from local storage window.localStorage.removeItem('history') // sync history bg.saveHistory() // change to converted history if current palette is empty if (bg.getPalette().colors.length < 1) { bg.changePalette(converted_palette.name) } } }, /** * Convert pre 0.4 Eye Dropper local settings to synced storage * * Synced storage is much better because it finally allows as to store objects and not * strings only. * */ tryConvertOldSettings: function () { // load default settings first bg.settings = bg.defaultSettings // convert old settings bg.settings.autoClipboard = window.localStorage.autoClipboard === 'true' ? true : false bg.settings.autoClipboardNoGrid = window.localStorage.autoClipboardNoGrid === 'true' ? true : false bg.settings.enableColorToolbox = window.localStorage.enableColorToolbox === 'false' ? false : true bg.settings.enableColorTooltip = window.localStorage.enableColorTooltip === 'false' ? false : true bg.settings.enableRightClickDeactivate = window.localStorage.enableRightClickDeactivate === 'false' ? false : true bg.settings.dropperCursor = window.localStorage.dropperCursor === 'crosshair' ? 'crosshair' : 'default' // sync settings bg.saveSettings() // remove old settings from local storage var setting_keys = [ 'autoClipboard', 'autoClipboardNoGrid', 'enableColorTooltip', 'enableColorToolbox', 'enableRightClickDeactivate', 'dropperCursor', ] for (var _i = 0, setting_keys_1 = setting_keys; _i < setting_keys_1.length; _i++) { var setting_name = setting_keys_1[_i] localStorage.removeItem(setting_name) } console.info('Removed old settings from locale storage.') }, saveHistory: function (all_palettes = true) { var saved_object = { history: { v: bg.history.version, cp: bg.history.current_palette, lc: bg.history.last_color, }, } if (all_palettes) { for (var _i = 0, _a = bg.history.palettes; _i < _a.length; _i++) { const palette = _a[_i] saved_object['palette.' + palette.name] = { c: palette.colors, t: palette.created, } } } chrome.storage.sync.set(saved_object, function () { console.info('History synced to storage') }) }, saveSettings: function () { chrome.storage.sync.set( { settings: bg.settings, }, function () { console.info('Settings synced to storage') }, ) }, unlockPlus: function (type: string) { bg.settings.plus = true bg.settings.plus_type = type bg.saveSettings() }, lockPlus: function () { bg.settings.plus = false bg.settings.plus_type = null bg.saveSettings() }, plus: function () { return bg.settings.plus ? bg.settings.plus_type : false }, plusColor: function (color = bg.settings.plus_type) { switch (color) { case 'free': return 'gray' case 'alpha': return 'silver' default: return color } }, init: function () { console.group('init') bg.edCb = document.getElementById('edClipboard') bg.loadSettings() bg.loadHistory() // set default badge text to empty string // we are comunicating with users only through badge background color chrome.browserAction.setBadgeText({ text: ' ', }) // we have to listen for messages bg.messageListener() // act when tab is changed // TODO: call only when needed? this is now used also if picker isn't active bg.tabOnChangeListener() // listen for shortcut commands bg.shortcutListener() console.groupEnd() }, } document.addEventListener('DOMContentLoaded', function () { bg.init() }) ;(<any>window).bg = bg
the_stack
import { allDocsAtom, deletedDocsAtom, docAtom, pathExpanderAtom, } from "@/atoms/firestore"; import { actionDeleteCollection, actionDeleteDoc, actionNewDocument, } from "@/atoms/firestore.action"; import { navigatorPathAtom } from "@/atoms/navigator"; import { actionExportCollectionCSV, actionExportCollectionJSON, actionExportDocCSV, actionExportDocJSON, actionGoTo, actionPathExpand, } from "@/atoms/navigator.action"; import { actionToggleImportModal } from "@/atoms/ui.action"; import { useContextMenu } from "@/hooks/contextMenu"; import { ClientDocumentSnapshot } from "@/types/ClientDocumentSnapshot"; import { beautifyId, getParentPath, getProjectId, getRecursivePath, isCollection, prettifyPath, } from "@/utils/common"; import { COLLECTION_PREFIX } from "@/utils/contant"; import { Input } from "@zendeskgarden/react-forms"; import classNames from "classnames"; import { uniq, uniqueId } from "lodash"; import * as immutable from "object-path-immutable"; import Tree from "rc-tree"; import { DataNode, EventDataNode } from "rc-tree/lib/interface"; import React, { useCallback, useEffect, useMemo, useRef, useState, } from "react"; import { useDebounce } from "react-use"; import AutoSizer from "react-virtualized-auto-sizer"; import { useRecoilState, useRecoilValue } from "recoil"; import "./index.css"; interface IFSDataNode extends DataNode { isCollection: boolean; key: string; path: string; name: string; } const NodeComponent = ({ path, name, isCollection }: IFSDataNode) => { const doc = useRecoilValue(docAtom(path)); return ( <span className={classNames("text-gray-800", { ["text-green-600"]: doc?.isNew, ["text-blue-600"]: doc?.isChanged(), ["font-mono text-xs"]: !isCollection, })} > {isCollection ? name : beautifyId(name)} </span> ); }; const constructData = (paths: string[], additionNode: IFSDataNode | null) => { const newObject = immutable.wrap({}); paths.forEach((path) => { newObject.merge(path.replace("/", "").replaceAll("/", "."), {}); }); return buildTree(newObject.value(), [], "", true, additionNode); }; function buildTree( mapObj: Record<string, any>, result: IFSDataNode[], parent = "", isCollection = true, additionNode: IFSDataNode | null ): IFSDataNode[] { result = Object.keys(mapObj) .sort((a, b) => a.localeCompare(b)) .map((key) => ({ key: [parent, key].join("/"), path: [parent, key].join("/"), name: key, title: (props) => <NodeComponent {...props} />, children: [], isCollection: isCollection, className: "hover:bg-gray-200 cursor-pointer", props: { onClick: (e) => { if (e.target?.getAttribute("role") !== "expander") { // Ignore if user click on the expander icon actionGoTo([parent, key].join("/")); } }, "cm-template": isCollection ? "treeCollectionContext" : "treeDocContext", "cm-payload-path": [parent, key].join("/"), "cm-id": "tree", }, icon: ({ expanded }: { expanded: boolean }) => { return ( <div className="w-4"> {isCollection ? ( <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="currentColor" > <path fillRule="evenodd" clipRule="evenodd" d="M5 2.5l.5-.5h2l.5.5v11l-.5.5h-2l-.5-.5v-11zM6 3v10h1V3H6zm3.171.345l.299-.641 1.88-.684.64.299 3.762 10.336-.299.641-1.879.684-.64-.299L9.17 3.345zm1.11.128l3.42 9.396.94-.341-3.42-9.397-.94.342zM1 2.5l.5-.5h2l.5.5v11l-.5.5h-2l-.5-.5v-11zM2 3v10h1V3H2z" /> </svg> ) : ( <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="currentColor" > <path fillRule="evenodd" clipRule="evenodd" d="M13.71 4.29l-3-3L10 1H4L3 2v12l1 1h9l1-1V5l-.29-.71zM13 14H4V2h5v4h4v8zm-3-9V2l3 3h-3z" /> </svg> )} </div> ); }, switcherIcon({ expanded, isLeaf, }: { expanded: boolean; isLeaf: boolean; }) { if (!isCollection) { return null; } if (expanded) { return ( <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="w-3 pt-0.5" role="expander" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /> </svg> ); } return ( <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="w-3 pt-0.5" role="expander" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" /> </svg> ); }, })); let passAdditionNode = true; if (additionNode) { const additionNodeParentPath = getParentPath(additionNode.key); const simplifiedParentPath = additionNodeParentPath === "/" ? "" : additionNodeParentPath; if (simplifiedParentPath === parent) { passAdditionNode = false; result.push(additionNode); } } Object.keys(mapObj).forEach((key) => { const parent = result.find((node: IFSDataNode) => node.name === key); if (parent) { parent.children = buildTree( mapObj[key], [], parent.key, !isCollection, passAdditionNode ? additionNode : null ).sort((a, b) => a.name.localeCompare(b.name)); } }); return result; } interface INewCollectionInputProps { path: string; onChange: (path: string | null) => void; } const NewCollectionInput = ({ path, onChange }: INewCollectionInputProps) => { // TODO: Validate the path user has input https://firebase.google.com/docs/firestore/quotas?authuser=0 const inputRef = useRef<HTMLInputElement>(null); const handleCreateCollection = () => { if (!inputRef?.current?.value) { onChange(null); return; } const newPath = prettifyPath( `${path === "/" ? "" : path}/${inputRef?.current?.value}` ); actionNewDocument(newPath); onChange(newPath); }; const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === "Escape") { onChange(null); } if (e.key === "Enter") { handleCreateCollection(); } }; useEffect(() => { inputRef.current?.focus(); }, []); const handleFocus: React.FocusEventHandler = (e) => { e.stopPropagation(); }; return ( <input onKeyDown={onKeyDown} onBlur={() => handleCreateCollection()} ref={inputRef} tabIndex={2} onFocus={handleFocus} className="w-auto p-0.5 min-h border border-gray-300 h-6 focus:border-blue-400 text-sm outline-none" /> ); }; const addNewCollectionNode = ( path: string, key: string, cb: (path: string | null) => void ): IFSDataNode => { return { key: [path, key].join("/"), title: () => <NewCollectionInput path={path} onChange={cb} />, path: [path, key].join("/"), name: key, children: [], isLeaf: true, isCollection: true, selectable: false, icon: () => { return ( <div className="w-4"> <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="currentColor" > <path fillRule="evenodd" clipRule="evenodd" d="M5 2.5l.5-.5h2l.5.5v11l-.5.5h-2l-.5-.5v-11zM6 3v10h1V3H6zm3.171.345l.299-.641 1.88-.684.64.299 3.762 10.336-.299.641-1.879.684-.64-.299L9.17 3.345zm1.11.128l3.42 9.396.94-.341-3.42-9.397-.94.342zM1 2.5l.5-.5h2l.5.5v11l-.5.5h-2l-.5-.5v-11zM2 3v10h1V3H2z" /> </svg> </div> ); }, switcherIcon: () => null, }; }; interface ITreeViewProps { allDocs: ClientDocumentSnapshot[]; deletedDocs: ClientDocumentSnapshot[]; pathAvailable: string[]; } function TreeView({ allDocs, deletedDocs, pathAvailable }: ITreeViewProps) { const [path, setPath] = useRecoilState(navigatorPathAtom); // const allDocs = useRecoilValue(allDocsAtom); // const pathAvailable = useRecoilValue(pathExpanderAtom); const [searchInput, setSearchInput] = useState(""); const treeWrapperRef = useRef<HTMLDivElement>(null); const [addingNewCollection, setAddNewCollection] = useState<{ path: string; key: string; } | null>(null); const [expandedKeys, setExpanded] = useState<string[]>([]); const handleSelectTree = useCallback((keys: React.ReactText[]) => { if (keys.length > 0) { setPath(keys[0] as string); } }, []); const handleExpandData = useCallback(async (node: EventDataNode) => { actionPathExpand(node.key.toString()); }, []); const handleOnAddCollection = useCallback( (path: string | null): void => { setAddNewCollection(null); }, [setAddNewCollection] ); const allPaths = useMemo(() => { let paths = [ ...pathAvailable, ...allDocs.map((doc) => doc.ref.path), ].filter((item) => !deletedDocs.find((doc) => doc.ref.path === item)); if (searchInput) { paths = paths.filter((path) => path.toLowerCase().includes(searchInput.toLowerCase()) ); } return paths; }, [pathAvailable, allDocs, deletedDocs, searchInput]); const treeData = useMemo(() => { const currentTree = constructData( allPaths, addingNewCollection ? addNewCollectionNode( addingNewCollection.path, addingNewCollection.key, handleOnAddCollection ) : null ); return currentTree; }, [allPaths, addingNewCollection]); const handleOnFocus = () => { treeWrapperRef?.current?.querySelector("input")?.focus(); }; const handleAddCollection = (path = "") => { setAddNewCollection({ path, key: uniqueId(COLLECTION_PREFIX), }); }; useContextMenu( "EXPORT_CSV", ({ path }: { path: string }) => { if (isCollection(path)) { actionExportCollectionCSV(path); } else { actionExportDocCSV(path); } }, "tree" ); useContextMenu( "EXPORT_JSON", ({ path }: { path: string }) => { if (isCollection(path)) { actionExportCollectionJSON(path); } else { actionExportDocJSON(path); } }, "tree" ); useContextMenu( "NEW_DOC", ({ path }: { path: string }) => { actionNewDocument(path); }, "tree" ); useContextMenu( "NEW_COLLECTION", ({ path }: { path: string }) => { setExpanded((keys) => uniq([...keys, path])); handleAddCollection(path); }, "tree" ); useContextMenu( "IMPORT", ({ path }: { path: string }) => { actionToggleImportModal(path, true); }, "tree" ); useContextMenu( "DELETE", ({ path }: { path: string }) => { if (isCollection(path)) { actionDeleteCollection(path); } else { actionDeleteDoc(path); } }, "tree" ); const handleOnExpand = ( expandedKeys: any[], { expanded = true, node }: { expanded: boolean; node: DataNode } ) => { if (!expanded) { setExpanded((keys) => keys.filter((key) => !key.startsWith(node.key.toString())) ); return; } setExpanded(expandedKeys as string[]); }; useEffect(() => { setExpanded((keys) => uniq([...keys, ...getRecursivePath(path)])); }, [path]); const expandedKeysWithFilter = useMemo(() => { if (searchInput.length >= 3) { return uniq( allPaths.reduce( (prev, path) => { return [...prev, ...getRecursivePath(path)]; }, [...expandedKeys] ) ); } return expandedKeys; }, [expandedKeys, searchInput]); return ( <div className="flex flex-col h-full"> <Input placeholder="Search for item..." isCompact value={searchInput} onChange={(e) => setSearchInput(e.target.value)} /> <div className="flex flex-col h-full mt-2" tabIndex={1} ref={treeWrapperRef} onFocus={handleOnFocus} > <div className="flex h-8 flex-row items-center justify-between pl-1.5 bg-gray-200 border-b-2 border-gray-400"> <span>{getProjectId()}</span> <button className="h-full px-1.5 hover:bg-gray-400" role="button" onClick={() => handleAddCollection("")} > <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="currentColor" > <path fillRule="evenodd" clipRule="evenodd" d="M14.5 2H7.71l-.85-.85L6.51 1h-5l-.5.5v11l.5.5H7v-1H1.99V6h4.49l.35-.15.86-.86H14v1.5l-.001.51h1.011V2.5L14.5 2zm-.51 2h-6.5l-.35.15-.86.86H2v-3h4.29l.85.85.36.15H14l-.01.99zM13 16h-1v-3H9v-1h3V9h1v3h3v1h-3v3z" /> </svg> </button> </div> <div className="w-full h-full"> <AutoSizer disableWidth> {({ height }) => ( <Tree // showLine treeData={treeData as any} onSelect={handleSelectTree} loadData={handleExpandData} height={height} itemHeight={30} virtual focusable className="h-full" defaultExpandedKeys={[path]} selectedKeys={[path]} expandedKeys={expandedKeysWithFilter} onExpand={handleOnExpand} /> )} </AutoSizer> </div> </div> </div> ); } const TreeViewDebouncer = () => { const allDocs = useRecoilValue(allDocsAtom); const deletedDocs = useRecoilValue(deletedDocsAtom); const pathAvailable = useRecoilValue(pathExpanderAtom); const [debouncedDocs, setDebouncedDocs] = useState<ClientDocumentSnapshot[]>( allDocs ); const [debouncedDeletedDocs, setDebouncedDeletedDocs] = useState< ClientDocumentSnapshot[] >(deletedDocs); const [debouncedPathAvailable, setDebouncedPathAvailable] = useState< string[] >(pathAvailable); useDebounce( () => { setDebouncedDocs(allDocs); setDebouncedDeletedDocs(deletedDocs); setDebouncedPathAvailable(pathAvailable); }, 250, [allDocs, deletedDocs, pathAvailable] ); return ( <TreeView allDocs={debouncedDocs} deletedDocs={debouncedDeletedDocs} pathAvailable={debouncedPathAvailable} /> ); }; export default TreeViewDebouncer;
the_stack
import axios from 'axios'; import nock from 'nock'; import { act, renderHook } from '@testing-library/react-hooks'; import { mockAccounts, mockSettings } from '../__mocks__/mock-state'; import { useNotifications } from './useNotifications'; import { AuthState } from '../types'; describe('hooks/useNotifications.ts', () => { beforeEach(() => { axios.defaults.adapter = require('axios/lib/adapters/http'); }); describe('fetchNotifications', () => { describe('github.com & enterprise', () => { it('should fetch notifications with success - github.com & enterprise', async () => { const notifications = [ { id: 1, title: 'This is a notification.' }, { id: 2, title: 'This is another one.' }, ]; nock('https://api.github.com') .get('/notifications?participating=false') .reply(200, notifications); nock('https://github.gitify.io/api/v3') .get('/notifications?participating=false') .reply(200, notifications); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.fetchNotifications(mockAccounts, mockSettings); }); expect(result.current.isFetching).toBe(true); await waitForNextUpdate(); expect(result.current.isFetching).toBe(false); expect(result.current.notifications[0].hostname).toBe( 'github.gitify.io' ); expect(result.current.notifications[1].hostname).toBe('github.com'); }); it('should fetch notifications with failure - github.com & enterprise', async () => { const message = 'Oops! Something went wrong.'; nock('https://api.github.com/') .get('/notifications?participating=false') .reply(400, { message }); nock('https://github.gitify.io/api/v3/') .get('/notifications?participating=false') .reply(400, { message }); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.fetchNotifications(mockAccounts, mockSettings); }); expect(result.current.isFetching).toBe(true); await waitForNextUpdate(); expect(result.current.isFetching).toBe(false); expect(result.current.requestFailed).toBe(true); }); }); describe('enterprise', () => { it('should fetch notifications with success - enterprise only', async () => { const accounts: AuthState = { ...mockAccounts, token: null, }; const notifications = [ { id: 1, title: 'This is a notification.' }, { id: 2, title: 'This is another one.' }, ]; nock('https://github.gitify.io/api/v3/') .get('/notifications?participating=false') .reply(200, notifications); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.fetchNotifications(accounts, mockSettings); }); await waitForNextUpdate(); expect(result.current.notifications[0].hostname).toBe( 'github.gitify.io' ); expect(result.current.notifications[0].notifications.length).toBe(2); }); it('should fetch notifications with failure - enterprise only', async () => { const accounts: AuthState = { ...mockAccounts, token: null, }; nock('https://github.gitify.io/api/v3/') .get('/notifications?participating=false') .reply(400, { message: 'Oops! Something went wrong.' }); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.fetchNotifications(accounts, mockSettings); }); await waitForNextUpdate(); expect(result.current.requestFailed).toBe(true); }); }); describe('github.com', () => { it('should fetch notifications with success - github.com only', async () => { const accounts: AuthState = { ...mockAccounts, enterpriseAccounts: [], }; const notifications = [ { id: 1, title: 'This is a notification.' }, { id: 2, title: 'This is another one.' }, ]; nock('https://api.github.com') .get('/notifications?participating=false') .reply(200, notifications); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.fetchNotifications(accounts, mockSettings); }); await waitForNextUpdate(); expect(result.current.notifications[0].hostname).toBe('github.com'); expect(result.current.notifications[0].notifications.length).toBe(2); }); it('should fetch notifications with failure - github.com only', async () => { const accounts: AuthState = { ...mockAccounts, enterpriseAccounts: [], }; nock('https://api.github.com/') .get('/notifications?participating=false') .reply(400, { message: 'Oops! Something went wrong.' }); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.fetchNotifications(accounts, mockSettings); }); await waitForNextUpdate(); expect(result.current.requestFailed).toBe(true); }); }); }); describe('markNotification', () => { const id = 'notification-123'; describe('github.com', () => { const accounts = { ...mockAccounts, enterpriseAccounts: [] }; const hostname = 'github.com'; it('should mark a notification as read with success - github.com', async () => { nock('https://api.github.com/') .patch(`/notifications/threads/${id}`) .reply(200); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.markNotification(accounts, id, hostname); }); await waitForNextUpdate(); expect(result.current.notifications.length).toBe(0); }); it('should mark a notification as read with failure - github.com', async () => { nock('https://api.github.com/') .patch(`/notifications/threads/${id}`) .reply(400); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.markNotification(accounts, id, hostname); }); await waitForNextUpdate(); expect(result.current.notifications.length).toBe(0); }); }); describe('enterprise', () => { const accounts = { ...mockAccounts, token: null }; const hostname = 'github.gitify.io'; it('should mark a notification as read with success - enterprise', async () => { nock('https://github.gitify.io/') .patch(`/notifications/threads/${id}`) .reply(200); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.markNotification(accounts, id, hostname); }); await waitForNextUpdate(); expect(result.current.notifications.length).toBe(0); }); it('should mark a notification as read with failure - enterprise', async () => { nock('https://github.gitify.io/') .patch(`/notifications/threads/${id}`) .reply(400); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.markNotification(accounts, id, hostname); }); await waitForNextUpdate(); expect(result.current.notifications.length).toBe(0); }); }); }); describe('unsubscribeNotification', () => { const id = 'notification-123'; describe('github.com', () => { const accounts = { ...mockAccounts, enterpriseAccounts: [] }; const hostname = 'github.com'; it('should unsubscribe from a notification with success - github.com', async () => { // The unsubscribe endpoint call. nock('https://api.github.com/') .put(`/notifications/threads/${id}/subscription`) .reply(200); // The mark read endpoint call. nock('https://api.github.com/') .patch(`/notifications/threads/${id}`) .reply(200); const { result, waitForValueToChange } = renderHook(() => useNotifications() ); act(() => { result.current.unsubscribeNotification(accounts, id, hostname); }); await waitForValueToChange(() => { return result.current.isFetching; }); expect(result.current.notifications.length).toBe(0); }); it('should unsubscribe from a notification with failure - github.com', async () => { // The unsubscribe endpoint call. nock('https://api.github.com/') .put(`/notifications/threads/${id}/subscription`) .reply(400); // The mark read endpoint call. nock('https://api.github.com/') .patch(`/notifications/threads/${id}`) .reply(400); const { result, waitForValueToChange } = renderHook(() => useNotifications() ); act(() => { result.current.unsubscribeNotification(accounts, id, hostname); }); await waitForValueToChange(() => { return result.current.isFetching; }); expect(result.current.notifications.length).toBe(0); }); }); describe('enterprise', () => { const accounts = { ...mockAccounts, token: null }; const hostname = 'github.gitify.io'; it('should unsubscribe from a notification with success - enterprise', async () => { // The unsubscribe endpoint call. nock('https://github.gitify.io/') .put(`/notifications/threads/${id}/subscription`) .reply(200); // The mark read endpoint call. nock('https://github.gitify.io/') .patch(`/notifications/threads/${id}`) .reply(200); const { result, waitForValueToChange } = renderHook(() => useNotifications() ); act(() => { result.current.unsubscribeNotification(accounts, id, hostname); }); await waitForValueToChange(() => { return result.current.isFetching; }); expect(result.current.notifications.length).toBe(0); }); it('should unsubscribe from a notification with failure - enterprise', async () => { // The unsubscribe endpoint call. nock('https://github.gitify.io/') .put(`/notifications/threads/${id}/subscription`) .reply(400); // The mark read endpoint call. nock('https://github.gitify.io/') .patch(`/notifications/threads/${id}`) .reply(400); const { result, waitForValueToChange } = renderHook(() => useNotifications() ); act(() => { result.current.unsubscribeNotification(accounts, id, hostname); }); await waitForValueToChange(() => { return result.current.isFetching; }); expect(result.current.notifications.length).toBe(0); }); }); }); describe('markRepoNotifications', () => { const repoSlug = 'manosim/gitify'; describe('github.com', () => { const accounts = { ...mockAccounts, enterpriseAccounts: [] }; const hostname = 'github.com'; it("should mark a repository's notifications as read with success - github.com", async () => { nock('https://api.github.com/') .put(`/repos/${repoSlug}/notifications`) .reply(200); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.markRepoNotifications(accounts, repoSlug, hostname); }); await waitForNextUpdate(); expect(result.current.notifications.length).toBe(0); }); it("should mark a repository's notifications as read with failure - github.com", async () => { nock('https://api.github.com/') .put(`/repos/${repoSlug}/notifications`) .reply(400); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.markRepoNotifications(accounts, repoSlug, hostname); }); await waitForNextUpdate(); expect(result.current.notifications.length).toBe(0); }); }); describe('enterprise', () => { const accounts = { ...mockAccounts, token: null }; const hostname = 'github.gitify.io'; it("should mark a repository's notifications as read with success - enterprise", async () => { nock('https://github.gitify.io/') .put(`/repos/${repoSlug}/notifications`) .reply(200); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.markRepoNotifications(accounts, repoSlug, hostname); }); await waitForNextUpdate(); expect(result.current.notifications.length).toBe(0); }); it("should mark a repository's notifications as read with failure - enterprise", async () => { nock('https://github.gitify.io/') .put(`/repos/${repoSlug}/notifications`) .reply(400); const { result, waitForNextUpdate } = renderHook(() => useNotifications() ); act(() => { result.current.markRepoNotifications(accounts, repoSlug, hostname); }); await waitForNextUpdate(); expect(result.current.notifications.length).toBe(0); }); }); }); });
the_stack
import { expect } from '@0x/contracts-test-utils'; import { BigNumber, hexUtils } from '@0x/utils'; import 'mocha'; import { Connection, Repository } from 'typeorm'; import { getDBConnectionAsync } from '../src/db_connection'; import { TransactionEntity } from '../src/entities'; import { TransactionStates } from '../src/types'; import { parseUtils } from '../src/utils/parse_utils'; import { DatabaseKeysUsedForRateLimiter, MetaTransactionDailyLimiter, MetaTransactionRateLimiter, MetaTransactionRollingLimiter, RollingLimiterIntervalUnit, } from '../src/utils/rate-limiters'; import { MetaTransactionComposableLimiter } from '../src/utils/rate-limiters/meta_transaction_composable_rate_limiter'; import { MetaTransactionRollingValueLimiter } from '../src/utils/rate-limiters/meta_transaction_value_limiter'; import { setupDependenciesAsync, teardownDependenciesAsync } from './utils/deployment'; const SUITE_NAME = 'Rate Limiter Tests'; const TEST_API_KEY = 'test-key'; const TEST_FIRST_TAKER_ADDRESS = 'one'; const TEST_SECOND_TAKER_ADDRESS = 'two'; const DAILY_LIMIT = 10; let connection: Connection; let transactionRepository: Repository<TransactionEntity>; let dailyLimiter: MetaTransactionRateLimiter; let rollingLimiter: MetaTransactionRollingLimiter; let composedLimiter: MetaTransactionComposableLimiter; let rollingLimiterForTakerAddress: MetaTransactionRollingLimiter; let rollingValueLimiter: MetaTransactionRollingValueLimiter; function* intGenerator(): Iterator<number> { let i = 0; while (true) { yield i++; } } const intGen = intGenerator(); const newTx = ( apiKey: string, takerAddress?: string, values?: { value: number; gasPrice: number; gasUsed: number }, ): TransactionEntity => { const tx = TransactionEntity.make({ to: '', refHash: hexUtils.hash(intGen.next().value), takerAddress: takerAddress === undefined ? TEST_FIRST_TAKER_ADDRESS : takerAddress, apiKey, status: TransactionStates.Submitted, expectedMinedInSec: 123, }); if (values !== undefined) { const { value, gasPrice, gasUsed } = values; tx.gasPrice = new BigNumber(gasPrice); tx.gasUsed = gasUsed; tx.value = new BigNumber(value); } return tx; }; const generateNewTransactionsForKey = ( apiKey: string, numberOfTransactions: number, takerAddress?: string, values?: { value: number; gasPrice: number; gasUsed: number }, ): TransactionEntity[] => { const txes: TransactionEntity[] = []; for (let i = 0; i < numberOfTransactions; i++) { const tx = newTx(apiKey, takerAddress, values); txes.push(tx); } return txes; }; // NOTE: Because TypeORM does not allow us to override entities createdAt // directly, we resort to a raw query. const backdateTransactions = async (txes: TransactionEntity[], num: number, unit: string): Promise<void> => { const txesString = txes.map((tx) => `'${tx.refHash}'`).join(','); await transactionRepository.query( `UPDATE transactions SET created_at = now() - interval '${num} ${unit}' WHERE transactions.ref_hash IN (${txesString});`, ); }; const cleanTransactions = async (): Promise<void> => { await transactionRepository.query('DELETE FROM transactions;'); }; describe(SUITE_NAME, () => { before(async () => { await setupDependenciesAsync(SUITE_NAME); connection = await getDBConnectionAsync(); await connection.synchronize(true); transactionRepository = connection.getRepository(TransactionEntity); dailyLimiter = new MetaTransactionDailyLimiter(DatabaseKeysUsedForRateLimiter.ApiKey, connection, { allowedDailyLimit: DAILY_LIMIT, }); rollingLimiter = new MetaTransactionRollingLimiter(DatabaseKeysUsedForRateLimiter.ApiKey, connection, { allowedLimit: 10, intervalNumber: 1, intervalUnit: RollingLimiterIntervalUnit.Hours, }); rollingLimiterForTakerAddress = new MetaTransactionRollingLimiter( DatabaseKeysUsedForRateLimiter.TakerAddress, connection, { allowedLimit: 2, intervalNumber: 1, intervalUnit: RollingLimiterIntervalUnit.Minutes, }, ); rollingValueLimiter = new MetaTransactionRollingValueLimiter( DatabaseKeysUsedForRateLimiter.TakerAddress, connection, { allowedLimitEth: 1, intervalNumber: 1, intervalUnit: RollingLimiterIntervalUnit.Hours, }, ); composedLimiter = new MetaTransactionComposableLimiter([ dailyLimiter, rollingLimiter, rollingLimiterForTakerAddress, ]); }); after(async () => { await teardownDependenciesAsync(SUITE_NAME); }); describe('api key daily rate limiter', async () => { const context = { apiKey: TEST_API_KEY, takerAddress: TEST_FIRST_TAKER_ADDRESS }; it('should not trigger within limit', async () => { const firstCheck = await dailyLimiter.isAllowedAsync(context); expect(firstCheck.isAllowed).to.be.true(); await transactionRepository.save(generateNewTransactionsForKey(TEST_API_KEY, DAILY_LIMIT - 1)); const secondCheck = await dailyLimiter.isAllowedAsync(context); expect(secondCheck.isAllowed).to.be.true(); }); it('should not trigger for other api keys', async () => { await transactionRepository.save(generateNewTransactionsForKey('0ther-key', DAILY_LIMIT)); const { isAllowed } = await dailyLimiter.isAllowedAsync(context); expect(isAllowed).to.be.true(); }); it('should not trigger because of keys from a day before', async () => { const txes = generateNewTransactionsForKey(TEST_API_KEY, DAILY_LIMIT); await transactionRepository.save(txes); // tslint:disable-next-line:custom-no-magic-numbers await backdateTransactions(txes, 24, 'hours'); const { isAllowed } = await dailyLimiter.isAllowedAsync(context); expect(isAllowed).to.be.true(); }); it('should trigger after limit', async () => { await transactionRepository.save(generateNewTransactionsForKey(TEST_API_KEY, 1)); const { isAllowed } = await dailyLimiter.isAllowedAsync(context); expect(isAllowed).to.be.false(); }); }); describe('api rolling rate limiter', async () => { before(async () => { await cleanTransactions(); }); const context = { apiKey: TEST_API_KEY, takerAddress: TEST_FIRST_TAKER_ADDRESS }; it('shoult not trigger within limit', async () => { const firstCheck = await rollingLimiter.isAllowedAsync(context); expect(firstCheck.isAllowed).to.be.true(); await transactionRepository.save(generateNewTransactionsForKey(TEST_API_KEY, DAILY_LIMIT - 1)); const secondCheck = await rollingLimiter.isAllowedAsync(context); expect(secondCheck.isAllowed).to.be.true(); }); it('should not trigger because of keys from an interval before', async () => { const txes = generateNewTransactionsForKey(TEST_API_KEY, DAILY_LIMIT); await transactionRepository.save(txes); // tslint:disable-next-line:custom-no-magic-numbers await backdateTransactions(txes, 61, 'minutes'); const { isAllowed } = await rollingLimiter.isAllowedAsync(context); expect(isAllowed).to.be.true(); }); it('should trigger after limit', async () => { const txes = generateNewTransactionsForKey(TEST_API_KEY, 1); await transactionRepository.save(txes); // tslint:disable-next-line:custom-no-magic-numbers await backdateTransactions(txes, 15, 'minutes'); const { isAllowed } = await rollingLimiter.isAllowedAsync(context); expect(isAllowed).to.be.false(); }); }); describe('api composable rate limiter', () => { before(async () => { await cleanTransactions(); }); const firstTakerContext = { apiKey: TEST_API_KEY, takerAddress: TEST_FIRST_TAKER_ADDRESS }; const secondTakerContext = { apiKey: TEST_API_KEY, takerAddress: TEST_SECOND_TAKER_ADDRESS }; it('should not trigger within limits', async () => { const firstCheck = await composedLimiter.isAllowedAsync(secondTakerContext); expect(firstCheck.isAllowed).to.be.true(); }); it('should trigger for the first taker address, but not the second', async () => { // tslint:disable-next-line:custom-no-magic-numbers const txes = generateNewTransactionsForKey(TEST_API_KEY, 2, TEST_FIRST_TAKER_ADDRESS); await transactionRepository.save(txes); const firstTakerCheck = await composedLimiter.isAllowedAsync(firstTakerContext); expect(firstTakerCheck.isAllowed).to.be.false(); const secondTakerCheck = await composedLimiter.isAllowedAsync(secondTakerContext); expect(secondTakerCheck.isAllowed).to.be.true(); }); it('should trigger all rate limiters', async () => { // tslint:disable-next-line:custom-no-magic-numbers const txes = generateNewTransactionsForKey(TEST_API_KEY, 20, TEST_SECOND_TAKER_ADDRESS); await transactionRepository.save(txes); const check = await composedLimiter.isAllowedAsync(secondTakerContext); expect(check.isAllowed).to.be.false(); }); }); describe('value rate limiter', () => { before(async () => { await cleanTransactions(); }); const context = { apiKey: TEST_API_KEY, takerAddress: TEST_SECOND_TAKER_ADDRESS }; // tslint:disable:custom-no-magic-numbers it('should not trigger when under value limit', async () => { const txes = generateNewTransactionsForKey(TEST_API_KEY, 5, TEST_SECOND_TAKER_ADDRESS, { value: 10 ** 17, gasPrice: 10 ** 9, gasUsed: 400000, }); await transactionRepository.save(txes); const check = await rollingValueLimiter.isAllowedAsync(context); expect(check.isAllowed).to.be.true(); }); it('should trigger when over value limit', async () => { const txes = generateNewTransactionsForKey(TEST_API_KEY, 10, TEST_SECOND_TAKER_ADDRESS, { value: 10 ** 18, gasPrice: 10 ** 9, gasUsed: 400000, }); await transactionRepository.save(txes); const check = await rollingValueLimiter.isAllowedAsync(context); expect(check.isAllowed).to.be.false(); }); // tslint:enable:custom-no-magic-numbers }); describe('parser utils', () => { it('should throw on invalid json string', () => { const configString = '<html></html>'; expect(() => { parseUtils.parseJsonStringForMetaTransactionRateLimitConfigOrThrow(configString); }).to.throw('Unexpected token < in JSON at position 0'); }); it('should throw on invalid configuration', () => { const configString = '{"api_key":{"daily": true}}'; expect(() => { parseUtils.parseJsonStringForMetaTransactionRateLimitConfigOrThrow(configString); }).to.throw('Expected allowedDailyLimit to be of type number, encountered: undefined'); }); it('should throw on invalid enum in rolling configuration', () => { const configString = '{"api_key":{"rolling": {"allowedLimit":1,"intervalNumber":1,"intervalUnit":"months"}}}'; expect(() => { parseUtils.parseJsonStringForMetaTransactionRateLimitConfigOrThrow(configString); }).to.throw("Expected intervalUnit to be one of: 'hours', 'minutes', encountered: months"); }); it('should throw on an unsupported database key', () => { const config = { api_key: {}, taker_address: {}, private_key: {}, }; expect(() => { parseUtils.parseJsonStringForMetaTransactionRateLimitConfigOrThrow(JSON.stringify(config)); }).to.throw("Expected dbField to be one of: 'api_key', 'taker_address', encountered: private_key"); }); it('should parse daily configuration properly', () => { const expectedDailyConfig = { allowedDailyLimit: 1 }; const configString = `{"api_key":{"daily": ${JSON.stringify(expectedDailyConfig)}}}`; const config = parseUtils.parseJsonStringForMetaTransactionRateLimitConfigOrThrow(configString); expect(config.api_key!.daily).to.be.deep.equal(expectedDailyConfig); }); it('should parse rolling configuration properly', () => { const expectedRollingConfig = { allowedLimit: 1, intervalNumber: 1, intervalUnit: 'hours' }; const configString = `{"api_key":{"rolling": ${JSON.stringify(expectedRollingConfig)}}}`; const config = parseUtils.parseJsonStringForMetaTransactionRateLimitConfigOrThrow(configString); expect(config.api_key!.rolling).to.be.deep.equal(expectedRollingConfig); }); it('should parse rolling value configuration properly', () => { const expectedRollingValueConfig = { allowedLimitEth: 1, intervalNumber: 1, intervalUnit: 'hours' }; const configString = `{"api_key":{"rollingValue": ${JSON.stringify(expectedRollingValueConfig)}}}`; const config = parseUtils.parseJsonStringForMetaTransactionRateLimitConfigOrThrow(configString); expect(config.api_key!.rollingValue).to.be.deep.equal(expectedRollingValueConfig); }); it('should parse a full configuration', () => { const expectedConfig = { api_key: { daily: { allowedDailyLimit: 1 }, rolling: { allowedLimit: 1, intervalNumber: 1, intervalUnit: 'hours' }, rollingValue: { allowedLimitEth: 1, intervalNumber: 1, intervalUnit: 'hours' }, }, taker_address: { daily: { allowedDailyLimit: 1 }, rolling: { allowedLimit: 1, intervalNumber: 1, intervalUnit: 'hours' }, rollingValue: { allowedLimitEth: 1, intervalNumber: 1, intervalUnit: 'hours' }, }, }; const parsedConfig = parseUtils.parseJsonStringForMetaTransactionRateLimitConfigOrThrow( JSON.stringify(expectedConfig), ); expect(parsedConfig).to.be.deep.equal(expectedConfig); }); }); });
the_stack
declare module 'vscode' { /** * Defines a problem pattern */ export interface ProblemPattern { /** * The regular expression to find a problem in the console output of an * executed task. */ regexp: RegExp; /** * The match group index of the filename. * * Defaults to 1 if omitted. */ file?: number; /** * The match group index of the problems's location. Valid location * patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). * If omitted the line and colum properties are used. */ location?: number; /** * The match group index of the problem's line in the source file. * * Defaults to 2 if omitted. */ line?: number; /** * The match group index of the problem's character in the source file. * * Defaults to 3 if omitted. */ character?: number; /** * The match group index of the problem's end line in the source file. * * Defaults to undefined. No end line is captured. */ endLine?: number; /** * The match group index of the problem's end character in the source file. * * Defaults to undefined. No end column is captured. */ endCharacter?: number; /** * The match group index of the problem's severity. * * Defaults to undefined. In this case the problem matcher's severity * is used. */ severity?: number; /** * The match group index of the problems's code. * * Defaults to undefined. No code is captured. */ code?: number; /** * The match group index of the message. If omitted it defaults * to 4 if location is specified. Otherwise it defaults to 5. */ message?: number; /** * Specifies if the last pattern in a multi line problem matcher should * loop as long as it does match a line consequently. Only valid on the * last problem pattern in a multi line problem matcher. */ loop?: boolean; } /** * A multi line problem pattern. */ export type MultiLineProblemPattern = ProblemPattern[]; /** * The way how the file location is interpreted */ export enum FileLocationKind { /** * VS Code should decide based on whether the file path found in the * output is absolute or relative. A relative file path will be treated * relative to the workspace root. */ Auto = 1, /** * Always treat the file path relative. */ Relative = 2, /** * Always treat the file path absolute. */ Absolute = 3 } /** * Controls to which kind of documents problems are applied. */ export enum ApplyToKind { /** * Problems are applied to all documents. */ AllDocuments = 1, /** * Problems are applied to open documents only. */ OpenDocuments = 2, /** * Problems are applied to closed documents only. */ ClosedDocuments = 3 } /** * A background monitor pattern */ export interface BackgroundPattern { /** * The actual regular expression */ regexp: RegExp; /** * The match group index of the filename. If provided the expression * is matched for that file only. */ file?: number; } /** * A description to control the activity of a problem matcher * watching a background task. */ export interface BackgroundMonitor { /** * If set to true the monitor is in active mode when the task * starts. This is equals of issuing a line that matches the * beginPattern. */ activeOnStart?: boolean; /** * If matched in the output the start of a background activity is signaled. */ beginsPattern: RegExp | BackgroundPattern; /** * If matched in the output the end of a background activity is signaled. */ endsPattern: RegExp | BackgroundPattern; } /** * Defines a problem matcher */ export interface ProblemMatcher { /** * The owner of a problem. Defaults to a generated id * if omitted. */ owner?: string; /** * The type of documents problems detected by this matcher * apply to. Default to `ApplyToKind.AllDocuments` if omitted. */ applyTo?: ApplyToKind; /** * How a file location recognize by a matcher should be interpreted. If omitted the file location * if `FileLocationKind.Auto`. */ fileLocation?: FileLocationKind | string; /** * The actual pattern used by the problem matcher. */ pattern: ProblemPattern | MultiLineProblemPattern; /** * The default severity of a detected problem in the output. Used * if the `ProblemPattern` doesn't define a severity match group. */ severity?: DiagnosticSeverity; /** * A background monitor for tasks that are running in the background. */ backgound?: BackgroundMonitor; } /** * Controls the behaviour of the terminal's visibility. */ export enum RevealKind { /** * Always brings the terminal to front if the task is executed. */ Always = 1, /** * Only brings the terminal to front if a problem is detected executing the task * (e.g. the task couldn't be started because). */ Silent = 2, /** * The terminal never comes to front when the task is executed. */ Never = 3 } /** * Controls terminal specific behaviour. */ export interface TerminalBehaviour { /** * Controls whether the terminal executing a task is brought to front or not. * Defaults to `RevealKind.Always`. */ reveal?: RevealKind; /** * Controls whether the command is echoed in the terminal or not. */ echo?: boolean; } export interface ProcessOptions { /** * The current working directory of the executed program or shell. * If omitted VSCode's current workspace root is used. */ cwd?: string; /** * The additional environment of the executed program or shell. If omitted * the parent process' environment is used. If provided it is merged with * the parent process' environment. */ env?: { [key: string]: string }; } export namespace TaskGroup { /** * The clean task group */ export const Clean: 'clean'; /** * The build task group */ export const Build: 'build'; /** * The rebuild all task group */ export const RebuildAll: 'rebuildAll'; /** * The test task group */ export const Test: 'test'; } /** * The supported task groups. */ export type TaskGroup = 'clean' | 'build' | 'rebuildAll' | 'test'; /** * A task that starts an external process. */ export class ProcessTask { /** * Creates a process task. * * @param name the task's name. Is presented in the user interface. * @param process the process to start. * @param problemMatchers the problem matchers to use. */ constructor(name: string, process: string, ...problemMatchers: ProblemMatcher[]); /** * Creates a process task. * * @param name the task's name. Is presented in the user interface. * @param process the process to start. * @param args arguments to be passed to the process. * @param problemMatchers the problem matchers to use. */ constructor(name: string, process: string, args: string[], ...problemMatchers: ProblemMatcher[]); /** * Creates a process task. * * @param name the task's name. Is presented in the user interface. * @param process the process to start. * @param args arguments to be passed to the process. * @param options additional options for the started process. * @param problemMatchers the problem matchers to use. */ constructor(name: string, process: string, args: string[], options: ProcessOptions, ...problemMatchers: ProblemMatcher[]); /** * The task's name */ readonly name: string; /** * The task's identifier. If omitted the name is * used as an identifier. */ identifier: string; /** * Whether the task is a background task or not. */ isBackground: boolean; /** * The process to be executed. */ readonly process: string; /** * The arguments passed to the process. Defaults to an empty array. */ args: string[]; /** * The task group this tasks belongs to. Defaults to undefined meaning * that the task doesn't belong to any special group. */ group?: TaskGroup; /** * The process options used when the process is executed. * Defaults to an empty object literal. */ options: ProcessOptions; /** * The terminal options. Defaults to an empty object literal. */ terminal: TerminalBehaviour; /** * The problem matchers attached to the task. Defaults to an empty * array. */ problemMatchers: ProblemMatcher[]; } export type ShellOptions = { /** * The shell executable. */ executable: string; /** * The arguments to be passed to the shell executable used to run the task. */ shellArgs?: string[]; /** * The current working directory of the executed shell. * If omitted VSCode's current workspace root is used. */ cwd?: string; /** * The additional environment of the executed shell. If omitted * the parent process' environment is used. If provided it is merged with * the parent process' environment. */ env?: { [key: string]: string }; } | { /** * The current working directory of the executed shell. * If omitted VSCode's current workspace root is used. */ cwd: string; /** * The additional environment of the executed shell. If omitted * the parent process' environment is used. If provided it is merged with * the parent process' environment. */ env?: { [key: string]: string }; } | { /** * The current working directory of the executed shell. * If omitted VSCode's current workspace root is used. */ cwd?: string; /** * The additional environment of the executed shell. If omitted * the parent process' environment is used. If provided it is merged with * the parent process' environment. */ env: { [key: string]: string }; }; /** * A task that executes a shell command. */ export class ShellTask { /** * Creates a shell task. * * @param name the task's name. Is presented in the user interface. * @param commandLine the command line to execute. * @param problemMatchers the problem matchers to use. */ constructor(name: string, commandLine: string, ...problemMatchers: ProblemMatcher[]); /** * Creates a shell task. * * @param name the task's name. Is presented in the user interface. * @param commandLine the command line to execute. * @param options additional options used when creating the shell. * @param problemMatchers the problem matchers to use. */ constructor(name: string, commandLine: string, options: ShellOptions, ...problemMatchers: ProblemMatcher[]); /** * The task's name */ readonly name: string; /** * The task's identifier. If omitted the name is * used as an identifier. */ identifier: string; /** * Whether the task is a background task or not. */ isBackground: boolean; /** * The command line to execute. */ readonly commandLine: string; /** * The task group this tasks belongs to. Defaults to undefined meaning * that the task doesn't belong to any special group. */ group?: TaskGroup; /** * The shell options used when the shell is executed. Defaults to an * empty object literal. */ options: ShellOptions; /** * The terminal options. Defaults to an empty object literal. */ terminal: TerminalBehaviour; /** * The problem matchers attached to the task. Defaults to an empty * array. */ problemMatchers: ProblemMatcher[]; } export type Task = ProcessTask | ShellTask; /** * A task provider allows to add tasks to the task service. * A task provider is registerd via #workspace.registerTaskProvider. */ export interface TaskProvider { /** * Provides additional tasks. * @param token A cancellation token. * @return a #TaskSet */ provideTasks(token: CancellationToken): ProviderResult<Task[]>; } export namespace workspace { /** * Register a task provider. * * @param provider A task provider. * @return A [disposable](#Disposable) that unregisters this provider when being disposed. */ export function registerTaskProvider(provider: TaskProvider): Disposable; } export namespace window { export function sampleFunction(): Thenable<any>; } export namespace window { /** * Create a new [TreeView](#TreeView) instance. * * @param viewId A unique id that identifies the view. * @param provider A [TreeDataProvider](#TreeDataProvider). * @return An instance of [TreeView](#TreeView). */ export function createTreeView<T>(viewId: string, provider: TreeDataProvider<T>): TreeView<T>; } /** * An source control is able to provide [resource states](#SourceControlResourceState) * to the editor and interact with the editor in several source control related ways. */ export interface TreeView<T> { /** * Refresh the given nodes */ refresh(...nodes: T[]): void; /** * Dispose this view */ dispose(): void; } /** * A data provider for a tree view contribution. * * The contributed tree view will ask the corresponding provider to provide the root * node and resolve children for each node. In addition, the provider could **optionally** * provide the following information for each node: * - label: A human-readable label used for rendering the node. * - hasChildren: Whether the node has children and is expandable. * - clickCommand: A command to execute when the node is clicked. */ export interface TreeDataProvider<T> { /** * Provide the root node. This function will be called when the tree explorer is activated * for the first time. The root node is hidden and its direct children will be displayed on the first level of * the tree explorer. * * @return The root node. */ provideRootNode(): T | Thenable<T>; /** * Resolve the children of `node`. * * @param node The node from which the provider resolves children. * @return Children of `node`. */ resolveChildren?(node: T): T[] | Thenable<T[]>; /** * Provide a human-readable string that will be used for rendering the node. Default to use * `node.toString()` if not provided. * * @param node The node from which the provider computes label. * @return A human-readable label. */ getLabel?(node: T): string; /** * Determine if `node` has children and is expandable. Default to `true` if not provided. * * @param node The node to determine if it has children and is expandable. * @return A boolean that determines if `node` has children and is expandable. */ getHasChildren?(node: T): boolean; /** * Get the command to execute when `node` is clicked. * * Commands can be registered through [registerCommand](#commands.registerCommand). `node` will be provided * as the first argument to the command's callback function. * * @param node The node that the command is associated with. * @return The command to execute when `node` is clicked. */ getClickCommand?(node: T): Command; } /** * The contiguous set of modified lines in a diff. */ export interface LineChange { readonly originalStartLineNumber: number; readonly originalEndLineNumber: number; readonly modifiedStartLineNumber: number; readonly modifiedEndLineNumber: number; } export namespace commands { /** * Registers a diff information command that can be invoked via a keyboard shortcut, * a menu item, an action, or directly. * * Diff information commands are different from ordinary [commands](#commands.registerCommand) as * they only execute when there is an active diff editor when the command is called, and the diff * information has been computed. Also, the command handler of an editor command has access to * the diff information. * * @param command A unique identifier for the command. * @param callback A command handler function with access to the [diff information](#LineChange). * @param thisArg The `this` context used when invoking the handler function. * @return Disposable which unregisters this command on disposal. */ export function registerDiffInformationCommand(command: string, callback: (diff: LineChange[], ...args: any[]) => any, thisArg?: any): Disposable; } export interface Terminal { /** * The name of the terminal. */ readonly name: string; /** * The process ID of the shell process. */ readonly processId: Thenable<number>; /** * Send text to the terminal. The text is written to the stdin of the underlying pty process * (shell) of the terminal. * * @param text The text to send. * @param addNewLine Whether to add a new line to the text being sent, this is normally * required to run a command in the terminal. The character(s) added are \n or \r\n * depending on the platform. This defaults to `true`. */ sendText(text: string, addNewLine?: boolean): void; /** * Show the terminal panel and reveal this terminal in the UI. * * @param preserveFocus When `true` the terminal will not take focus. */ show(preserveFocus?: boolean): void; /** * Hide the terminal panel if this terminal is currently showing. */ hide(): void; /** * Dispose and free associated resources. */ dispose(): void; /** * Experimental API that allows listening to the raw data stream coming from the terminal's * pty process (including ANSI escape sequences). * * @param callback The callback that is triggered when data is sent to the terminal. */ onData(callback: (data: string) => any): void; } }
the_stack
import * as iam from '@aws-cdk/aws-iam'; import * as secretsmanager from '@aws-cdk/aws-secretsmanager'; import { Construct } from 'constructs'; import { IEngine } from './engine'; import { EngineVersion } from './engine-version'; import { IParameterGroup, ParameterGroup } from './parameter-group'; /** * The extra options passed to the {@link IClusterEngine.bindToCluster} method. */ export interface ClusterEngineBindOptions { /** * The role used for S3 importing. * * @default - none */ readonly s3ImportRole?: iam.IRole; /** * The role used for S3 exporting. * * @default - none */ readonly s3ExportRole?: iam.IRole; /** * The customer-provided ParameterGroup. * * @default - none */ readonly parameterGroup?: IParameterGroup; } /** * The type returned from the {@link IClusterEngine.bindToCluster} method. */ export interface ClusterEngineConfig { /** * The ParameterGroup to use for the cluster. * * @default - no ParameterGroup will be used */ readonly parameterGroup?: IParameterGroup; /** * The port to use for this cluster, * unless the customer specified the port directly. * * @default - use the default port for clusters (3306) */ readonly port?: number; /** * Features supported by the database engine. * * @see https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DBEngineVersion.html * * @default - no features */ readonly features?: ClusterEngineFeatures; } /** * Represents Database Engine features */ export interface ClusterEngineFeatures { /** * Feature name for the DB instance that the IAM role to access the S3 bucket for import * is to be associated with. * * @default - no s3Import feature name */ readonly s3Import?: string; /** * Feature name for the DB instance that the IAM role to export to S3 bucket is to be * associated with. * * @default - no s3Export feature name */ readonly s3Export?: string; } /** * The interface representing a database cluster (as opposed to instance) engine. */ export interface IClusterEngine extends IEngine { /** The application used by this engine to perform rotation for a single-user scenario. */ readonly singleUserRotationApplication: secretsmanager.SecretRotationApplication; /** The application used by this engine to perform rotation for a multi-user scenario. */ readonly multiUserRotationApplication: secretsmanager.SecretRotationApplication; /** The log types that are available with this engine type */ readonly supportedLogTypes: string[]; /** * Whether the IAM Roles used for data importing and exporting need to be combined for this Engine, * or can they be kept separate. * * @default false */ readonly combineImportAndExportRoles?: boolean; /** * Method called when the engine is used to create a new cluster. */ bindToCluster(scope: Construct, options: ClusterEngineBindOptions): ClusterEngineConfig; } interface ClusterEngineBaseProps { readonly engineType: string; readonly singleUserRotationApplication: secretsmanager.SecretRotationApplication; readonly multiUserRotationApplication: secretsmanager.SecretRotationApplication; readonly defaultPort?: number; readonly engineVersion?: EngineVersion; readonly features?: ClusterEngineFeatures; } abstract class ClusterEngineBase implements IClusterEngine { public readonly engineType: string; public readonly engineVersion?: EngineVersion; public readonly parameterGroupFamily?: string; public readonly singleUserRotationApplication: secretsmanager.SecretRotationApplication; public readonly multiUserRotationApplication: secretsmanager.SecretRotationApplication; public abstract readonly supportedLogTypes: string[]; private readonly defaultPort?: number; private readonly features?: ClusterEngineFeatures; constructor(props: ClusterEngineBaseProps) { this.engineType = props.engineType; this.features = props.features; this.singleUserRotationApplication = props.singleUserRotationApplication; this.multiUserRotationApplication = props.multiUserRotationApplication; this.defaultPort = props.defaultPort; this.engineVersion = props.engineVersion; this.parameterGroupFamily = this.engineVersion ? `${this.engineType}${this.engineVersion.majorVersion}` : undefined; } public bindToCluster(scope: Construct, options: ClusterEngineBindOptions): ClusterEngineConfig { const parameterGroup = options.parameterGroup ?? this.defaultParameterGroup(scope); return { parameterGroup, port: this.defaultPort, features: this.features, }; } /** * Return an optional default ParameterGroup, * possibly an imported one, * if one wasn't provided by the customer explicitly. */ protected abstract defaultParameterGroup(scope: Construct): IParameterGroup | undefined; } interface MysqlClusterEngineBaseProps { readonly engineType: string; readonly engineVersion?: EngineVersion; readonly defaultMajorVersion: string; readonly combineImportAndExportRoles?: boolean; } abstract class MySqlClusterEngineBase extends ClusterEngineBase { public readonly engineFamily = 'MYSQL'; public readonly supportedLogTypes: string[] = ['error', 'general', 'slowquery', 'audit']; public readonly combineImportAndExportRoles?: boolean; constructor(props: MysqlClusterEngineBaseProps) { super({ ...props, singleUserRotationApplication: secretsmanager.SecretRotationApplication.MYSQL_ROTATION_SINGLE_USER, multiUserRotationApplication: secretsmanager.SecretRotationApplication.MYSQL_ROTATION_MULTI_USER, engineVersion: props.engineVersion ? props.engineVersion : { majorVersion: props.defaultMajorVersion }, }); this.combineImportAndExportRoles = props.combineImportAndExportRoles; } public bindToCluster(scope: Construct, options: ClusterEngineBindOptions): ClusterEngineConfig { const config = super.bindToCluster(scope, options); const parameterGroup = options.parameterGroup ?? (options.s3ImportRole || options.s3ExportRole ? new ParameterGroup(scope, 'ClusterParameterGroup', { engine: this, }) : config.parameterGroup); if (options.s3ImportRole) { // versions which combine the import and export Roles (right now, this is only 8.0) // require a different parameter name (identical for both import and export) const s3ImportParam = this.combineImportAndExportRoles ? 'aws_default_s3_role' : 'aurora_load_from_s3_role'; parameterGroup?.addParameter(s3ImportParam, options.s3ImportRole.roleArn); } if (options.s3ExportRole) { const s3ExportParam = this.combineImportAndExportRoles ? 'aws_default_s3_role' : 'aurora_select_into_s3_role'; parameterGroup?.addParameter(s3ExportParam, options.s3ExportRole.roleArn); } return { ...config, parameterGroup, }; } } /** * The versions for the Aurora cluster engine * (those returned by {@link DatabaseClusterEngine.aurora}). */ export class AuroraEngineVersion { /** Version "5.6.10a". */ public static readonly VER_10A = AuroraEngineVersion.builtIn_5_6('10a', false); /** Version "5.6.mysql_aurora.1.17.9". */ public static readonly VER_1_17_9 = AuroraEngineVersion.builtIn_5_6('1.17.9'); /** Version "5.6.mysql_aurora.1.19.0". */ public static readonly VER_1_19_0 = AuroraEngineVersion.builtIn_5_6('1.19.0'); /** Version "5.6.mysql_aurora.1.19.1". */ public static readonly VER_1_19_1 = AuroraEngineVersion.builtIn_5_6('1.19.1'); /** Version "5.6.mysql_aurora.1.19.2". */ public static readonly VER_1_19_2 = AuroraEngineVersion.builtIn_5_6('1.19.2'); /** Version "5.6.mysql_aurora.1.19.5". */ public static readonly VER_1_19_5 = AuroraEngineVersion.builtIn_5_6('1.19.5'); /** Version "5.6.mysql_aurora.1.19.6". */ public static readonly VER_1_19_6 = AuroraEngineVersion.builtIn_5_6('1.19.6'); /** Version "5.6.mysql_aurora.1.20.0". */ public static readonly VER_1_20_0 = AuroraEngineVersion.builtIn_5_6('1.20.0'); /** Version "5.6.mysql_aurora.1.20.1". */ public static readonly VER_1_20_1 = AuroraEngineVersion.builtIn_5_6('1.20.1'); /** Version "5.6.mysql_aurora.1.21.0". */ public static readonly VER_1_21_0 = AuroraEngineVersion.builtIn_5_6('1.21.0'); /** Version "5.6.mysql_aurora.1.22.0". */ public static readonly VER_1_22_0 = AuroraEngineVersion.builtIn_5_6('1.22.0'); /** Version "5.6.mysql_aurora.1.22.1". */ public static readonly VER_1_22_1 = AuroraEngineVersion.builtIn_5_6('1.22.1'); /** Version "5.6.mysql_aurora.1.22.1.3". */ public static readonly VER_1_22_1_3 = AuroraEngineVersion.builtIn_5_6('1.22.1.3'); /** Version "5.6.mysql_aurora.1.22.2". */ public static readonly VER_1_22_2 = AuroraEngineVersion.builtIn_5_6('1.22.2'); /** * Create a new AuroraEngineVersion with an arbitrary version. * * @param auroraFullVersion the full version string, * for example "5.6.mysql_aurora.1.78.3.6" * @param auroraMajorVersion the major version of the engine, * defaults to "5.6" */ public static of(auroraFullVersion: string, auroraMajorVersion?: string): AuroraEngineVersion { return new AuroraEngineVersion(auroraFullVersion, auroraMajorVersion); } private static builtIn_5_6(minorVersion: string, addStandardPrefix: boolean = true): AuroraEngineVersion { return new AuroraEngineVersion(`5.6.${addStandardPrefix ? 'mysql_aurora.' : ''}${minorVersion}`); } /** The full version string, for example, "5.6.mysql_aurora.1.78.3.6". */ public readonly auroraFullVersion: string; /** The major version of the engine. Currently, it's always "5.6". */ public readonly auroraMajorVersion: string; private constructor(auroraFullVersion: string, auroraMajorVersion: string = '5.6') { this.auroraFullVersion = auroraFullVersion; this.auroraMajorVersion = auroraMajorVersion; } } /** * Creation properties of the plain Aurora database cluster engine. * Used in {@link DatabaseClusterEngine.aurora}. */ export interface AuroraClusterEngineProps { /** The version of the Aurora cluster engine. */ readonly version: AuroraEngineVersion; } class AuroraClusterEngine extends MySqlClusterEngineBase { constructor(version?: AuroraEngineVersion) { super({ engineType: 'aurora', engineVersion: version ? { fullVersion: version.auroraFullVersion, majorVersion: version.auroraMajorVersion, } : undefined, defaultMajorVersion: '5.6', }); } protected defaultParameterGroup(_scope: Construct): IParameterGroup | undefined { // the default.aurora5.6 ParameterGroup is actually the default, // so just return undefined in this case return undefined; } } /** * The versions for the Aurora MySQL cluster engine * (those returned by {@link DatabaseClusterEngine.auroraMysql}). */ export class AuroraMysqlEngineVersion { /** Version "5.7.12". */ public static readonly VER_5_7_12 = AuroraMysqlEngineVersion.builtIn_5_7('12', false); /** Version "5.7.mysql_aurora.2.03.2". */ public static readonly VER_2_03_2 = AuroraMysqlEngineVersion.builtIn_5_7('2.03.2'); /** Version "5.7.mysql_aurora.2.03.3". */ public static readonly VER_2_03_3 = AuroraMysqlEngineVersion.builtIn_5_7('2.03.3'); /** Version "5.7.mysql_aurora.2.03.4". */ public static readonly VER_2_03_4 = AuroraMysqlEngineVersion.builtIn_5_7('2.03.4'); /** Version "5.7.mysql_aurora.2.04.0". */ public static readonly VER_2_04_0 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.0'); /** Version "5.7.mysql_aurora.2.04.1". */ public static readonly VER_2_04_1 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.1'); /** Version "5.7.mysql_aurora.2.04.2". */ public static readonly VER_2_04_2 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.2'); /** Version "5.7.mysql_aurora.2.04.3". */ public static readonly VER_2_04_3 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.3'); /** Version "5.7.mysql_aurora.2.04.4". */ public static readonly VER_2_04_4 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.4'); /** Version "5.7.mysql_aurora.2.04.5". */ public static readonly VER_2_04_5 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.5'); /** Version "5.7.mysql_aurora.2.04.6". */ public static readonly VER_2_04_6 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.6'); /** Version "5.7.mysql_aurora.2.04.7". */ public static readonly VER_2_04_7 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.7'); /** Version "5.7.mysql_aurora.2.04.8". */ public static readonly VER_2_04_8 = AuroraMysqlEngineVersion.builtIn_5_7('2.04.8'); /** Version "5.7.mysql_aurora.2.05.0". */ public static readonly VER_2_05_0 = AuroraMysqlEngineVersion.builtIn_5_7('2.05.0'); /** Version "5.7.mysql_aurora.2.06.0". */ public static readonly VER_2_06_0 = AuroraMysqlEngineVersion.builtIn_5_7('2.06.0'); /** Version "5.7.mysql_aurora.2.07.0". */ public static readonly VER_2_07_0 = AuroraMysqlEngineVersion.builtIn_5_7('2.07.0'); /** Version "5.7.mysql_aurora.2.07.1". */ public static readonly VER_2_07_1 = AuroraMysqlEngineVersion.builtIn_5_7('2.07.1'); /** Version "5.7.mysql_aurora.2.07.2". */ public static readonly VER_2_07_2 = AuroraMysqlEngineVersion.builtIn_5_7('2.07.2'); /** Version "5.7.mysql_aurora.2.08.0". */ public static readonly VER_2_08_0 = AuroraMysqlEngineVersion.builtIn_5_7('2.08.0'); /** Version "5.7.mysql_aurora.2.08.1". */ public static readonly VER_2_08_1 = AuroraMysqlEngineVersion.builtIn_5_7('2.08.1'); /** Version "5.7.mysql_aurora.2.08.2". */ public static readonly VER_2_08_2 = AuroraMysqlEngineVersion.builtIn_5_7('2.08.2'); /** Version "5.7.mysql_aurora.2.09.0". */ public static readonly VER_2_09_0 = AuroraMysqlEngineVersion.builtIn_5_7('2.09.0'); /** Version "5.7.mysql_aurora.2.09.1". */ public static readonly VER_2_09_1 = AuroraMysqlEngineVersion.builtIn_5_7('2.09.1'); /** Version "5.7.mysql_aurora.2.09.2". */ public static readonly VER_2_09_2 = AuroraMysqlEngineVersion.builtIn_5_7('2.09.2'); /** Version "5.7.mysql_aurora.2.09.3". */ public static readonly VER_2_09_3 = AuroraMysqlEngineVersion.builtIn_5_7('2.09.3'); /** Version "5.7.mysql_aurora.2.10.0". */ public static readonly VER_2_10_0 = AuroraMysqlEngineVersion.builtIn_5_7('2.10.0'); /** Version "5.7.mysql_aurora.2.10.1". */ public static readonly VER_2_10_1 = AuroraMysqlEngineVersion.builtIn_5_7('2.10.1'); /** Version "5.7.mysql_aurora.2.10.2". */ public static readonly VER_2_10_2 = AuroraMysqlEngineVersion.builtIn_5_7('2.10.2'); /** Version "8.0.mysql_aurora.3.01.0". */ public static readonly VER_3_01_0 = AuroraMysqlEngineVersion.builtIn_8_0('3.01.0'); /** * Create a new AuroraMysqlEngineVersion with an arbitrary version. * * @param auroraMysqlFullVersion the full version string, * for example "5.7.mysql_aurora.2.78.3.6" * @param auroraMysqlMajorVersion the major version of the engine, * defaults to "5.7" */ public static of(auroraMysqlFullVersion: string, auroraMysqlMajorVersion?: string): AuroraMysqlEngineVersion { return new AuroraMysqlEngineVersion(auroraMysqlFullVersion, auroraMysqlMajorVersion); } private static builtIn_5_7(minorVersion: string, addStandardPrefix: boolean = true): AuroraMysqlEngineVersion { return new AuroraMysqlEngineVersion(`5.7.${addStandardPrefix ? 'mysql_aurora.' : ''}${minorVersion}`); } private static builtIn_8_0(minorVersion: string): AuroraMysqlEngineVersion { // 8.0 of the MySQL engine needs to combine the import and export Roles return new AuroraMysqlEngineVersion(`8.0.mysql_aurora.${minorVersion}`, '8.0', true); } /** The full version string, for example, "5.7.mysql_aurora.1.78.3.6". */ public readonly auroraMysqlFullVersion: string; /** The major version of the engine. Currently, it's either "5.7", or "8.0". */ public readonly auroraMysqlMajorVersion: string; /** * Whether this version requires combining the import and export IAM Roles. * * @internal */ public readonly _combineImportAndExportRoles?: boolean; private constructor( auroraMysqlFullVersion: string, auroraMysqlMajorVersion: string = '5.7', combineImportAndExportRoles?: boolean, ) { this.auroraMysqlFullVersion = auroraMysqlFullVersion; this.auroraMysqlMajorVersion = auroraMysqlMajorVersion; this._combineImportAndExportRoles = combineImportAndExportRoles; } } /** * Creation properties of the Aurora MySQL database cluster engine. * Used in {@link DatabaseClusterEngine.auroraMysql}. */ export interface AuroraMysqlClusterEngineProps { /** The version of the Aurora MySQL cluster engine. */ readonly version: AuroraMysqlEngineVersion; } class AuroraMysqlClusterEngine extends MySqlClusterEngineBase { constructor(version?: AuroraMysqlEngineVersion) { super({ engineType: 'aurora-mysql', engineVersion: version ? { fullVersion: version.auroraMysqlFullVersion, majorVersion: version.auroraMysqlMajorVersion, } : undefined, defaultMajorVersion: '5.7', combineImportAndExportRoles: version?._combineImportAndExportRoles, }); } protected defaultParameterGroup(scope: Construct): IParameterGroup | undefined { return ParameterGroup.fromParameterGroupName(scope, 'AuroraMySqlDatabaseClusterEngineDefaultParameterGroup', `default.${this.parameterGroupFamily}`); } } /** * Features supported by this version of the Aurora Postgres cluster engine. */ export interface AuroraPostgresEngineFeatures { /** * Whether this version of the Aurora Postgres cluster engine supports the S3 data import feature. * * @default false */ readonly s3Import?: boolean; /** * Whether this version of the Aurora Postgres cluster engine supports the S3 data export feature. * * @default false */ readonly s3Export?: boolean; } /** * The versions for the Aurora PostgreSQL cluster engine * (those returned by {@link DatabaseClusterEngine.auroraPostgres}). */ export class AuroraPostgresEngineVersion { /** Version "9.6.8". */ public static readonly VER_9_6_8 = AuroraPostgresEngineVersion.of('9.6.8', '9.6'); /** Version "9.6.9". */ public static readonly VER_9_6_9 = AuroraPostgresEngineVersion.of('9.6.9', '9.6'); /** Version "9.6.11". */ public static readonly VER_9_6_11 = AuroraPostgresEngineVersion.of('9.6.11', '9.6'); /** Version "9.6.12". */ public static readonly VER_9_6_12 = AuroraPostgresEngineVersion.of('9.6.12', '9.6'); /** Version "9.6.16". */ public static readonly VER_9_6_16 = AuroraPostgresEngineVersion.of('9.6.16', '9.6'); /** Version "9.6.17". */ public static readonly VER_9_6_17 = AuroraPostgresEngineVersion.of('9.6.17', '9.6'); /** Version "9.6.18". */ public static readonly VER_9_6_18 = AuroraPostgresEngineVersion.of('9.6.18', '9.6'); /** Version "9.6.19". */ public static readonly VER_9_6_19 = AuroraPostgresEngineVersion.of('9.6.19', '9.6'); /** Version "10.4". */ public static readonly VER_10_4 = AuroraPostgresEngineVersion.of('10.4', '10'); /** Version "10.5". */ public static readonly VER_10_5 = AuroraPostgresEngineVersion.of('10.5', '10'); /** Version "10.6". */ public static readonly VER_10_6 = AuroraPostgresEngineVersion.of('10.6', '10'); /** Version "10.7". */ public static readonly VER_10_7 = AuroraPostgresEngineVersion.of('10.7', '10', { s3Import: true }); /** Version "10.11". */ public static readonly VER_10_11 = AuroraPostgresEngineVersion.of('10.11', '10', { s3Import: true, s3Export: true }); /** Version "10.12". */ public static readonly VER_10_12 = AuroraPostgresEngineVersion.of('10.12', '10', { s3Import: true, s3Export: true }); /** Version "10.13". */ public static readonly VER_10_13 = AuroraPostgresEngineVersion.of('10.13', '10', { s3Import: true, s3Export: true }); /** Version "10.14". */ public static readonly VER_10_14 = AuroraPostgresEngineVersion.of('10.14', '10', { s3Import: true, s3Export: true }); /** Version "10.16". */ public static readonly VER_10_16 = AuroraPostgresEngineVersion.of('10.16', '10', { s3Import: true, s3Export: true }); /** Version "10.18". */ public static readonly VER_10_18 = AuroraPostgresEngineVersion.of('10.18', '10', { s3Import: true, s3Export: true }); /** Version "10.19". */ public static readonly VER_10_19 = AuroraPostgresEngineVersion.of('10.19', '10', { s3Import: true, s3Export: true }); /** Version "10.20". */ public static readonly VER_10_20 = AuroraPostgresEngineVersion.of('10.20', '10', { s3Import: true, s3Export: true }); /** Version "11.4". */ public static readonly VER_11_4 = AuroraPostgresEngineVersion.of('11.4', '11', { s3Import: true }); /** Version "11.6". */ public static readonly VER_11_6 = AuroraPostgresEngineVersion.of('11.6', '11', { s3Import: true, s3Export: true }); /** Version "11.7". */ public static readonly VER_11_7 = AuroraPostgresEngineVersion.of('11.7', '11', { s3Import: true, s3Export: true }); /** Version "11.8". */ public static readonly VER_11_8 = AuroraPostgresEngineVersion.of('11.8', '11', { s3Import: true, s3Export: true }); /** Version "11.9". */ public static readonly VER_11_9 = AuroraPostgresEngineVersion.of('11.9', '11', { s3Import: true, s3Export: true }); /** Version "11.11". */ public static readonly VER_11_11 = AuroraPostgresEngineVersion.of('11.11', '11', { s3Import: true, s3Export: true }); /** Version "11.13". */ public static readonly VER_11_13 = AuroraPostgresEngineVersion.of('11.13', '11', { s3Import: true, s3Export: true }); /** Version "11.14". */ public static readonly VER_11_14 = AuroraPostgresEngineVersion.of('11.14', '11', { s3Import: true, s3Export: true }); /** Version "11.15". */ public static readonly VER_11_15 = AuroraPostgresEngineVersion.of('11.15', '11', { s3Import: true, s3Export: true }); /** Version "12.4". */ public static readonly VER_12_4 = AuroraPostgresEngineVersion.of('12.4', '12', { s3Import: true, s3Export: true }); /** Version "12.6". */ public static readonly VER_12_6 = AuroraPostgresEngineVersion.of('12.6', '12', { s3Import: true, s3Export: true }); /** Version "12.8". */ public static readonly VER_12_8 = AuroraPostgresEngineVersion.of('12.8', '12', { s3Import: true, s3Export: true }); /** Version "12.8". */ public static readonly VER_12_9 = AuroraPostgresEngineVersion.of('12.9', '12', { s3Import: true, s3Export: true }); /** Version "12.10". */ public static readonly VER_12_10 = AuroraPostgresEngineVersion.of('12.10', '12', { s3Import: true, s3Export: true }); /** Version "13.3". */ public static readonly VER_13_3 = AuroraPostgresEngineVersion.of('13.3', '13', { s3Import: true, s3Export: true }); /** Version "13.4". */ public static readonly VER_13_4 = AuroraPostgresEngineVersion.of('13.4', '13', { s3Import: true, s3Export: true }); /** Version "13.5". */ public static readonly VER_13_5 = AuroraPostgresEngineVersion.of('13.5', '13', { s3Import: true, s3Export: true }); /** Version "13.6". */ public static readonly VER_13_6 = AuroraPostgresEngineVersion.of('13.6', '13', { s3Import: true, s3Export: true }); /** * Create a new AuroraPostgresEngineVersion with an arbitrary version. * * @param auroraPostgresFullVersion the full version string, * for example "9.6.25.1" * @param auroraPostgresMajorVersion the major version of the engine, * for example "9.6" */ public static of(auroraPostgresFullVersion: string, auroraPostgresMajorVersion: string, auroraPostgresFeatures?: AuroraPostgresEngineFeatures): AuroraPostgresEngineVersion { return new AuroraPostgresEngineVersion(auroraPostgresFullVersion, auroraPostgresMajorVersion, auroraPostgresFeatures); } /** The full version string, for example, "9.6.25.1". */ public readonly auroraPostgresFullVersion: string; /** The major version of the engine, for example, "9.6". */ public readonly auroraPostgresMajorVersion: string; /** * The supported features for the DB engine * * @internal */ public readonly _features: ClusterEngineFeatures; private constructor(auroraPostgresFullVersion: string, auroraPostgresMajorVersion: string, auroraPostgresFeatures?: AuroraPostgresEngineFeatures) { this.auroraPostgresFullVersion = auroraPostgresFullVersion; this.auroraPostgresMajorVersion = auroraPostgresMajorVersion; this._features = { s3Import: auroraPostgresFeatures?.s3Import ? 's3Import' : undefined, s3Export: auroraPostgresFeatures?.s3Export ? 's3Export' : undefined, }; } } /** * Creation properties of the Aurora PostgreSQL database cluster engine. * Used in {@link DatabaseClusterEngine.auroraPostgres}. */ export interface AuroraPostgresClusterEngineProps { /** The version of the Aurora PostgreSQL cluster engine. */ readonly version: AuroraPostgresEngineVersion; } class AuroraPostgresClusterEngine extends ClusterEngineBase { /** * feature name for the S3 data import feature */ private static readonly S3_IMPORT_FEATURE_NAME = 's3Import'; /** * feature name for the S3 data export feature */ private static readonly S3_EXPORT_FEATURE_NAME = 's3Export'; public readonly engineFamily = 'POSTGRESQL'; public readonly defaultUsername = 'postgres'; public readonly supportedLogTypes: string[] = ['postgresql']; constructor(version?: AuroraPostgresEngineVersion) { super({ engineType: 'aurora-postgresql', singleUserRotationApplication: secretsmanager.SecretRotationApplication.POSTGRES_ROTATION_SINGLE_USER, multiUserRotationApplication: secretsmanager.SecretRotationApplication.POSTGRES_ROTATION_MULTI_USER, defaultPort: 5432, engineVersion: version ? { fullVersion: version.auroraPostgresFullVersion, majorVersion: version.auroraPostgresMajorVersion, } : undefined, features: version ? { s3Import: version._features.s3Import ? AuroraPostgresClusterEngine.S3_IMPORT_FEATURE_NAME : undefined, s3Export: version._features.s3Export ? AuroraPostgresClusterEngine.S3_EXPORT_FEATURE_NAME : undefined, } : { s3Import: AuroraPostgresClusterEngine.S3_IMPORT_FEATURE_NAME, s3Export: AuroraPostgresClusterEngine.S3_EXPORT_FEATURE_NAME, }, }); } public bindToCluster(scope: Construct, options: ClusterEngineBindOptions): ClusterEngineConfig { const config = super.bindToCluster(scope, options); // skip validation for unversioned as it might be supported/unsupported. we cannot reliably tell at compile-time if (this.engineVersion?.fullVersion) { if (options.s3ImportRole && !(config.features?.s3Import)) { throw new Error(`s3Import is not supported for Postgres version: ${this.engineVersion.fullVersion}. Use a version that supports the s3Import feature.`); } if (options.s3ExportRole && !(config.features?.s3Export)) { throw new Error(`s3Export is not supported for Postgres version: ${this.engineVersion.fullVersion}. Use a version that supports the s3Export feature.`); } } return config; } protected defaultParameterGroup(scope: Construct): IParameterGroup | undefined { if (!this.parameterGroupFamily) { throw new Error('Could not create a new ParameterGroup for an unversioned aurora-postgresql cluster engine. ' + 'Please either use a versioned engine, or pass an explicit ParameterGroup when creating the cluster'); } return ParameterGroup.fromParameterGroupName(scope, 'AuroraPostgreSqlDatabaseClusterEngineDefaultParameterGroup', `default.${this.parameterGroupFamily}`); } } /** * A database cluster engine. Provides mapping to the serverless application * used for secret rotation. */ export class DatabaseClusterEngine { /** * The unversioned 'aurora' cluster engine. * * **Note**: we do not recommend using unversioned engines for non-serverless Clusters, * as that can pose an availability risk. * We recommend using versioned engines created using the {@link aurora()} method */ public static readonly AURORA: IClusterEngine = new AuroraClusterEngine(); /** * The unversioned 'aurora-msql' cluster engine. * * **Note**: we do not recommend using unversioned engines for non-serverless Clusters, * as that can pose an availability risk. * We recommend using versioned engines created using the {@link auroraMysql()} method */ public static readonly AURORA_MYSQL: IClusterEngine = new AuroraMysqlClusterEngine(); /** * The unversioned 'aurora-postgresql' cluster engine. * * **Note**: we do not recommend using unversioned engines for non-serverless Clusters, * as that can pose an availability risk. * We recommend using versioned engines created using the {@link auroraPostgres()} method */ public static readonly AURORA_POSTGRESQL: IClusterEngine = new AuroraPostgresClusterEngine(); /** Creates a new plain Aurora database cluster engine. */ public static aurora(props: AuroraClusterEngineProps): IClusterEngine { return new AuroraClusterEngine(props.version); } /** Creates a new Aurora MySQL database cluster engine. */ public static auroraMysql(props: AuroraMysqlClusterEngineProps): IClusterEngine { return new AuroraMysqlClusterEngine(props.version); } /** Creates a new Aurora PostgreSQL database cluster engine. */ public static auroraPostgres(props: AuroraPostgresClusterEngineProps): IClusterEngine { return new AuroraPostgresClusterEngine(props.version); } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class Greengrass extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: Greengrass.Types.ClientConfiguration) config: Config & Greengrass.Types.ClientConfiguration; /** * Associates a role with a group. Your Greengrass core will use the role to access AWS cloud services. The role's permissions should allow Greengrass core Lambda functions to perform actions against the cloud. */ associateRoleToGroup(params: Greengrass.Types.AssociateRoleToGroupRequest, callback?: (err: AWSError, data: Greengrass.Types.AssociateRoleToGroupResponse) => void): Request<Greengrass.Types.AssociateRoleToGroupResponse, AWSError>; /** * Associates a role with a group. Your Greengrass core will use the role to access AWS cloud services. The role's permissions should allow Greengrass core Lambda functions to perform actions against the cloud. */ associateRoleToGroup(callback?: (err: AWSError, data: Greengrass.Types.AssociateRoleToGroupResponse) => void): Request<Greengrass.Types.AssociateRoleToGroupResponse, AWSError>; /** * Associates a role with your account. AWS IoT Greengrass will use the role to access your Lambda functions and AWS IoT resources. This is necessary for deployments to succeed. The role must have at least minimum permissions in the policy ''AWSGreengrassResourceAccessRolePolicy''. */ associateServiceRoleToAccount(params: Greengrass.Types.AssociateServiceRoleToAccountRequest, callback?: (err: AWSError, data: Greengrass.Types.AssociateServiceRoleToAccountResponse) => void): Request<Greengrass.Types.AssociateServiceRoleToAccountResponse, AWSError>; /** * Associates a role with your account. AWS IoT Greengrass will use the role to access your Lambda functions and AWS IoT resources. This is necessary for deployments to succeed. The role must have at least minimum permissions in the policy ''AWSGreengrassResourceAccessRolePolicy''. */ associateServiceRoleToAccount(callback?: (err: AWSError, data: Greengrass.Types.AssociateServiceRoleToAccountResponse) => void): Request<Greengrass.Types.AssociateServiceRoleToAccountResponse, AWSError>; /** * Creates a connector definition. You may provide the initial version of the connector definition now or use ''CreateConnectorDefinitionVersion'' at a later time. */ createConnectorDefinition(params: Greengrass.Types.CreateConnectorDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateConnectorDefinitionResponse) => void): Request<Greengrass.Types.CreateConnectorDefinitionResponse, AWSError>; /** * Creates a connector definition. You may provide the initial version of the connector definition now or use ''CreateConnectorDefinitionVersion'' at a later time. */ createConnectorDefinition(callback?: (err: AWSError, data: Greengrass.Types.CreateConnectorDefinitionResponse) => void): Request<Greengrass.Types.CreateConnectorDefinitionResponse, AWSError>; /** * Creates a version of a connector definition which has already been defined. */ createConnectorDefinitionVersion(params: Greengrass.Types.CreateConnectorDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateConnectorDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateConnectorDefinitionVersionResponse, AWSError>; /** * Creates a version of a connector definition which has already been defined. */ createConnectorDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.CreateConnectorDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateConnectorDefinitionVersionResponse, AWSError>; /** * Creates a core definition. You may provide the initial version of the core definition now or use ''CreateCoreDefinitionVersion'' at a later time. Greengrass groups must each contain exactly one Greengrass core. */ createCoreDefinition(params: Greengrass.Types.CreateCoreDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateCoreDefinitionResponse) => void): Request<Greengrass.Types.CreateCoreDefinitionResponse, AWSError>; /** * Creates a core definition. You may provide the initial version of the core definition now or use ''CreateCoreDefinitionVersion'' at a later time. Greengrass groups must each contain exactly one Greengrass core. */ createCoreDefinition(callback?: (err: AWSError, data: Greengrass.Types.CreateCoreDefinitionResponse) => void): Request<Greengrass.Types.CreateCoreDefinitionResponse, AWSError>; /** * Creates a version of a core definition that has already been defined. Greengrass groups must each contain exactly one Greengrass core. */ createCoreDefinitionVersion(params: Greengrass.Types.CreateCoreDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateCoreDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateCoreDefinitionVersionResponse, AWSError>; /** * Creates a version of a core definition that has already been defined. Greengrass groups must each contain exactly one Greengrass core. */ createCoreDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.CreateCoreDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateCoreDefinitionVersionResponse, AWSError>; /** * Creates a deployment. ''CreateDeployment'' requests are idempotent with respect to the ''X-Amzn-Client-Token'' token and the request parameters. */ createDeployment(params: Greengrass.Types.CreateDeploymentRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateDeploymentResponse) => void): Request<Greengrass.Types.CreateDeploymentResponse, AWSError>; /** * Creates a deployment. ''CreateDeployment'' requests are idempotent with respect to the ''X-Amzn-Client-Token'' token and the request parameters. */ createDeployment(callback?: (err: AWSError, data: Greengrass.Types.CreateDeploymentResponse) => void): Request<Greengrass.Types.CreateDeploymentResponse, AWSError>; /** * Creates a device definition. You may provide the initial version of the device definition now or use ''CreateDeviceDefinitionVersion'' at a later time. */ createDeviceDefinition(params: Greengrass.Types.CreateDeviceDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateDeviceDefinitionResponse) => void): Request<Greengrass.Types.CreateDeviceDefinitionResponse, AWSError>; /** * Creates a device definition. You may provide the initial version of the device definition now or use ''CreateDeviceDefinitionVersion'' at a later time. */ createDeviceDefinition(callback?: (err: AWSError, data: Greengrass.Types.CreateDeviceDefinitionResponse) => void): Request<Greengrass.Types.CreateDeviceDefinitionResponse, AWSError>; /** * Creates a version of a device definition that has already been defined. */ createDeviceDefinitionVersion(params: Greengrass.Types.CreateDeviceDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateDeviceDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateDeviceDefinitionVersionResponse, AWSError>; /** * Creates a version of a device definition that has already been defined. */ createDeviceDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.CreateDeviceDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateDeviceDefinitionVersionResponse, AWSError>; /** * Creates a Lambda function definition which contains a list of Lambda functions and their configurations to be used in a group. You can create an initial version of the definition by providing a list of Lambda functions and their configurations now, or use ''CreateFunctionDefinitionVersion'' later. */ createFunctionDefinition(params: Greengrass.Types.CreateFunctionDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateFunctionDefinitionResponse) => void): Request<Greengrass.Types.CreateFunctionDefinitionResponse, AWSError>; /** * Creates a Lambda function definition which contains a list of Lambda functions and their configurations to be used in a group. You can create an initial version of the definition by providing a list of Lambda functions and their configurations now, or use ''CreateFunctionDefinitionVersion'' later. */ createFunctionDefinition(callback?: (err: AWSError, data: Greengrass.Types.CreateFunctionDefinitionResponse) => void): Request<Greengrass.Types.CreateFunctionDefinitionResponse, AWSError>; /** * Creates a version of a Lambda function definition that has already been defined. */ createFunctionDefinitionVersion(params: Greengrass.Types.CreateFunctionDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateFunctionDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateFunctionDefinitionVersionResponse, AWSError>; /** * Creates a version of a Lambda function definition that has already been defined. */ createFunctionDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.CreateFunctionDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateFunctionDefinitionVersionResponse, AWSError>; /** * Creates a group. You may provide the initial version of the group or use ''CreateGroupVersion'' at a later time. Tip: You can use the ''gg_group_setup'' package (https://github.com/awslabs/aws-greengrass-group-setup) as a library or command-line application to create and deploy Greengrass groups. */ createGroup(params: Greengrass.Types.CreateGroupRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateGroupResponse) => void): Request<Greengrass.Types.CreateGroupResponse, AWSError>; /** * Creates a group. You may provide the initial version of the group or use ''CreateGroupVersion'' at a later time. Tip: You can use the ''gg_group_setup'' package (https://github.com/awslabs/aws-greengrass-group-setup) as a library or command-line application to create and deploy Greengrass groups. */ createGroup(callback?: (err: AWSError, data: Greengrass.Types.CreateGroupResponse) => void): Request<Greengrass.Types.CreateGroupResponse, AWSError>; /** * Creates a CA for the group. If a CA already exists, it will rotate the existing CA. */ createGroupCertificateAuthority(params: Greengrass.Types.CreateGroupCertificateAuthorityRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateGroupCertificateAuthorityResponse) => void): Request<Greengrass.Types.CreateGroupCertificateAuthorityResponse, AWSError>; /** * Creates a CA for the group. If a CA already exists, it will rotate the existing CA. */ createGroupCertificateAuthority(callback?: (err: AWSError, data: Greengrass.Types.CreateGroupCertificateAuthorityResponse) => void): Request<Greengrass.Types.CreateGroupCertificateAuthorityResponse, AWSError>; /** * Creates a version of a group which has already been defined. */ createGroupVersion(params: Greengrass.Types.CreateGroupVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateGroupVersionResponse) => void): Request<Greengrass.Types.CreateGroupVersionResponse, AWSError>; /** * Creates a version of a group which has already been defined. */ createGroupVersion(callback?: (err: AWSError, data: Greengrass.Types.CreateGroupVersionResponse) => void): Request<Greengrass.Types.CreateGroupVersionResponse, AWSError>; /** * Creates a logger definition. You may provide the initial version of the logger definition now or use ''CreateLoggerDefinitionVersion'' at a later time. */ createLoggerDefinition(params: Greengrass.Types.CreateLoggerDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateLoggerDefinitionResponse) => void): Request<Greengrass.Types.CreateLoggerDefinitionResponse, AWSError>; /** * Creates a logger definition. You may provide the initial version of the logger definition now or use ''CreateLoggerDefinitionVersion'' at a later time. */ createLoggerDefinition(callback?: (err: AWSError, data: Greengrass.Types.CreateLoggerDefinitionResponse) => void): Request<Greengrass.Types.CreateLoggerDefinitionResponse, AWSError>; /** * Creates a version of a logger definition that has already been defined. */ createLoggerDefinitionVersion(params: Greengrass.Types.CreateLoggerDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateLoggerDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateLoggerDefinitionVersionResponse, AWSError>; /** * Creates a version of a logger definition that has already been defined. */ createLoggerDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.CreateLoggerDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateLoggerDefinitionVersionResponse, AWSError>; /** * Creates a resource definition which contains a list of resources to be used in a group. You can create an initial version of the definition by providing a list of resources now, or use ''CreateResourceDefinitionVersion'' later. */ createResourceDefinition(params: Greengrass.Types.CreateResourceDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateResourceDefinitionResponse) => void): Request<Greengrass.Types.CreateResourceDefinitionResponse, AWSError>; /** * Creates a resource definition which contains a list of resources to be used in a group. You can create an initial version of the definition by providing a list of resources now, or use ''CreateResourceDefinitionVersion'' later. */ createResourceDefinition(callback?: (err: AWSError, data: Greengrass.Types.CreateResourceDefinitionResponse) => void): Request<Greengrass.Types.CreateResourceDefinitionResponse, AWSError>; /** * Creates a version of a resource definition that has already been defined. */ createResourceDefinitionVersion(params: Greengrass.Types.CreateResourceDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateResourceDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateResourceDefinitionVersionResponse, AWSError>; /** * Creates a version of a resource definition that has already been defined. */ createResourceDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.CreateResourceDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateResourceDefinitionVersionResponse, AWSError>; /** * Creates a software update for a core or group of cores (specified as an IoT thing group.) Use this to update the OTA Agent as well as the Greengrass core software. It makes use of the IoT Jobs feature which provides additional commands to manage a Greengrass core software update job. */ createSoftwareUpdateJob(params: Greengrass.Types.CreateSoftwareUpdateJobRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateSoftwareUpdateJobResponse) => void): Request<Greengrass.Types.CreateSoftwareUpdateJobResponse, AWSError>; /** * Creates a software update for a core or group of cores (specified as an IoT thing group.) Use this to update the OTA Agent as well as the Greengrass core software. It makes use of the IoT Jobs feature which provides additional commands to manage a Greengrass core software update job. */ createSoftwareUpdateJob(callback?: (err: AWSError, data: Greengrass.Types.CreateSoftwareUpdateJobResponse) => void): Request<Greengrass.Types.CreateSoftwareUpdateJobResponse, AWSError>; /** * Creates a subscription definition. You may provide the initial version of the subscription definition now or use ''CreateSubscriptionDefinitionVersion'' at a later time. */ createSubscriptionDefinition(params: Greengrass.Types.CreateSubscriptionDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateSubscriptionDefinitionResponse) => void): Request<Greengrass.Types.CreateSubscriptionDefinitionResponse, AWSError>; /** * Creates a subscription definition. You may provide the initial version of the subscription definition now or use ''CreateSubscriptionDefinitionVersion'' at a later time. */ createSubscriptionDefinition(callback?: (err: AWSError, data: Greengrass.Types.CreateSubscriptionDefinitionResponse) => void): Request<Greengrass.Types.CreateSubscriptionDefinitionResponse, AWSError>; /** * Creates a version of a subscription definition which has already been defined. */ createSubscriptionDefinitionVersion(params: Greengrass.Types.CreateSubscriptionDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.CreateSubscriptionDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateSubscriptionDefinitionVersionResponse, AWSError>; /** * Creates a version of a subscription definition which has already been defined. */ createSubscriptionDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.CreateSubscriptionDefinitionVersionResponse) => void): Request<Greengrass.Types.CreateSubscriptionDefinitionVersionResponse, AWSError>; /** * Deletes a connector definition. */ deleteConnectorDefinition(params: Greengrass.Types.DeleteConnectorDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.DeleteConnectorDefinitionResponse) => void): Request<Greengrass.Types.DeleteConnectorDefinitionResponse, AWSError>; /** * Deletes a connector definition. */ deleteConnectorDefinition(callback?: (err: AWSError, data: Greengrass.Types.DeleteConnectorDefinitionResponse) => void): Request<Greengrass.Types.DeleteConnectorDefinitionResponse, AWSError>; /** * Deletes a core definition. */ deleteCoreDefinition(params: Greengrass.Types.DeleteCoreDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.DeleteCoreDefinitionResponse) => void): Request<Greengrass.Types.DeleteCoreDefinitionResponse, AWSError>; /** * Deletes a core definition. */ deleteCoreDefinition(callback?: (err: AWSError, data: Greengrass.Types.DeleteCoreDefinitionResponse) => void): Request<Greengrass.Types.DeleteCoreDefinitionResponse, AWSError>; /** * Deletes a device definition. */ deleteDeviceDefinition(params: Greengrass.Types.DeleteDeviceDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.DeleteDeviceDefinitionResponse) => void): Request<Greengrass.Types.DeleteDeviceDefinitionResponse, AWSError>; /** * Deletes a device definition. */ deleteDeviceDefinition(callback?: (err: AWSError, data: Greengrass.Types.DeleteDeviceDefinitionResponse) => void): Request<Greengrass.Types.DeleteDeviceDefinitionResponse, AWSError>; /** * Deletes a Lambda function definition. */ deleteFunctionDefinition(params: Greengrass.Types.DeleteFunctionDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.DeleteFunctionDefinitionResponse) => void): Request<Greengrass.Types.DeleteFunctionDefinitionResponse, AWSError>; /** * Deletes a Lambda function definition. */ deleteFunctionDefinition(callback?: (err: AWSError, data: Greengrass.Types.DeleteFunctionDefinitionResponse) => void): Request<Greengrass.Types.DeleteFunctionDefinitionResponse, AWSError>; /** * Deletes a group. */ deleteGroup(params: Greengrass.Types.DeleteGroupRequest, callback?: (err: AWSError, data: Greengrass.Types.DeleteGroupResponse) => void): Request<Greengrass.Types.DeleteGroupResponse, AWSError>; /** * Deletes a group. */ deleteGroup(callback?: (err: AWSError, data: Greengrass.Types.DeleteGroupResponse) => void): Request<Greengrass.Types.DeleteGroupResponse, AWSError>; /** * Deletes a logger definition. */ deleteLoggerDefinition(params: Greengrass.Types.DeleteLoggerDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.DeleteLoggerDefinitionResponse) => void): Request<Greengrass.Types.DeleteLoggerDefinitionResponse, AWSError>; /** * Deletes a logger definition. */ deleteLoggerDefinition(callback?: (err: AWSError, data: Greengrass.Types.DeleteLoggerDefinitionResponse) => void): Request<Greengrass.Types.DeleteLoggerDefinitionResponse, AWSError>; /** * Deletes a resource definition. */ deleteResourceDefinition(params: Greengrass.Types.DeleteResourceDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.DeleteResourceDefinitionResponse) => void): Request<Greengrass.Types.DeleteResourceDefinitionResponse, AWSError>; /** * Deletes a resource definition. */ deleteResourceDefinition(callback?: (err: AWSError, data: Greengrass.Types.DeleteResourceDefinitionResponse) => void): Request<Greengrass.Types.DeleteResourceDefinitionResponse, AWSError>; /** * Deletes a subscription definition. */ deleteSubscriptionDefinition(params: Greengrass.Types.DeleteSubscriptionDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.DeleteSubscriptionDefinitionResponse) => void): Request<Greengrass.Types.DeleteSubscriptionDefinitionResponse, AWSError>; /** * Deletes a subscription definition. */ deleteSubscriptionDefinition(callback?: (err: AWSError, data: Greengrass.Types.DeleteSubscriptionDefinitionResponse) => void): Request<Greengrass.Types.DeleteSubscriptionDefinitionResponse, AWSError>; /** * Disassociates the role from a group. */ disassociateRoleFromGroup(params: Greengrass.Types.DisassociateRoleFromGroupRequest, callback?: (err: AWSError, data: Greengrass.Types.DisassociateRoleFromGroupResponse) => void): Request<Greengrass.Types.DisassociateRoleFromGroupResponse, AWSError>; /** * Disassociates the role from a group. */ disassociateRoleFromGroup(callback?: (err: AWSError, data: Greengrass.Types.DisassociateRoleFromGroupResponse) => void): Request<Greengrass.Types.DisassociateRoleFromGroupResponse, AWSError>; /** * Disassociates the service role from your account. Without a service role, deployments will not work. */ disassociateServiceRoleFromAccount(params: Greengrass.Types.DisassociateServiceRoleFromAccountRequest, callback?: (err: AWSError, data: Greengrass.Types.DisassociateServiceRoleFromAccountResponse) => void): Request<Greengrass.Types.DisassociateServiceRoleFromAccountResponse, AWSError>; /** * Disassociates the service role from your account. Without a service role, deployments will not work. */ disassociateServiceRoleFromAccount(callback?: (err: AWSError, data: Greengrass.Types.DisassociateServiceRoleFromAccountResponse) => void): Request<Greengrass.Types.DisassociateServiceRoleFromAccountResponse, AWSError>; /** * Retrieves the role associated with a particular group. */ getAssociatedRole(params: Greengrass.Types.GetAssociatedRoleRequest, callback?: (err: AWSError, data: Greengrass.Types.GetAssociatedRoleResponse) => void): Request<Greengrass.Types.GetAssociatedRoleResponse, AWSError>; /** * Retrieves the role associated with a particular group. */ getAssociatedRole(callback?: (err: AWSError, data: Greengrass.Types.GetAssociatedRoleResponse) => void): Request<Greengrass.Types.GetAssociatedRoleResponse, AWSError>; /** * Returns the status of a bulk deployment. */ getBulkDeploymentStatus(params: Greengrass.Types.GetBulkDeploymentStatusRequest, callback?: (err: AWSError, data: Greengrass.Types.GetBulkDeploymentStatusResponse) => void): Request<Greengrass.Types.GetBulkDeploymentStatusResponse, AWSError>; /** * Returns the status of a bulk deployment. */ getBulkDeploymentStatus(callback?: (err: AWSError, data: Greengrass.Types.GetBulkDeploymentStatusResponse) => void): Request<Greengrass.Types.GetBulkDeploymentStatusResponse, AWSError>; /** * Retrieves the connectivity information for a core. */ getConnectivityInfo(params: Greengrass.Types.GetConnectivityInfoRequest, callback?: (err: AWSError, data: Greengrass.Types.GetConnectivityInfoResponse) => void): Request<Greengrass.Types.GetConnectivityInfoResponse, AWSError>; /** * Retrieves the connectivity information for a core. */ getConnectivityInfo(callback?: (err: AWSError, data: Greengrass.Types.GetConnectivityInfoResponse) => void): Request<Greengrass.Types.GetConnectivityInfoResponse, AWSError>; /** * Retrieves information about a connector definition. */ getConnectorDefinition(params: Greengrass.Types.GetConnectorDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetConnectorDefinitionResponse) => void): Request<Greengrass.Types.GetConnectorDefinitionResponse, AWSError>; /** * Retrieves information about a connector definition. */ getConnectorDefinition(callback?: (err: AWSError, data: Greengrass.Types.GetConnectorDefinitionResponse) => void): Request<Greengrass.Types.GetConnectorDefinitionResponse, AWSError>; /** * Retrieves information about a connector definition version, including the connectors that the version contains. Connectors are prebuilt modules that interact with local infrastructure, device protocols, AWS, and other cloud services. */ getConnectorDefinitionVersion(params: Greengrass.Types.GetConnectorDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetConnectorDefinitionVersionResponse) => void): Request<Greengrass.Types.GetConnectorDefinitionVersionResponse, AWSError>; /** * Retrieves information about a connector definition version, including the connectors that the version contains. Connectors are prebuilt modules that interact with local infrastructure, device protocols, AWS, and other cloud services. */ getConnectorDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.GetConnectorDefinitionVersionResponse) => void): Request<Greengrass.Types.GetConnectorDefinitionVersionResponse, AWSError>; /** * Retrieves information about a core definition version. */ getCoreDefinition(params: Greengrass.Types.GetCoreDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetCoreDefinitionResponse) => void): Request<Greengrass.Types.GetCoreDefinitionResponse, AWSError>; /** * Retrieves information about a core definition version. */ getCoreDefinition(callback?: (err: AWSError, data: Greengrass.Types.GetCoreDefinitionResponse) => void): Request<Greengrass.Types.GetCoreDefinitionResponse, AWSError>; /** * Retrieves information about a core definition version. */ getCoreDefinitionVersion(params: Greengrass.Types.GetCoreDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetCoreDefinitionVersionResponse) => void): Request<Greengrass.Types.GetCoreDefinitionVersionResponse, AWSError>; /** * Retrieves information about a core definition version. */ getCoreDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.GetCoreDefinitionVersionResponse) => void): Request<Greengrass.Types.GetCoreDefinitionVersionResponse, AWSError>; /** * Returns the status of a deployment. */ getDeploymentStatus(params: Greengrass.Types.GetDeploymentStatusRequest, callback?: (err: AWSError, data: Greengrass.Types.GetDeploymentStatusResponse) => void): Request<Greengrass.Types.GetDeploymentStatusResponse, AWSError>; /** * Returns the status of a deployment. */ getDeploymentStatus(callback?: (err: AWSError, data: Greengrass.Types.GetDeploymentStatusResponse) => void): Request<Greengrass.Types.GetDeploymentStatusResponse, AWSError>; /** * Retrieves information about a device definition. */ getDeviceDefinition(params: Greengrass.Types.GetDeviceDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetDeviceDefinitionResponse) => void): Request<Greengrass.Types.GetDeviceDefinitionResponse, AWSError>; /** * Retrieves information about a device definition. */ getDeviceDefinition(callback?: (err: AWSError, data: Greengrass.Types.GetDeviceDefinitionResponse) => void): Request<Greengrass.Types.GetDeviceDefinitionResponse, AWSError>; /** * Retrieves information about a device definition version. */ getDeviceDefinitionVersion(params: Greengrass.Types.GetDeviceDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetDeviceDefinitionVersionResponse) => void): Request<Greengrass.Types.GetDeviceDefinitionVersionResponse, AWSError>; /** * Retrieves information about a device definition version. */ getDeviceDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.GetDeviceDefinitionVersionResponse) => void): Request<Greengrass.Types.GetDeviceDefinitionVersionResponse, AWSError>; /** * Retrieves information about a Lambda function definition, including its creation time and latest version. */ getFunctionDefinition(params: Greengrass.Types.GetFunctionDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetFunctionDefinitionResponse) => void): Request<Greengrass.Types.GetFunctionDefinitionResponse, AWSError>; /** * Retrieves information about a Lambda function definition, including its creation time and latest version. */ getFunctionDefinition(callback?: (err: AWSError, data: Greengrass.Types.GetFunctionDefinitionResponse) => void): Request<Greengrass.Types.GetFunctionDefinitionResponse, AWSError>; /** * Retrieves information about a Lambda function definition version, including which Lambda functions are included in the version and their configurations. */ getFunctionDefinitionVersion(params: Greengrass.Types.GetFunctionDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetFunctionDefinitionVersionResponse) => void): Request<Greengrass.Types.GetFunctionDefinitionVersionResponse, AWSError>; /** * Retrieves information about a Lambda function definition version, including which Lambda functions are included in the version and their configurations. */ getFunctionDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.GetFunctionDefinitionVersionResponse) => void): Request<Greengrass.Types.GetFunctionDefinitionVersionResponse, AWSError>; /** * Retrieves information about a group. */ getGroup(params: Greengrass.Types.GetGroupRequest, callback?: (err: AWSError, data: Greengrass.Types.GetGroupResponse) => void): Request<Greengrass.Types.GetGroupResponse, AWSError>; /** * Retrieves information about a group. */ getGroup(callback?: (err: AWSError, data: Greengrass.Types.GetGroupResponse) => void): Request<Greengrass.Types.GetGroupResponse, AWSError>; /** * Retreives the CA associated with a group. Returns the public key of the CA. */ getGroupCertificateAuthority(params: Greengrass.Types.GetGroupCertificateAuthorityRequest, callback?: (err: AWSError, data: Greengrass.Types.GetGroupCertificateAuthorityResponse) => void): Request<Greengrass.Types.GetGroupCertificateAuthorityResponse, AWSError>; /** * Retreives the CA associated with a group. Returns the public key of the CA. */ getGroupCertificateAuthority(callback?: (err: AWSError, data: Greengrass.Types.GetGroupCertificateAuthorityResponse) => void): Request<Greengrass.Types.GetGroupCertificateAuthorityResponse, AWSError>; /** * Retrieves the current configuration for the CA used by the group. */ getGroupCertificateConfiguration(params: Greengrass.Types.GetGroupCertificateConfigurationRequest, callback?: (err: AWSError, data: Greengrass.Types.GetGroupCertificateConfigurationResponse) => void): Request<Greengrass.Types.GetGroupCertificateConfigurationResponse, AWSError>; /** * Retrieves the current configuration for the CA used by the group. */ getGroupCertificateConfiguration(callback?: (err: AWSError, data: Greengrass.Types.GetGroupCertificateConfigurationResponse) => void): Request<Greengrass.Types.GetGroupCertificateConfigurationResponse, AWSError>; /** * Retrieves information about a group version. */ getGroupVersion(params: Greengrass.Types.GetGroupVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetGroupVersionResponse) => void): Request<Greengrass.Types.GetGroupVersionResponse, AWSError>; /** * Retrieves information about a group version. */ getGroupVersion(callback?: (err: AWSError, data: Greengrass.Types.GetGroupVersionResponse) => void): Request<Greengrass.Types.GetGroupVersionResponse, AWSError>; /** * Retrieves information about a logger definition. */ getLoggerDefinition(params: Greengrass.Types.GetLoggerDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetLoggerDefinitionResponse) => void): Request<Greengrass.Types.GetLoggerDefinitionResponse, AWSError>; /** * Retrieves information about a logger definition. */ getLoggerDefinition(callback?: (err: AWSError, data: Greengrass.Types.GetLoggerDefinitionResponse) => void): Request<Greengrass.Types.GetLoggerDefinitionResponse, AWSError>; /** * Retrieves information about a logger definition version. */ getLoggerDefinitionVersion(params: Greengrass.Types.GetLoggerDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetLoggerDefinitionVersionResponse) => void): Request<Greengrass.Types.GetLoggerDefinitionVersionResponse, AWSError>; /** * Retrieves information about a logger definition version. */ getLoggerDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.GetLoggerDefinitionVersionResponse) => void): Request<Greengrass.Types.GetLoggerDefinitionVersionResponse, AWSError>; /** * Retrieves information about a resource definition, including its creation time and latest version. */ getResourceDefinition(params: Greengrass.Types.GetResourceDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetResourceDefinitionResponse) => void): Request<Greengrass.Types.GetResourceDefinitionResponse, AWSError>; /** * Retrieves information about a resource definition, including its creation time and latest version. */ getResourceDefinition(callback?: (err: AWSError, data: Greengrass.Types.GetResourceDefinitionResponse) => void): Request<Greengrass.Types.GetResourceDefinitionResponse, AWSError>; /** * Retrieves information about a resource definition version, including which resources are included in the version. */ getResourceDefinitionVersion(params: Greengrass.Types.GetResourceDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetResourceDefinitionVersionResponse) => void): Request<Greengrass.Types.GetResourceDefinitionVersionResponse, AWSError>; /** * Retrieves information about a resource definition version, including which resources are included in the version. */ getResourceDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.GetResourceDefinitionVersionResponse) => void): Request<Greengrass.Types.GetResourceDefinitionVersionResponse, AWSError>; /** * Retrieves the service role that is attached to your account. */ getServiceRoleForAccount(params: Greengrass.Types.GetServiceRoleForAccountRequest, callback?: (err: AWSError, data: Greengrass.Types.GetServiceRoleForAccountResponse) => void): Request<Greengrass.Types.GetServiceRoleForAccountResponse, AWSError>; /** * Retrieves the service role that is attached to your account. */ getServiceRoleForAccount(callback?: (err: AWSError, data: Greengrass.Types.GetServiceRoleForAccountResponse) => void): Request<Greengrass.Types.GetServiceRoleForAccountResponse, AWSError>; /** * Retrieves information about a subscription definition. */ getSubscriptionDefinition(params: Greengrass.Types.GetSubscriptionDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetSubscriptionDefinitionResponse) => void): Request<Greengrass.Types.GetSubscriptionDefinitionResponse, AWSError>; /** * Retrieves information about a subscription definition. */ getSubscriptionDefinition(callback?: (err: AWSError, data: Greengrass.Types.GetSubscriptionDefinitionResponse) => void): Request<Greengrass.Types.GetSubscriptionDefinitionResponse, AWSError>; /** * Retrieves information about a subscription definition version. */ getSubscriptionDefinitionVersion(params: Greengrass.Types.GetSubscriptionDefinitionVersionRequest, callback?: (err: AWSError, data: Greengrass.Types.GetSubscriptionDefinitionVersionResponse) => void): Request<Greengrass.Types.GetSubscriptionDefinitionVersionResponse, AWSError>; /** * Retrieves information about a subscription definition version. */ getSubscriptionDefinitionVersion(callback?: (err: AWSError, data: Greengrass.Types.GetSubscriptionDefinitionVersionResponse) => void): Request<Greengrass.Types.GetSubscriptionDefinitionVersionResponse, AWSError>; /** * Get the runtime configuration of a thing. */ getThingRuntimeConfiguration(params: Greengrass.Types.GetThingRuntimeConfigurationRequest, callback?: (err: AWSError, data: Greengrass.Types.GetThingRuntimeConfigurationResponse) => void): Request<Greengrass.Types.GetThingRuntimeConfigurationResponse, AWSError>; /** * Get the runtime configuration of a thing. */ getThingRuntimeConfiguration(callback?: (err: AWSError, data: Greengrass.Types.GetThingRuntimeConfigurationResponse) => void): Request<Greengrass.Types.GetThingRuntimeConfigurationResponse, AWSError>; /** * Gets a paginated list of the deployments that have been started in a bulk deployment operation, and their current deployment status. */ listBulkDeploymentDetailedReports(params: Greengrass.Types.ListBulkDeploymentDetailedReportsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListBulkDeploymentDetailedReportsResponse) => void): Request<Greengrass.Types.ListBulkDeploymentDetailedReportsResponse, AWSError>; /** * Gets a paginated list of the deployments that have been started in a bulk deployment operation, and their current deployment status. */ listBulkDeploymentDetailedReports(callback?: (err: AWSError, data: Greengrass.Types.ListBulkDeploymentDetailedReportsResponse) => void): Request<Greengrass.Types.ListBulkDeploymentDetailedReportsResponse, AWSError>; /** * Returns a list of bulk deployments. */ listBulkDeployments(params: Greengrass.Types.ListBulkDeploymentsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListBulkDeploymentsResponse) => void): Request<Greengrass.Types.ListBulkDeploymentsResponse, AWSError>; /** * Returns a list of bulk deployments. */ listBulkDeployments(callback?: (err: AWSError, data: Greengrass.Types.ListBulkDeploymentsResponse) => void): Request<Greengrass.Types.ListBulkDeploymentsResponse, AWSError>; /** * Lists the versions of a connector definition, which are containers for connectors. Connectors run on the Greengrass core and contain built-in integration with local infrastructure, device protocols, AWS, and other cloud services. */ listConnectorDefinitionVersions(params: Greengrass.Types.ListConnectorDefinitionVersionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListConnectorDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListConnectorDefinitionVersionsResponse, AWSError>; /** * Lists the versions of a connector definition, which are containers for connectors. Connectors run on the Greengrass core and contain built-in integration with local infrastructure, device protocols, AWS, and other cloud services. */ listConnectorDefinitionVersions(callback?: (err: AWSError, data: Greengrass.Types.ListConnectorDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListConnectorDefinitionVersionsResponse, AWSError>; /** * Retrieves a list of connector definitions. */ listConnectorDefinitions(params: Greengrass.Types.ListConnectorDefinitionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListConnectorDefinitionsResponse) => void): Request<Greengrass.Types.ListConnectorDefinitionsResponse, AWSError>; /** * Retrieves a list of connector definitions. */ listConnectorDefinitions(callback?: (err: AWSError, data: Greengrass.Types.ListConnectorDefinitionsResponse) => void): Request<Greengrass.Types.ListConnectorDefinitionsResponse, AWSError>; /** * Lists the versions of a core definition. */ listCoreDefinitionVersions(params: Greengrass.Types.ListCoreDefinitionVersionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListCoreDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListCoreDefinitionVersionsResponse, AWSError>; /** * Lists the versions of a core definition. */ listCoreDefinitionVersions(callback?: (err: AWSError, data: Greengrass.Types.ListCoreDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListCoreDefinitionVersionsResponse, AWSError>; /** * Retrieves a list of core definitions. */ listCoreDefinitions(params: Greengrass.Types.ListCoreDefinitionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListCoreDefinitionsResponse) => void): Request<Greengrass.Types.ListCoreDefinitionsResponse, AWSError>; /** * Retrieves a list of core definitions. */ listCoreDefinitions(callback?: (err: AWSError, data: Greengrass.Types.ListCoreDefinitionsResponse) => void): Request<Greengrass.Types.ListCoreDefinitionsResponse, AWSError>; /** * Returns a history of deployments for the group. */ listDeployments(params: Greengrass.Types.ListDeploymentsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListDeploymentsResponse) => void): Request<Greengrass.Types.ListDeploymentsResponse, AWSError>; /** * Returns a history of deployments for the group. */ listDeployments(callback?: (err: AWSError, data: Greengrass.Types.ListDeploymentsResponse) => void): Request<Greengrass.Types.ListDeploymentsResponse, AWSError>; /** * Lists the versions of a device definition. */ listDeviceDefinitionVersions(params: Greengrass.Types.ListDeviceDefinitionVersionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListDeviceDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListDeviceDefinitionVersionsResponse, AWSError>; /** * Lists the versions of a device definition. */ listDeviceDefinitionVersions(callback?: (err: AWSError, data: Greengrass.Types.ListDeviceDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListDeviceDefinitionVersionsResponse, AWSError>; /** * Retrieves a list of device definitions. */ listDeviceDefinitions(params: Greengrass.Types.ListDeviceDefinitionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListDeviceDefinitionsResponse) => void): Request<Greengrass.Types.ListDeviceDefinitionsResponse, AWSError>; /** * Retrieves a list of device definitions. */ listDeviceDefinitions(callback?: (err: AWSError, data: Greengrass.Types.ListDeviceDefinitionsResponse) => void): Request<Greengrass.Types.ListDeviceDefinitionsResponse, AWSError>; /** * Lists the versions of a Lambda function definition. */ listFunctionDefinitionVersions(params: Greengrass.Types.ListFunctionDefinitionVersionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListFunctionDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListFunctionDefinitionVersionsResponse, AWSError>; /** * Lists the versions of a Lambda function definition. */ listFunctionDefinitionVersions(callback?: (err: AWSError, data: Greengrass.Types.ListFunctionDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListFunctionDefinitionVersionsResponse, AWSError>; /** * Retrieves a list of Lambda function definitions. */ listFunctionDefinitions(params: Greengrass.Types.ListFunctionDefinitionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListFunctionDefinitionsResponse) => void): Request<Greengrass.Types.ListFunctionDefinitionsResponse, AWSError>; /** * Retrieves a list of Lambda function definitions. */ listFunctionDefinitions(callback?: (err: AWSError, data: Greengrass.Types.ListFunctionDefinitionsResponse) => void): Request<Greengrass.Types.ListFunctionDefinitionsResponse, AWSError>; /** * Retrieves the current CAs for a group. */ listGroupCertificateAuthorities(params: Greengrass.Types.ListGroupCertificateAuthoritiesRequest, callback?: (err: AWSError, data: Greengrass.Types.ListGroupCertificateAuthoritiesResponse) => void): Request<Greengrass.Types.ListGroupCertificateAuthoritiesResponse, AWSError>; /** * Retrieves the current CAs for a group. */ listGroupCertificateAuthorities(callback?: (err: AWSError, data: Greengrass.Types.ListGroupCertificateAuthoritiesResponse) => void): Request<Greengrass.Types.ListGroupCertificateAuthoritiesResponse, AWSError>; /** * Lists the versions of a group. */ listGroupVersions(params: Greengrass.Types.ListGroupVersionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListGroupVersionsResponse) => void): Request<Greengrass.Types.ListGroupVersionsResponse, AWSError>; /** * Lists the versions of a group. */ listGroupVersions(callback?: (err: AWSError, data: Greengrass.Types.ListGroupVersionsResponse) => void): Request<Greengrass.Types.ListGroupVersionsResponse, AWSError>; /** * Retrieves a list of groups. */ listGroups(params: Greengrass.Types.ListGroupsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListGroupsResponse) => void): Request<Greengrass.Types.ListGroupsResponse, AWSError>; /** * Retrieves a list of groups. */ listGroups(callback?: (err: AWSError, data: Greengrass.Types.ListGroupsResponse) => void): Request<Greengrass.Types.ListGroupsResponse, AWSError>; /** * Lists the versions of a logger definition. */ listLoggerDefinitionVersions(params: Greengrass.Types.ListLoggerDefinitionVersionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListLoggerDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListLoggerDefinitionVersionsResponse, AWSError>; /** * Lists the versions of a logger definition. */ listLoggerDefinitionVersions(callback?: (err: AWSError, data: Greengrass.Types.ListLoggerDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListLoggerDefinitionVersionsResponse, AWSError>; /** * Retrieves a list of logger definitions. */ listLoggerDefinitions(params: Greengrass.Types.ListLoggerDefinitionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListLoggerDefinitionsResponse) => void): Request<Greengrass.Types.ListLoggerDefinitionsResponse, AWSError>; /** * Retrieves a list of logger definitions. */ listLoggerDefinitions(callback?: (err: AWSError, data: Greengrass.Types.ListLoggerDefinitionsResponse) => void): Request<Greengrass.Types.ListLoggerDefinitionsResponse, AWSError>; /** * Lists the versions of a resource definition. */ listResourceDefinitionVersions(params: Greengrass.Types.ListResourceDefinitionVersionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListResourceDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListResourceDefinitionVersionsResponse, AWSError>; /** * Lists the versions of a resource definition. */ listResourceDefinitionVersions(callback?: (err: AWSError, data: Greengrass.Types.ListResourceDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListResourceDefinitionVersionsResponse, AWSError>; /** * Retrieves a list of resource definitions. */ listResourceDefinitions(params: Greengrass.Types.ListResourceDefinitionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListResourceDefinitionsResponse) => void): Request<Greengrass.Types.ListResourceDefinitionsResponse, AWSError>; /** * Retrieves a list of resource definitions. */ listResourceDefinitions(callback?: (err: AWSError, data: Greengrass.Types.ListResourceDefinitionsResponse) => void): Request<Greengrass.Types.ListResourceDefinitionsResponse, AWSError>; /** * Lists the versions of a subscription definition. */ listSubscriptionDefinitionVersions(params: Greengrass.Types.ListSubscriptionDefinitionVersionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListSubscriptionDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListSubscriptionDefinitionVersionsResponse, AWSError>; /** * Lists the versions of a subscription definition. */ listSubscriptionDefinitionVersions(callback?: (err: AWSError, data: Greengrass.Types.ListSubscriptionDefinitionVersionsResponse) => void): Request<Greengrass.Types.ListSubscriptionDefinitionVersionsResponse, AWSError>; /** * Retrieves a list of subscription definitions. */ listSubscriptionDefinitions(params: Greengrass.Types.ListSubscriptionDefinitionsRequest, callback?: (err: AWSError, data: Greengrass.Types.ListSubscriptionDefinitionsResponse) => void): Request<Greengrass.Types.ListSubscriptionDefinitionsResponse, AWSError>; /** * Retrieves a list of subscription definitions. */ listSubscriptionDefinitions(callback?: (err: AWSError, data: Greengrass.Types.ListSubscriptionDefinitionsResponse) => void): Request<Greengrass.Types.ListSubscriptionDefinitionsResponse, AWSError>; /** * Retrieves a list of resource tags for a resource arn. */ listTagsForResource(params: Greengrass.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Greengrass.Types.ListTagsForResourceResponse) => void): Request<Greengrass.Types.ListTagsForResourceResponse, AWSError>; /** * Retrieves a list of resource tags for a resource arn. */ listTagsForResource(callback?: (err: AWSError, data: Greengrass.Types.ListTagsForResourceResponse) => void): Request<Greengrass.Types.ListTagsForResourceResponse, AWSError>; /** * Resets a group's deployments. */ resetDeployments(params: Greengrass.Types.ResetDeploymentsRequest, callback?: (err: AWSError, data: Greengrass.Types.ResetDeploymentsResponse) => void): Request<Greengrass.Types.ResetDeploymentsResponse, AWSError>; /** * Resets a group's deployments. */ resetDeployments(callback?: (err: AWSError, data: Greengrass.Types.ResetDeploymentsResponse) => void): Request<Greengrass.Types.ResetDeploymentsResponse, AWSError>; /** * Deploys multiple groups in one operation. This action starts the bulk deployment of a specified set of group versions. Each group version deployment will be triggered with an adaptive rate that has a fixed upper limit. We recommend that you include an ''X-Amzn-Client-Token'' token in every ''StartBulkDeployment'' request. These requests are idempotent with respect to the token and the request parameters. */ startBulkDeployment(params: Greengrass.Types.StartBulkDeploymentRequest, callback?: (err: AWSError, data: Greengrass.Types.StartBulkDeploymentResponse) => void): Request<Greengrass.Types.StartBulkDeploymentResponse, AWSError>; /** * Deploys multiple groups in one operation. This action starts the bulk deployment of a specified set of group versions. Each group version deployment will be triggered with an adaptive rate that has a fixed upper limit. We recommend that you include an ''X-Amzn-Client-Token'' token in every ''StartBulkDeployment'' request. These requests are idempotent with respect to the token and the request parameters. */ startBulkDeployment(callback?: (err: AWSError, data: Greengrass.Types.StartBulkDeploymentResponse) => void): Request<Greengrass.Types.StartBulkDeploymentResponse, AWSError>; /** * Stops the execution of a bulk deployment. This action returns a status of ''Stopping'' until the deployment is stopped. You cannot start a new bulk deployment while a previous deployment is in the ''Stopping'' state. This action doesn't rollback completed deployments or cancel pending deployments. */ stopBulkDeployment(params: Greengrass.Types.StopBulkDeploymentRequest, callback?: (err: AWSError, data: Greengrass.Types.StopBulkDeploymentResponse) => void): Request<Greengrass.Types.StopBulkDeploymentResponse, AWSError>; /** * Stops the execution of a bulk deployment. This action returns a status of ''Stopping'' until the deployment is stopped. You cannot start a new bulk deployment while a previous deployment is in the ''Stopping'' state. This action doesn't rollback completed deployments or cancel pending deployments. */ stopBulkDeployment(callback?: (err: AWSError, data: Greengrass.Types.StopBulkDeploymentResponse) => void): Request<Greengrass.Types.StopBulkDeploymentResponse, AWSError>; /** * Adds tags to a Greengrass resource. Valid resources are 'Group', 'ConnectorDefinition', 'CoreDefinition', 'DeviceDefinition', 'FunctionDefinition', 'LoggerDefinition', 'SubscriptionDefinition', 'ResourceDefinition', and 'BulkDeployment'. */ tagResource(params: Greengrass.Types.TagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Adds tags to a Greengrass resource. Valid resources are 'Group', 'ConnectorDefinition', 'CoreDefinition', 'DeviceDefinition', 'FunctionDefinition', 'LoggerDefinition', 'SubscriptionDefinition', 'ResourceDefinition', and 'BulkDeployment'. */ tagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Remove resource tags from a Greengrass Resource. */ untagResource(params: Greengrass.Types.UntagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Remove resource tags from a Greengrass Resource. */ untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the connectivity information for the core. Any devices that belong to the group which has this core will receive this information in order to find the location of the core and connect to it. */ updateConnectivityInfo(params: Greengrass.Types.UpdateConnectivityInfoRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateConnectivityInfoResponse) => void): Request<Greengrass.Types.UpdateConnectivityInfoResponse, AWSError>; /** * Updates the connectivity information for the core. Any devices that belong to the group which has this core will receive this information in order to find the location of the core and connect to it. */ updateConnectivityInfo(callback?: (err: AWSError, data: Greengrass.Types.UpdateConnectivityInfoResponse) => void): Request<Greengrass.Types.UpdateConnectivityInfoResponse, AWSError>; /** * Updates a connector definition. */ updateConnectorDefinition(params: Greengrass.Types.UpdateConnectorDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateConnectorDefinitionResponse) => void): Request<Greengrass.Types.UpdateConnectorDefinitionResponse, AWSError>; /** * Updates a connector definition. */ updateConnectorDefinition(callback?: (err: AWSError, data: Greengrass.Types.UpdateConnectorDefinitionResponse) => void): Request<Greengrass.Types.UpdateConnectorDefinitionResponse, AWSError>; /** * Updates a core definition. */ updateCoreDefinition(params: Greengrass.Types.UpdateCoreDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateCoreDefinitionResponse) => void): Request<Greengrass.Types.UpdateCoreDefinitionResponse, AWSError>; /** * Updates a core definition. */ updateCoreDefinition(callback?: (err: AWSError, data: Greengrass.Types.UpdateCoreDefinitionResponse) => void): Request<Greengrass.Types.UpdateCoreDefinitionResponse, AWSError>; /** * Updates a device definition. */ updateDeviceDefinition(params: Greengrass.Types.UpdateDeviceDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateDeviceDefinitionResponse) => void): Request<Greengrass.Types.UpdateDeviceDefinitionResponse, AWSError>; /** * Updates a device definition. */ updateDeviceDefinition(callback?: (err: AWSError, data: Greengrass.Types.UpdateDeviceDefinitionResponse) => void): Request<Greengrass.Types.UpdateDeviceDefinitionResponse, AWSError>; /** * Updates a Lambda function definition. */ updateFunctionDefinition(params: Greengrass.Types.UpdateFunctionDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateFunctionDefinitionResponse) => void): Request<Greengrass.Types.UpdateFunctionDefinitionResponse, AWSError>; /** * Updates a Lambda function definition. */ updateFunctionDefinition(callback?: (err: AWSError, data: Greengrass.Types.UpdateFunctionDefinitionResponse) => void): Request<Greengrass.Types.UpdateFunctionDefinitionResponse, AWSError>; /** * Updates a group. */ updateGroup(params: Greengrass.Types.UpdateGroupRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateGroupResponse) => void): Request<Greengrass.Types.UpdateGroupResponse, AWSError>; /** * Updates a group. */ updateGroup(callback?: (err: AWSError, data: Greengrass.Types.UpdateGroupResponse) => void): Request<Greengrass.Types.UpdateGroupResponse, AWSError>; /** * Updates the Certificate expiry time for a group. */ updateGroupCertificateConfiguration(params: Greengrass.Types.UpdateGroupCertificateConfigurationRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateGroupCertificateConfigurationResponse) => void): Request<Greengrass.Types.UpdateGroupCertificateConfigurationResponse, AWSError>; /** * Updates the Certificate expiry time for a group. */ updateGroupCertificateConfiguration(callback?: (err: AWSError, data: Greengrass.Types.UpdateGroupCertificateConfigurationResponse) => void): Request<Greengrass.Types.UpdateGroupCertificateConfigurationResponse, AWSError>; /** * Updates a logger definition. */ updateLoggerDefinition(params: Greengrass.Types.UpdateLoggerDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateLoggerDefinitionResponse) => void): Request<Greengrass.Types.UpdateLoggerDefinitionResponse, AWSError>; /** * Updates a logger definition. */ updateLoggerDefinition(callback?: (err: AWSError, data: Greengrass.Types.UpdateLoggerDefinitionResponse) => void): Request<Greengrass.Types.UpdateLoggerDefinitionResponse, AWSError>; /** * Updates a resource definition. */ updateResourceDefinition(params: Greengrass.Types.UpdateResourceDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateResourceDefinitionResponse) => void): Request<Greengrass.Types.UpdateResourceDefinitionResponse, AWSError>; /** * Updates a resource definition. */ updateResourceDefinition(callback?: (err: AWSError, data: Greengrass.Types.UpdateResourceDefinitionResponse) => void): Request<Greengrass.Types.UpdateResourceDefinitionResponse, AWSError>; /** * Updates a subscription definition. */ updateSubscriptionDefinition(params: Greengrass.Types.UpdateSubscriptionDefinitionRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateSubscriptionDefinitionResponse) => void): Request<Greengrass.Types.UpdateSubscriptionDefinitionResponse, AWSError>; /** * Updates a subscription definition. */ updateSubscriptionDefinition(callback?: (err: AWSError, data: Greengrass.Types.UpdateSubscriptionDefinitionResponse) => void): Request<Greengrass.Types.UpdateSubscriptionDefinitionResponse, AWSError>; /** * Updates the runtime configuration of a thing. */ updateThingRuntimeConfiguration(params: Greengrass.Types.UpdateThingRuntimeConfigurationRequest, callback?: (err: AWSError, data: Greengrass.Types.UpdateThingRuntimeConfigurationResponse) => void): Request<Greengrass.Types.UpdateThingRuntimeConfigurationResponse, AWSError>; /** * Updates the runtime configuration of a thing. */ updateThingRuntimeConfiguration(callback?: (err: AWSError, data: Greengrass.Types.UpdateThingRuntimeConfigurationResponse) => void): Request<Greengrass.Types.UpdateThingRuntimeConfigurationResponse, AWSError>; } declare namespace Greengrass { export interface AssociateRoleToGroupRequest { /** * The ID of the Greengrass group. */ GroupId: __string; /** * The ARN of the role you wish to associate with this group. The existence of the role is not validated. */ RoleArn: __string; } export interface AssociateRoleToGroupResponse { /** * The time, in milliseconds since the epoch, when the role ARN was associated with the group. */ AssociatedAt?: __string; } export interface AssociateServiceRoleToAccountRequest { /** * The ARN of the service role you wish to associate with your account. */ RoleArn: __string; } export interface AssociateServiceRoleToAccountResponse { /** * The time when the service role was associated with the account. */ AssociatedAt?: __string; } export interface BulkDeployment { /** * The ARN of the bulk deployment. */ BulkDeploymentArn?: __string; /** * The ID of the bulk deployment. */ BulkDeploymentId?: __string; /** * The time, in ISO format, when the deployment was created. */ CreatedAt?: __string; } export interface BulkDeploymentMetrics { /** * The total number of records that returned a non-retryable error. For example, this can occur if a group record from the input file uses an invalid format or specifies a nonexistent group version, or if the execution role doesn't grant permission to deploy a group or group version. */ InvalidInputRecords?: __integer; /** * The total number of group records from the input file that have been processed so far, or attempted. */ RecordsProcessed?: __integer; /** * The total number of deployment attempts that returned a retryable error. For example, a retry is triggered if the attempt to deploy a group returns a throttling error. ''StartBulkDeployment'' retries a group deployment up to five times. */ RetryAttempts?: __integer; } export interface BulkDeploymentResult { /** * The time, in ISO format, when the deployment was created. */ CreatedAt?: __string; /** * The ARN of the group deployment. */ DeploymentArn?: __string; /** * The ID of the group deployment. */ DeploymentId?: __string; /** * The current status of the group deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''. */ DeploymentStatus?: __string; /** * The type of the deployment. */ DeploymentType?: DeploymentType; /** * Details about the error. */ ErrorDetails?: ErrorDetails; /** * The error message for a failed deployment */ ErrorMessage?: __string; /** * The ARN of the Greengrass group. */ GroupArn?: __string; } export type BulkDeploymentResults = BulkDeploymentResult[]; export type BulkDeploymentStatus = "Initializing"|"Running"|"Completed"|"Stopping"|"Stopped"|"Failed"|string; export type BulkDeployments = BulkDeployment[]; export type ConfigurationSyncStatus = "InSync"|"OutOfSync"|string; export interface ConnectivityInfo { /** * The endpoint for the Greengrass core. Can be an IP address or DNS. */ HostAddress?: __string; /** * The ID of the connectivity information. */ Id?: __string; /** * Metadata for this endpoint. */ Metadata?: __string; /** * The port of the Greengrass core. Usually 8883. */ PortNumber?: __integer; } export interface Connector { /** * The ARN of the connector. */ ConnectorArn: __string; /** * A descriptive or arbitrary ID for the connector. This value must be unique within the connector definition version. Max length is 128 characters with pattern [a-zA-Z0-9:_-]+. */ Id: __string; /** * The parameters or configuration that the connector uses. */ Parameters?: __mapOf__string; } export interface ConnectorDefinitionVersion { /** * A list of references to connectors in this version, with their corresponding configuration settings. */ Connectors?: __listOfConnector; } export interface Core { /** * The ARN of the certificate associated with the core. */ CertificateArn: __string; /** * A descriptive or arbitrary ID for the core. This value must be unique within the core definition version. Max length is 128 characters with pattern ''[a-zA-Z0-9:_-]+''. */ Id: __string; /** * If true, the core's local shadow is automatically synced with the cloud. */ SyncShadow?: __boolean; /** * The ARN of the thing which is the core. */ ThingArn: __string; } export interface CoreDefinitionVersion { /** * A list of cores in the core definition version. */ Cores?: __listOfCore; } export interface CreateConnectorDefinitionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * Information about the initial version of the connector definition. */ InitialVersion?: ConnectorDefinitionVersion; /** * The name of the connector definition. */ Name?: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface CreateConnectorDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; } export interface CreateConnectorDefinitionVersionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ID of the connector definition. */ ConnectorDefinitionId: __string; /** * A list of references to connectors in this version, with their corresponding configuration settings. */ Connectors?: __listOfConnector; } export interface CreateConnectorDefinitionVersionResponse { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export interface CreateCoreDefinitionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * Information about the initial version of the core definition. */ InitialVersion?: CoreDefinitionVersion; /** * The name of the core definition. */ Name?: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface CreateCoreDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; } export interface CreateCoreDefinitionVersionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ID of the core definition. */ CoreDefinitionId: __string; /** * A list of cores in the core definition version. */ Cores?: __listOfCore; } export interface CreateCoreDefinitionVersionResponse { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export interface CreateDeploymentRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ID of the deployment if you wish to redeploy a previous deployment. */ DeploymentId?: __string; /** * The type of deployment. When used for ''CreateDeployment'', only ''NewDeployment'' and ''Redeployment'' are valid. */ DeploymentType: DeploymentType; /** * The ID of the Greengrass group. */ GroupId: __string; /** * The ID of the group version to be deployed. */ GroupVersionId?: __string; } export interface CreateDeploymentResponse { /** * The ARN of the deployment. */ DeploymentArn?: __string; /** * The ID of the deployment. */ DeploymentId?: __string; } export interface CreateDeviceDefinitionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * Information about the initial version of the device definition. */ InitialVersion?: DeviceDefinitionVersion; /** * The name of the device definition. */ Name?: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface CreateDeviceDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; } export interface CreateDeviceDefinitionVersionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ID of the device definition. */ DeviceDefinitionId: __string; /** * A list of devices in the definition version. */ Devices?: __listOfDevice; } export interface CreateDeviceDefinitionVersionResponse { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export interface CreateFunctionDefinitionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * Information about the initial version of the function definition. */ InitialVersion?: FunctionDefinitionVersion; /** * The name of the function definition. */ Name?: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface CreateFunctionDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; } export interface CreateFunctionDefinitionVersionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The default configuration that applies to all Lambda functions in this function definition version. Individual Lambda functions can override these settings. */ DefaultConfig?: FunctionDefaultConfig; /** * The ID of the Lambda function definition. */ FunctionDefinitionId: __string; /** * A list of Lambda functions in this function definition version. */ Functions?: __listOfFunction; } export interface CreateFunctionDefinitionVersionResponse { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export interface CreateGroupCertificateAuthorityRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ID of the Greengrass group. */ GroupId: __string; } export interface CreateGroupCertificateAuthorityResponse { /** * The ARN of the group certificate authority. */ GroupCertificateAuthorityArn?: __string; } export interface CreateGroupRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * Information about the initial version of the group. */ InitialVersion?: GroupVersion; /** * The name of the group. */ Name?: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface CreateGroupResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; } export interface CreateGroupVersionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ARN of the connector definition version for this group. */ ConnectorDefinitionVersionArn?: __string; /** * The ARN of the core definition version for this group. */ CoreDefinitionVersionArn?: __string; /** * The ARN of the device definition version for this group. */ DeviceDefinitionVersionArn?: __string; /** * The ARN of the function definition version for this group. */ FunctionDefinitionVersionArn?: __string; /** * The ID of the Greengrass group. */ GroupId: __string; /** * The ARN of the logger definition version for this group. */ LoggerDefinitionVersionArn?: __string; /** * The ARN of the resource definition version for this group. */ ResourceDefinitionVersionArn?: __string; /** * The ARN of the subscription definition version for this group. */ SubscriptionDefinitionVersionArn?: __string; } export interface CreateGroupVersionResponse { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export interface CreateLoggerDefinitionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * Information about the initial version of the logger definition. */ InitialVersion?: LoggerDefinitionVersion; /** * The name of the logger definition. */ Name?: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface CreateLoggerDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; } export interface CreateLoggerDefinitionVersionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ID of the logger definition. */ LoggerDefinitionId: __string; /** * A list of loggers. */ Loggers?: __listOfLogger; } export interface CreateLoggerDefinitionVersionResponse { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export interface CreateResourceDefinitionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * Information about the initial version of the resource definition. */ InitialVersion?: ResourceDefinitionVersion; /** * The name of the resource definition. */ Name?: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface CreateResourceDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; } export interface CreateResourceDefinitionVersionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ID of the resource definition. */ ResourceDefinitionId: __string; /** * A list of resources. */ Resources?: __listOfResource; } export interface CreateResourceDefinitionVersionResponse { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export interface CreateSoftwareUpdateJobRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; S3UrlSignerRole: S3UrlSignerRole; SoftwareToUpdate: SoftwareToUpdate; UpdateAgentLogLevel?: UpdateAgentLogLevel; UpdateTargets: UpdateTargets; UpdateTargetsArchitecture: UpdateTargetsArchitecture; UpdateTargetsOperatingSystem: UpdateTargetsOperatingSystem; } export interface CreateSoftwareUpdateJobResponse { /** * The IoT Job ARN corresponding to this update. */ IotJobArn?: __string; /** * The IoT Job Id corresponding to this update. */ IotJobId?: __string; /** * The software version installed on the device or devices after the update. */ PlatformSoftwareVersion?: __string; } export interface CreateSubscriptionDefinitionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * Information about the initial version of the subscription definition. */ InitialVersion?: SubscriptionDefinitionVersion; /** * The name of the subscription definition. */ Name?: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface CreateSubscriptionDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; } export interface CreateSubscriptionDefinitionVersionRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ID of the subscription definition. */ SubscriptionDefinitionId: __string; /** * A list of subscriptions. */ Subscriptions?: __listOfSubscription; } export interface CreateSubscriptionDefinitionVersionResponse { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export interface DefinitionInformation { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ Tags?: Tags; } export interface DeleteConnectorDefinitionRequest { /** * The ID of the connector definition. */ ConnectorDefinitionId: __string; } export interface DeleteConnectorDefinitionResponse { } export interface DeleteCoreDefinitionRequest { /** * The ID of the core definition. */ CoreDefinitionId: __string; } export interface DeleteCoreDefinitionResponse { } export interface DeleteDeviceDefinitionRequest { /** * The ID of the device definition. */ DeviceDefinitionId: __string; } export interface DeleteDeviceDefinitionResponse { } export interface DeleteFunctionDefinitionRequest { /** * The ID of the Lambda function definition. */ FunctionDefinitionId: __string; } export interface DeleteFunctionDefinitionResponse { } export interface DeleteGroupRequest { /** * The ID of the Greengrass group. */ GroupId: __string; } export interface DeleteGroupResponse { } export interface DeleteLoggerDefinitionRequest { /** * The ID of the logger definition. */ LoggerDefinitionId: __string; } export interface DeleteLoggerDefinitionResponse { } export interface DeleteResourceDefinitionRequest { /** * The ID of the resource definition. */ ResourceDefinitionId: __string; } export interface DeleteResourceDefinitionResponse { } export interface DeleteSubscriptionDefinitionRequest { /** * The ID of the subscription definition. */ SubscriptionDefinitionId: __string; } export interface DeleteSubscriptionDefinitionResponse { } export interface Deployment { /** * The time, in milliseconds since the epoch, when the deployment was created. */ CreatedAt?: __string; /** * The ARN of the deployment. */ DeploymentArn?: __string; /** * The ID of the deployment. */ DeploymentId?: __string; /** * The type of the deployment. */ DeploymentType?: DeploymentType; /** * The ARN of the group for this deployment. */ GroupArn?: __string; } export type DeploymentType = "NewDeployment"|"Redeployment"|"ResetDeployment"|"ForceResetDeployment"|string; export type Deployments = Deployment[]; export interface Device { /** * The ARN of the certificate associated with the device. */ CertificateArn: __string; /** * A descriptive or arbitrary ID for the device. This value must be unique within the device definition version. Max length is 128 characters with pattern ''[a-zA-Z0-9:_-]+''. */ Id: __string; /** * If true, the device's local shadow will be automatically synced with the cloud. */ SyncShadow?: __boolean; /** * The thing ARN of the device. */ ThingArn: __string; } export interface DeviceDefinitionVersion { /** * A list of devices in the definition version. */ Devices?: __listOfDevice; } export interface DisassociateRoleFromGroupRequest { /** * The ID of the Greengrass group. */ GroupId: __string; } export interface DisassociateRoleFromGroupResponse { /** * The time, in milliseconds since the epoch, when the role was disassociated from the group. */ DisassociatedAt?: __string; } export interface DisassociateServiceRoleFromAccountRequest { } export interface DisassociateServiceRoleFromAccountResponse { /** * The time when the service role was disassociated from the account. */ DisassociatedAt?: __string; } export type EncodingType = "binary"|"json"|string; export interface ErrorDetail { /** * A detailed error code. */ DetailedErrorCode?: __string; /** * A detailed error message. */ DetailedErrorMessage?: __string; } export type ErrorDetails = ErrorDetail[]; export interface Function { /** * The ARN of the Lambda function. */ FunctionArn?: __string; /** * The configuration of the Lambda function. */ FunctionConfiguration?: FunctionConfiguration; /** * A descriptive or arbitrary ID for the function. This value must be unique within the function definition version. Max length is 128 characters with pattern ''[a-zA-Z0-9:_-]+''. */ Id: __string; } export interface FunctionConfiguration { /** * The expected encoding type of the input payload for the function. The default is ''json''. */ EncodingType?: EncodingType; /** * The environment configuration of the function. */ Environment?: FunctionConfigurationEnvironment; /** * The execution arguments. */ ExecArgs?: __string; /** * The name of the function executable. */ Executable?: __string; /** * The memory size, in KB, which the function requires. This setting is not applicable and should be cleared when you run the Lambda function without containerization. */ MemorySize?: __integer; /** * True if the function is pinned. Pinned means the function is long-lived and starts when the core starts. */ Pinned?: __boolean; /** * The allowed function execution time, after which Lambda should terminate the function. This timeout still applies to pinned Lambda functions for each request. */ Timeout?: __integer; } export interface FunctionConfigurationEnvironment { /** * If true, the Lambda function is allowed to access the host's /sys folder. Use this when the Lambda function needs to read device information from /sys. This setting applies only when you run the Lambda function in a Greengrass container. */ AccessSysfs?: __boolean; /** * Configuration related to executing the Lambda function */ Execution?: FunctionExecutionConfig; /** * A list of the resources, with their permissions, to which the Lambda function will be granted access. A Lambda function can have at most 10 resources. ResourceAccessPolicies apply only when you run the Lambda function in a Greengrass container. */ ResourceAccessPolicies?: __listOfResourceAccessPolicy; /** * Environment variables for the Lambda function's configuration. */ Variables?: __mapOf__string; } export interface FunctionDefaultConfig { Execution?: FunctionDefaultExecutionConfig; } export interface FunctionDefaultExecutionConfig { IsolationMode?: FunctionIsolationMode; RunAs?: FunctionRunAsConfig; } export interface FunctionDefinitionVersion { /** * The default configuration that applies to all Lambda functions in this function definition version. Individual Lambda functions can override these settings. */ DefaultConfig?: FunctionDefaultConfig; /** * A list of Lambda functions in this function definition version. */ Functions?: __listOfFunction; } export interface FunctionExecutionConfig { IsolationMode?: FunctionIsolationMode; RunAs?: FunctionRunAsConfig; } export type FunctionIsolationMode = "GreengrassContainer"|"NoContainer"|string; export interface FunctionRunAsConfig { /** * The group ID whose permissions are used to run a Lambda function. */ Gid?: __integer; /** * The user ID whose permissions are used to run a Lambda function. */ Uid?: __integer; } export interface GetAssociatedRoleRequest { /** * The ID of the Greengrass group. */ GroupId: __string; } export interface GetAssociatedRoleResponse { /** * The time when the role was associated with the group. */ AssociatedAt?: __string; /** * The ARN of the role that is associated with the group. */ RoleArn?: __string; } export interface GetBulkDeploymentStatusRequest { /** * The ID of the bulk deployment. */ BulkDeploymentId: __string; } export interface GetBulkDeploymentStatusResponse { /** * Relevant metrics on input records processed during bulk deployment. */ BulkDeploymentMetrics?: BulkDeploymentMetrics; /** * The status of the bulk deployment. */ BulkDeploymentStatus?: BulkDeploymentStatus; /** * The time, in ISO format, when the deployment was created. */ CreatedAt?: __string; /** * Error details */ ErrorDetails?: ErrorDetails; /** * Error message */ ErrorMessage?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetConnectivityInfoRequest { /** * The thing name. */ ThingName: __string; } export interface GetConnectivityInfoResponse { /** * Connectivity info list. */ ConnectivityInfo?: __listOfConnectivityInfo; /** * A message about the connectivity info request. */ Message?: __string; } export interface GetConnectorDefinitionRequest { /** * The ID of the connector definition. */ ConnectorDefinitionId: __string; } export interface GetConnectorDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetConnectorDefinitionVersionRequest { /** * The ID of the connector definition. */ ConnectorDefinitionId: __string; /** * The ID of the connector definition version. This value maps to the ''Version'' property of the corresponding ''VersionInformation'' object, which is returned by ''ListConnectorDefinitionVersions'' requests. If the version is the last one that was associated with a connector definition, the value also maps to the ''LatestVersion'' property of the corresponding ''DefinitionInformation'' object. */ ConnectorDefinitionVersionId: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface GetConnectorDefinitionVersionResponse { /** * The ARN of the connector definition version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the connector definition version was created. */ CreationTimestamp?: __string; /** * Information about the connector definition version. */ Definition?: ConnectorDefinitionVersion; /** * The ID of the connector definition version. */ Id?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * The version of the connector definition version. */ Version?: __string; } export interface GetCoreDefinitionRequest { /** * The ID of the core definition. */ CoreDefinitionId: __string; } export interface GetCoreDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetCoreDefinitionVersionRequest { /** * The ID of the core definition. */ CoreDefinitionId: __string; /** * The ID of the core definition version. This value maps to the ''Version'' property of the corresponding ''VersionInformation'' object, which is returned by ''ListCoreDefinitionVersions'' requests. If the version is the last one that was associated with a core definition, the value also maps to the ''LatestVersion'' property of the corresponding ''DefinitionInformation'' object. */ CoreDefinitionVersionId: __string; } export interface GetCoreDefinitionVersionResponse { /** * The ARN of the core definition version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the core definition version was created. */ CreationTimestamp?: __string; /** * Information about the core definition version. */ Definition?: CoreDefinitionVersion; /** * The ID of the core definition version. */ Id?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * The version of the core definition version. */ Version?: __string; } export interface GetDeploymentStatusRequest { /** * The ID of the deployment. */ DeploymentId: __string; /** * The ID of the Greengrass group. */ GroupId: __string; } export interface GetDeploymentStatusResponse { /** * The status of the deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''. */ DeploymentStatus?: __string; /** * The type of the deployment. */ DeploymentType?: DeploymentType; /** * Error details */ ErrorDetails?: ErrorDetails; /** * Error message */ ErrorMessage?: __string; /** * The time, in milliseconds since the epoch, when the deployment status was updated. */ UpdatedAt?: __string; } export interface GetDeviceDefinitionRequest { /** * The ID of the device definition. */ DeviceDefinitionId: __string; } export interface GetDeviceDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetDeviceDefinitionVersionRequest { /** * The ID of the device definition. */ DeviceDefinitionId: __string; /** * The ID of the device definition version. This value maps to the ''Version'' property of the corresponding ''VersionInformation'' object, which is returned by ''ListDeviceDefinitionVersions'' requests. If the version is the last one that was associated with a device definition, the value also maps to the ''LatestVersion'' property of the corresponding ''DefinitionInformation'' object. */ DeviceDefinitionVersionId: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface GetDeviceDefinitionVersionResponse { /** * The ARN of the device definition version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the device definition version was created. */ CreationTimestamp?: __string; /** * Information about the device definition version. */ Definition?: DeviceDefinitionVersion; /** * The ID of the device definition version. */ Id?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * The version of the device definition version. */ Version?: __string; } export interface GetFunctionDefinitionRequest { /** * The ID of the Lambda function definition. */ FunctionDefinitionId: __string; } export interface GetFunctionDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetFunctionDefinitionVersionRequest { /** * The ID of the Lambda function definition. */ FunctionDefinitionId: __string; /** * The ID of the function definition version. This value maps to the ''Version'' property of the corresponding ''VersionInformation'' object, which is returned by ''ListFunctionDefinitionVersions'' requests. If the version is the last one that was associated with a function definition, the value also maps to the ''LatestVersion'' property of the corresponding ''DefinitionInformation'' object. */ FunctionDefinitionVersionId: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface GetFunctionDefinitionVersionResponse { /** * The ARN of the function definition version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the function definition version was created. */ CreationTimestamp?: __string; /** * Information on the definition. */ Definition?: FunctionDefinitionVersion; /** * The ID of the function definition version. */ Id?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * The version of the function definition version. */ Version?: __string; } export interface GetGroupCertificateAuthorityRequest { /** * The ID of the certificate authority. */ CertificateAuthorityId: __string; /** * The ID of the Greengrass group. */ GroupId: __string; } export interface GetGroupCertificateAuthorityResponse { /** * The ARN of the certificate authority for the group. */ GroupCertificateAuthorityArn?: __string; /** * The ID of the certificate authority for the group. */ GroupCertificateAuthorityId?: __string; /** * The PEM encoded certificate for the group. */ PemEncodedCertificate?: __string; } export interface GetGroupCertificateConfigurationRequest { /** * The ID of the Greengrass group. */ GroupId: __string; } export interface GetGroupCertificateConfigurationResponse { /** * The amount of time remaining before the certificate authority expires, in milliseconds. */ CertificateAuthorityExpiryInMilliseconds?: __string; /** * The amount of time remaining before the certificate expires, in milliseconds. */ CertificateExpiryInMilliseconds?: __string; /** * The ID of the group certificate configuration. */ GroupId?: __string; } export interface GetGroupRequest { /** * The ID of the Greengrass group. */ GroupId: __string; } export interface GetGroupResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetGroupVersionRequest { /** * The ID of the Greengrass group. */ GroupId: __string; /** * The ID of the group version. This value maps to the ''Version'' property of the corresponding ''VersionInformation'' object, which is returned by ''ListGroupVersions'' requests. If the version is the last one that was associated with a group, the value also maps to the ''LatestVersion'' property of the corresponding ''GroupInformation'' object. */ GroupVersionId: __string; } export interface GetGroupVersionResponse { /** * The ARN of the group version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the group version was created. */ CreationTimestamp?: __string; /** * Information about the group version definition. */ Definition?: GroupVersion; /** * The ID of the group that the version is associated with. */ Id?: __string; /** * The ID of the group version. */ Version?: __string; } export interface GetLoggerDefinitionRequest { /** * The ID of the logger definition. */ LoggerDefinitionId: __string; } export interface GetLoggerDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetLoggerDefinitionVersionRequest { /** * The ID of the logger definition. */ LoggerDefinitionId: __string; /** * The ID of the logger definition version. This value maps to the ''Version'' property of the corresponding ''VersionInformation'' object, which is returned by ''ListLoggerDefinitionVersions'' requests. If the version is the last one that was associated with a logger definition, the value also maps to the ''LatestVersion'' property of the corresponding ''DefinitionInformation'' object. */ LoggerDefinitionVersionId: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface GetLoggerDefinitionVersionResponse { /** * The ARN of the logger definition version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the logger definition version was created. */ CreationTimestamp?: __string; /** * Information about the logger definition version. */ Definition?: LoggerDefinitionVersion; /** * The ID of the logger definition version. */ Id?: __string; /** * The version of the logger definition version. */ Version?: __string; } export interface GetResourceDefinitionRequest { /** * The ID of the resource definition. */ ResourceDefinitionId: __string; } export interface GetResourceDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetResourceDefinitionVersionRequest { /** * The ID of the resource definition. */ ResourceDefinitionId: __string; /** * The ID of the resource definition version. This value maps to the ''Version'' property of the corresponding ''VersionInformation'' object, which is returned by ''ListResourceDefinitionVersions'' requests. If the version is the last one that was associated with a resource definition, the value also maps to the ''LatestVersion'' property of the corresponding ''DefinitionInformation'' object. */ ResourceDefinitionVersionId: __string; } export interface GetResourceDefinitionVersionResponse { /** * Arn of the resource definition version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the resource definition version was created. */ CreationTimestamp?: __string; /** * Information about the definition. */ Definition?: ResourceDefinitionVersion; /** * The ID of the resource definition version. */ Id?: __string; /** * The version of the resource definition version. */ Version?: __string; } export interface GetServiceRoleForAccountRequest { } export interface GetServiceRoleForAccountResponse { /** * The time when the service role was associated with the account. */ AssociatedAt?: __string; /** * The ARN of the role which is associated with the account. */ RoleArn?: __string; } export interface GetSubscriptionDefinitionRequest { /** * The ID of the subscription definition. */ SubscriptionDefinitionId: __string; } export interface GetSubscriptionDefinitionResponse { /** * The ARN of the definition. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the definition was created. */ CreationTimestamp?: __string; /** * The ID of the definition. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the definition was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the definition. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the definition. */ LatestVersionArn?: __string; /** * The name of the definition. */ Name?: __string; /** * Tag(s) attached to the resource arn. */ tags?: Tags; } export interface GetSubscriptionDefinitionVersionRequest { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * The ID of the subscription definition. */ SubscriptionDefinitionId: __string; /** * The ID of the subscription definition version. This value maps to the ''Version'' property of the corresponding ''VersionInformation'' object, which is returned by ''ListSubscriptionDefinitionVersions'' requests. If the version is the last one that was associated with a subscription definition, the value also maps to the ''LatestVersion'' property of the corresponding ''DefinitionInformation'' object. */ SubscriptionDefinitionVersionId: __string; } export interface GetSubscriptionDefinitionVersionResponse { /** * The ARN of the subscription definition version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the subscription definition version was created. */ CreationTimestamp?: __string; /** * Information about the subscription definition version. */ Definition?: SubscriptionDefinitionVersion; /** * The ID of the subscription definition version. */ Id?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * The version of the subscription definition version. */ Version?: __string; } export interface GetThingRuntimeConfigurationRequest { /** * The thing name. */ ThingName: __string; } export interface GetThingRuntimeConfigurationResponse { /** * Runtime configuration for a thing. */ RuntimeConfiguration?: RuntimeConfiguration; } export interface GroupCertificateAuthorityProperties { /** * The ARN of the certificate authority for the group. */ GroupCertificateAuthorityArn?: __string; /** * The ID of the certificate authority for the group. */ GroupCertificateAuthorityId?: __string; } export interface GroupInformation { /** * The ARN of the group. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the group was created. */ CreationTimestamp?: __string; /** * The ID of the group. */ Id?: __string; /** * The time, in milliseconds since the epoch, when the group was last updated. */ LastUpdatedTimestamp?: __string; /** * The ID of the latest version associated with the group. */ LatestVersion?: __string; /** * The ARN of the latest version associated with the group. */ LatestVersionArn?: __string; /** * The name of the group. */ Name?: __string; } export interface GroupOwnerSetting { /** * If true, AWS IoT Greengrass automatically adds the specified Linux OS group owner of the resource to the Lambda process privileges. Thus the Lambda process will have the file access permissions of the added Linux group. */ AutoAddGroupOwner?: __boolean; /** * The name of the Linux OS group whose privileges will be added to the Lambda process. This field is optional. */ GroupOwner?: __string; } export interface GroupVersion { /** * The ARN of the connector definition version for this group. */ ConnectorDefinitionVersionArn?: __string; /** * The ARN of the core definition version for this group. */ CoreDefinitionVersionArn?: __string; /** * The ARN of the device definition version for this group. */ DeviceDefinitionVersionArn?: __string; /** * The ARN of the function definition version for this group. */ FunctionDefinitionVersionArn?: __string; /** * The ARN of the logger definition version for this group. */ LoggerDefinitionVersionArn?: __string; /** * The ARN of the resource definition version for this group. */ ResourceDefinitionVersionArn?: __string; /** * The ARN of the subscription definition version for this group. */ SubscriptionDefinitionVersionArn?: __string; } export interface ListBulkDeploymentDetailedReportsRequest { /** * The ID of the bulk deployment. */ BulkDeploymentId: __string; /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListBulkDeploymentDetailedReportsResponse { /** * A list of the individual group deployments in the bulk deployment operation. */ Deployments?: BulkDeploymentResults; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListBulkDeploymentsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListBulkDeploymentsResponse { /** * A list of bulk deployments. */ BulkDeployments?: BulkDeployments; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListConnectorDefinitionVersionsRequest { /** * The ID of the connector definition. */ ConnectorDefinitionId: __string; /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListConnectorDefinitionVersionsResponse { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * Information about a version. */ Versions?: __listOfVersionInformation; } export interface ListConnectorDefinitionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListConnectorDefinitionsResponse { /** * Information about a definition. */ Definitions?: __listOfDefinitionInformation; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListCoreDefinitionVersionsRequest { /** * The ID of the core definition. */ CoreDefinitionId: __string; /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListCoreDefinitionVersionsResponse { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * Information about a version. */ Versions?: __listOfVersionInformation; } export interface ListCoreDefinitionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListCoreDefinitionsResponse { /** * Information about a definition. */ Definitions?: __listOfDefinitionInformation; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListDeploymentsRequest { /** * The ID of the Greengrass group. */ GroupId: __string; /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListDeploymentsResponse { /** * A list of deployments for the requested groups. */ Deployments?: Deployments; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListDeviceDefinitionVersionsRequest { /** * The ID of the device definition. */ DeviceDefinitionId: __string; /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListDeviceDefinitionVersionsResponse { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * Information about a version. */ Versions?: __listOfVersionInformation; } export interface ListDeviceDefinitionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListDeviceDefinitionsResponse { /** * Information about a definition. */ Definitions?: __listOfDefinitionInformation; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListFunctionDefinitionVersionsRequest { /** * The ID of the Lambda function definition. */ FunctionDefinitionId: __string; /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListFunctionDefinitionVersionsResponse { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * Information about a version. */ Versions?: __listOfVersionInformation; } export interface ListFunctionDefinitionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListFunctionDefinitionsResponse { /** * Information about a definition. */ Definitions?: __listOfDefinitionInformation; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListGroupCertificateAuthoritiesRequest { /** * The ID of the Greengrass group. */ GroupId: __string; } export interface ListGroupCertificateAuthoritiesResponse { /** * A list of certificate authorities associated with the group. */ GroupCertificateAuthorities?: __listOfGroupCertificateAuthorityProperties; } export interface ListGroupVersionsRequest { /** * The ID of the Greengrass group. */ GroupId: __string; /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListGroupVersionsResponse { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * Information about a version. */ Versions?: __listOfVersionInformation; } export interface ListGroupsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListGroupsResponse { /** * Information about a group. */ Groups?: __listOfGroupInformation; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListLoggerDefinitionVersionsRequest { /** * The ID of the logger definition. */ LoggerDefinitionId: __string; /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListLoggerDefinitionVersionsResponse { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * Information about a version. */ Versions?: __listOfVersionInformation; } export interface ListLoggerDefinitionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListLoggerDefinitionsResponse { /** * Information about a definition. */ Definitions?: __listOfDefinitionInformation; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListResourceDefinitionVersionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * The ID of the resource definition. */ ResourceDefinitionId: __string; } export interface ListResourceDefinitionVersionsResponse { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * Information about a version. */ Versions?: __listOfVersionInformation; } export interface ListResourceDefinitionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListResourceDefinitionsResponse { /** * Information about a definition. */ Definitions?: __listOfDefinitionInformation; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListSubscriptionDefinitionVersionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * The ID of the subscription definition. */ SubscriptionDefinitionId: __string; } export interface ListSubscriptionDefinitionVersionsResponse { /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; /** * Information about a version. */ Versions?: __listOfVersionInformation; } export interface ListSubscriptionDefinitionsRequest { /** * The maximum number of results to be returned per request. */ MaxResults?: __string; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListSubscriptionDefinitionsResponse { /** * Information about a definition. */ Definitions?: __listOfDefinitionInformation; /** * The token for the next set of results, or ''null'' if there are no additional results. */ NextToken?: __string; } export interface ListTagsForResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ ResourceArn: __string; } export interface ListTagsForResourceResponse { tags?: Tags; } export interface LocalDeviceResourceData { /** * Group/owner related settings for local resources. */ GroupOwnerSetting?: GroupOwnerSetting; /** * The local absolute path of the device resource. The source path for a device resource can refer only to a character device or block device under ''/dev''. */ SourcePath?: __string; } export interface LocalVolumeResourceData { /** * The absolute local path of the resource inside the Lambda environment. */ DestinationPath?: __string; /** * Allows you to configure additional group privileges for the Lambda process. This field is optional. */ GroupOwnerSetting?: GroupOwnerSetting; /** * The local absolute path of the volume resource on the host. The source path for a volume resource type cannot start with ''/sys''. */ SourcePath?: __string; } export interface Logger { /** * The component that will be subject to logging. */ Component: LoggerComponent; /** * A descriptive or arbitrary ID for the logger. This value must be unique within the logger definition version. Max length is 128 characters with pattern ''[a-zA-Z0-9:_-]+''. */ Id: __string; /** * The level of the logs. */ Level: LoggerLevel; /** * The amount of file space, in KB, to use if the local file system is used for logging purposes. */ Space?: __integer; /** * The type of log output which will be used. */ Type: LoggerType; } export type LoggerComponent = "GreengrassSystem"|"Lambda"|string; export interface LoggerDefinitionVersion { /** * A list of loggers. */ Loggers?: __listOfLogger; } export type LoggerLevel = "DEBUG"|"INFO"|"WARN"|"ERROR"|"FATAL"|string; export type LoggerType = "FileSystem"|"AWSCloudWatch"|string; export type Permission = "ro"|"rw"|string; export interface ResetDeploymentsRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * If true, performs a best-effort only core reset. */ Force?: __boolean; /** * The ID of the Greengrass group. */ GroupId: __string; } export interface ResetDeploymentsResponse { /** * The ARN of the deployment. */ DeploymentArn?: __string; /** * The ID of the deployment. */ DeploymentId?: __string; } export interface Resource { /** * The resource ID, used to refer to a resource in the Lambda function configuration. Max length is 128 characters with pattern ''[a-zA-Z0-9:_-]+''. This must be unique within a Greengrass group. */ Id: __string; /** * The descriptive resource name, which is displayed on the AWS IoT Greengrass console. Max length 128 characters with pattern ''[a-zA-Z0-9:_-]+''. This must be unique within a Greengrass group. */ Name: __string; /** * A container of data for all resource types. */ ResourceDataContainer: ResourceDataContainer; } export interface ResourceAccessPolicy { /** * The permissions that the Lambda function has to the resource. Can be one of ''rw'' (read/write) or ''ro'' (read-only). */ Permission?: Permission; /** * The ID of the resource. (This ID is assigned to the resource when you create the resource definiton.) */ ResourceId: __string; } export interface ResourceDataContainer { /** * Attributes that define the local device resource. */ LocalDeviceResourceData?: LocalDeviceResourceData; /** * Attributes that define the local volume resource. */ LocalVolumeResourceData?: LocalVolumeResourceData; /** * Attributes that define an Amazon S3 machine learning resource. */ S3MachineLearningModelResourceData?: S3MachineLearningModelResourceData; /** * Attributes that define an Amazon SageMaker machine learning resource. */ SageMakerMachineLearningModelResourceData?: SageMakerMachineLearningModelResourceData; /** * Attributes that define a secret resource, which references a secret from AWS Secrets Manager. */ SecretsManagerSecretResourceData?: SecretsManagerSecretResourceData; } export interface ResourceDefinitionVersion { /** * A list of resources. */ Resources?: __listOfResource; } export interface ResourceDownloadOwnerSetting { /** * The group owner of the resource. This is the name of an existing Linux OS group on the system or a GID. The group's permissions are added to the Lambda process. */ GroupOwner: __string; /** * The permissions that the group owner has to the resource. Valid values are ''rw'' (read/write) or ''ro'' (read-only). */ GroupPermission: Permission; } export interface RuntimeConfiguration { /** * Configuration for telemetry service. */ TelemetryConfiguration?: TelemetryConfiguration; } export interface S3MachineLearningModelResourceData { /** * The absolute local path of the resource inside the Lambda environment. */ DestinationPath?: __string; OwnerSetting?: ResourceDownloadOwnerSetting; /** * The URI of the source model in an S3 bucket. The model package must be in tar.gz or .zip format. */ S3Uri?: __string; } export type S3UrlSignerRole = string; export interface SageMakerMachineLearningModelResourceData { /** * The absolute local path of the resource inside the Lambda environment. */ DestinationPath?: __string; OwnerSetting?: ResourceDownloadOwnerSetting; /** * The ARN of the Amazon SageMaker training job that represents the source model. */ SageMakerJobArn?: __string; } export interface SecretsManagerSecretResourceData { /** * The ARN of the Secrets Manager secret to make available on the core. The value of the secret's latest version (represented by the ''AWSCURRENT'' staging label) is included by default. */ ARN?: __string; /** * Optional. The staging labels whose values you want to make available on the core, in addition to ''AWSCURRENT''. */ AdditionalStagingLabelsToDownload?: __listOf__string; } export type SoftwareToUpdate = "core"|"ota_agent"|string; export interface StartBulkDeploymentRequest { /** * A client token used to correlate requests and responses. */ AmznClientToken?: __string; /** * The ARN of the execution role to associate with the bulk deployment operation. This IAM role must allow the ''greengrass:CreateDeployment'' action for all group versions that are listed in the input file. This IAM role must have access to the S3 bucket containing the input file. */ ExecutionRoleArn: __string; /** * The URI of the input file contained in the S3 bucket. The execution role must have ''getObject'' permissions on this bucket to access the input file. The input file is a JSON-serialized, line delimited file with UTF-8 encoding that provides a list of group and version IDs and the deployment type. This file must be less than 100 MB. Currently, AWS IoT Greengrass supports only ''NewDeployment'' deployment types. */ InputFileUri: __string; /** * Tag(s) to add to the new resource. */ tags?: Tags; } export interface StartBulkDeploymentResponse { /** * The ARN of the bulk deployment. */ BulkDeploymentArn?: __string; /** * The ID of the bulk deployment. */ BulkDeploymentId?: __string; } export interface StopBulkDeploymentRequest { /** * The ID of the bulk deployment. */ BulkDeploymentId: __string; } export interface StopBulkDeploymentResponse { } export interface Subscription { /** * A descriptive or arbitrary ID for the subscription. This value must be unique within the subscription definition version. Max length is 128 characters with pattern ''[a-zA-Z0-9:_-]+''. */ Id: __string; /** * The source of the subscription. Can be a thing ARN, a Lambda function ARN, a connector ARN, 'cloud' (which represents the AWS IoT cloud), or 'GGShadowService'. */ Source: __string; /** * The MQTT topic used to route the message. */ Subject: __string; /** * Where the message is sent to. Can be a thing ARN, a Lambda function ARN, a connector ARN, 'cloud' (which represents the AWS IoT cloud), or 'GGShadowService'. */ Target: __string; } export interface SubscriptionDefinitionVersion { /** * A list of subscriptions. */ Subscriptions?: __listOfSubscription; } export interface TagResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ ResourceArn: __string; tags?: Tags; } export type Tags = {[key: string]: __string}; export type Telemetry = "On"|"Off"|string; export interface TelemetryConfiguration { /** * Synchronization status of the device reported configuration with the desired configuration. */ ConfigurationSyncStatus?: ConfigurationSyncStatus; /** * Configure telemetry to be on or off. */ Telemetry: Telemetry; } export interface TelemetryConfigurationUpdate { /** * Configure telemetry to be on or off. */ Telemetry: Telemetry; } export interface UntagResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ ResourceArn: __string; /** * An array of tag keys to delete */ TagKeys: __listOf__string; } export type UpdateAgentLogLevel = "NONE"|"TRACE"|"DEBUG"|"VERBOSE"|"INFO"|"WARN"|"ERROR"|"FATAL"|string; export interface UpdateConnectivityInfoRequest { /** * A list of connectivity info. */ ConnectivityInfo?: __listOfConnectivityInfo; /** * The thing name. */ ThingName: __string; } export interface UpdateConnectivityInfoResponse { /** * A message about the connectivity info update request. */ Message?: __string; /** * The new version of the connectivity info. */ Version?: __string; } export interface UpdateConnectorDefinitionRequest { /** * The ID of the connector definition. */ ConnectorDefinitionId: __string; /** * The name of the definition. */ Name?: __string; } export interface UpdateConnectorDefinitionResponse { } export interface UpdateCoreDefinitionRequest { /** * The ID of the core definition. */ CoreDefinitionId: __string; /** * The name of the definition. */ Name?: __string; } export interface UpdateCoreDefinitionResponse { } export interface UpdateDeviceDefinitionRequest { /** * The ID of the device definition. */ DeviceDefinitionId: __string; /** * The name of the definition. */ Name?: __string; } export interface UpdateDeviceDefinitionResponse { } export interface UpdateFunctionDefinitionRequest { /** * The ID of the Lambda function definition. */ FunctionDefinitionId: __string; /** * The name of the definition. */ Name?: __string; } export interface UpdateFunctionDefinitionResponse { } export interface UpdateGroupCertificateConfigurationRequest { /** * The amount of time remaining before the certificate expires, in milliseconds. */ CertificateExpiryInMilliseconds?: __string; /** * The ID of the Greengrass group. */ GroupId: __string; } export interface UpdateGroupCertificateConfigurationResponse { /** * The amount of time remaining before the certificate authority expires, in milliseconds. */ CertificateAuthorityExpiryInMilliseconds?: __string; /** * The amount of time remaining before the certificate expires, in milliseconds. */ CertificateExpiryInMilliseconds?: __string; /** * The ID of the group certificate configuration. */ GroupId?: __string; } export interface UpdateGroupRequest { /** * The ID of the Greengrass group. */ GroupId: __string; /** * The name of the definition. */ Name?: __string; } export interface UpdateGroupResponse { } export interface UpdateLoggerDefinitionRequest { /** * The ID of the logger definition. */ LoggerDefinitionId: __string; /** * The name of the definition. */ Name?: __string; } export interface UpdateLoggerDefinitionResponse { } export interface UpdateResourceDefinitionRequest { /** * The name of the definition. */ Name?: __string; /** * The ID of the resource definition. */ ResourceDefinitionId: __string; } export interface UpdateResourceDefinitionResponse { } export interface UpdateSubscriptionDefinitionRequest { /** * The name of the definition. */ Name?: __string; /** * The ID of the subscription definition. */ SubscriptionDefinitionId: __string; } export interface UpdateSubscriptionDefinitionResponse { } export type UpdateTargets = __string[]; export type UpdateTargetsArchitecture = "armv6l"|"armv7l"|"x86_64"|"aarch64"|string; export type UpdateTargetsOperatingSystem = "ubuntu"|"raspbian"|"amazon_linux"|"openwrt"|string; export interface UpdateThingRuntimeConfigurationRequest { /** * Configuration for telemetry service. */ TelemetryConfiguration?: TelemetryConfigurationUpdate; /** * The thing name. */ ThingName: __string; } export interface UpdateThingRuntimeConfigurationResponse { } export interface VersionInformation { /** * The ARN of the version. */ Arn?: __string; /** * The time, in milliseconds since the epoch, when the version was created. */ CreationTimestamp?: __string; /** * The ID of the parent definition that the version is associated with. */ Id?: __string; /** * The ID of the version. */ Version?: __string; } export type __boolean = boolean; export type __integer = number; export type __listOfConnectivityInfo = ConnectivityInfo[]; export type __listOfConnector = Connector[]; export type __listOfCore = Core[]; export type __listOfDefinitionInformation = DefinitionInformation[]; export type __listOfDevice = Device[]; export type __listOfFunction = Function[]; export type __listOfGroupCertificateAuthorityProperties = GroupCertificateAuthorityProperties[]; export type __listOfGroupInformation = GroupInformation[]; export type __listOfLogger = Logger[]; export type __listOfResource = Resource[]; export type __listOfResourceAccessPolicy = ResourceAccessPolicy[]; export type __listOfSubscription = Subscription[]; export type __listOfVersionInformation = VersionInformation[]; export type __listOf__string = __string[]; export type __mapOf__string = {[key: string]: __string}; export type __string = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2017-06-07"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the Greengrass client. */ export import Types = Greengrass; } export = Greengrass;
the_stack
import { ExposedPromise } from '../../utils/exposed-promise' import { Logger } from '../../utils/Logger' import { generateGUID } from '../../utils/generate-uuid' import { BeaconEvent, BeaconEventHandlerFunction, BeaconEventType, WalletInfo } from '../../events' import { BEACON_VERSION } from '../../constants' import { getAddressFromPublicKey } from '../../utils/crypto' import { ConnectionContext } from '../../types/ConnectionContext' import { AccountInfo, Client, TransportType, StorageKey, BeaconMessageType, PermissionScope, PermissionResponse, NetworkType, SignPayloadResponse, SignPayloadRequest, OperationResponse, OperationRequest, BroadcastResponse, BroadcastRequest, ErrorResponse, BeaconMessage, RequestPermissionInput, RequestSignPayloadInput, RequestOperationInput, RequestBroadcastInput, PermissionRequest, Serializer, LocalStorage, PermissionResponseOutput, PermissionRequestInput, SignPayloadResponseOutput, SignPayloadRequestInput, OperationResponseOutput, OperationRequestInput, BroadcastResponseOutput, BroadcastRequestInput, BeaconRequestInputMessage, Network, BeaconError, Origin, PostMessageTransport, PeerInfo, Transport, DappP2PTransport, DappPostMessageTransport, AppMetadataManager, AppMetadata // RequestEncryptPayloadInput, // EncryptPayloadResponseOutput, // EncryptPayloadResponse, // EncryptPayloadRequest } from '../..' import { messageEvents } from '../../beacon-message-events' import { // EncryptPayloadRequestInput, IgnoredRequestInputProperties } from '../../types/beacon/messages/BeaconRequestInputMessage' import { getAccountIdentifier } from '../../utils/get-account-identifier' import { BlockExplorer } from '../../utils/block-explorer' import { TezblockBlockExplorer } from '../../utils/tezblock-blockexplorer' import { BeaconErrorType } from '../../types/BeaconErrorType' import { AlertButton } from '../../ui/alert/Alert' import { ExtendedP2PPairingResponse } from '../../types/P2PPairingResponse' import { ExtendedPostMessagePairingResponse, PostMessagePairingResponse } from '../../types/PostMessagePairingResponse' import { getSenderId } from '../../utils/get-sender-id' import { SigningType } from '../../types/beacon/SigningType' import { ExtendedPeerInfo } from '../../types/PeerInfo' import { ColorMode } from '../../types/ColorMode' import { getColorMode, setColorMode } from '../../colorMode' import { desktopList, extensionList, iOSList, webList } from '../../ui/alert/wallet-lists' import { Optional } from '../../utils/utils' import { DAppClientOptions } from './DAppClientOptions' import { App, DesktopApp, ExtensionApp, WebApp } from '../../ui/alert/Pairing' import { closeToast } from '../../ui/toast/Toast' const logger = new Logger('DAppClient') /** * @publicapi * * The DAppClient has to be used in decentralized applications. It handles all the logic related to connecting to beacon-compatible * wallets and sending requests. * * @category DApp */ export class DAppClient extends Client { /** * The block explorer used by the SDK */ public readonly blockExplorer: BlockExplorer public preferredNetwork: NetworkType protected postMessageTransport: DappPostMessageTransport | undefined protected p2pTransport: DappP2PTransport | undefined /** * A map of requests that are currently "open", meaning we have sent them to a wallet and are still awaiting a response. */ private readonly openRequests = new Map< string, ExposedPromise<{ message: BeaconMessage; connectionInfo: ConnectionContext }, ErrorResponse> >() /** * The currently active account. For all requests that are associated to a specific request (operation request, signing request), * the active account is used to determine the network and destination wallet */ private _activeAccount: ExposedPromise<AccountInfo | undefined> = new ExposedPromise() /** * The currently active peer. This is used to address a peer in case the active account is not set. (Eg. for permission requests) */ private _activePeer: ExposedPromise< ExtendedPostMessagePairingResponse | ExtendedP2PPairingResponse | undefined > = new ExposedPromise() private _initPromise: Promise<TransportType> | undefined private readonly activeAccountLoaded: Promise<void> private readonly appMetadataManager: AppMetadataManager private readonly disclaimerText?: string constructor(config: DAppClientOptions) { super({ storage: config && config.storage ? config.storage : new LocalStorage(), ...config }) this.blockExplorer = config.blockExplorer ?? new TezblockBlockExplorer() this.preferredNetwork = config.preferredNetwork ?? NetworkType.MAINNET setColorMode(config.colorMode ?? ColorMode.LIGHT) this.disclaimerText = config.disclaimerText this.appMetadataManager = new AppMetadataManager(this.storage) this.activeAccountLoaded = this.storage .get(StorageKey.ACTIVE_ACCOUNT) .then(async (activeAccountIdentifier) => { if (activeAccountIdentifier) { await this.setActiveAccount(await this.accountManager.getAccount(activeAccountIdentifier)) } else { await this.setActiveAccount(undefined) } }) .catch(async (storageError) => { await this.setActiveAccount(undefined) console.error(storageError) }) this.handleResponse = async ( message: BeaconMessage, connectionInfo: ConnectionContext ): Promise<void> => { const openRequest = this.openRequests.get(message.id) logger.log('handleResponse', 'Received message', message, connectionInfo) if (openRequest && message.type === BeaconMessageType.Acknowledge) { logger.log(`acknowledge message received for ${message.id}`) console.timeLog(message.id, 'acknowledge') this.events .emit(BeaconEvent.ACKNOWLEDGE_RECEIVED, { message, extraInfo: {}, walletInfo: await this.getWalletInfo() }) .catch(console.error) } else if (openRequest) { if (message.type === BeaconMessageType.PermissionResponse && message.appMetadata) { await this.appMetadataManager.addAppMetadata(message.appMetadata) } console.timeLog(message.id, 'response') console.timeEnd(message.id) if (message.type === BeaconMessageType.Error || (message as any).errorType) { // TODO: Remove "any" once we remove support for v1 wallets openRequest.reject(message as any) } else { openRequest.resolve({ message, connectionInfo }) } this.openRequests.delete(message.id) } else { if (message.type === BeaconMessageType.Disconnect) { const relevantTransport = connectionInfo.origin === Origin.P2P ? this.p2pTransport : this.postMessageTransport ?? (await this.transport) if (relevantTransport) { // TODO: Handle removing it from the right transport (if it was received from the non-active transport) const peers: ExtendedPeerInfo[] = await relevantTransport.getPeers() const peer: ExtendedPeerInfo | undefined = peers.find( (peerEl) => peerEl.senderId === message.senderId ) if (peer) { await relevantTransport.removePeer(peer as any) await this.removeAccountsForPeers([peer]) await this.events.emit(BeaconEvent.CHANNEL_CLOSED) } else { logger.error('handleDisconnect', 'cannot find peer for sender ID', message.senderId) } } } else { logger.error('handleResponse', 'no request found for id ', message.id) } } } } public async initInternalTransports(): Promise<void> { const keyPair = await this.keyPair if (this.postMessageTransport || this.p2pTransport) { return } this.postMessageTransport = new DappPostMessageTransport(this.name, keyPair, this.storage) await this.addListener(this.postMessageTransport) this.p2pTransport = new DappP2PTransport( this.name, keyPair, this.storage, this.matrixNodes, this.iconUrl, this.appUrl ) await this.addListener(this.p2pTransport) } public async init(transport?: Transport<any>): Promise<TransportType> { if (this._initPromise) { return this._initPromise } try { await this.activeAccountLoaded } catch { // } this._initPromise = new Promise(async (resolve) => { if (transport) { await this.addListener(transport) resolve(await super.init(transport)) } else if (this._transport.isSettled()) { await (await this.transport).connect() resolve(await super.init(await this.transport)) } else { const activeAccount = await this.getActiveAccount() const stopListening = () => { if (this.postMessageTransport) { this.postMessageTransport.stopListeningForNewPeers().catch(console.error) } if (this.p2pTransport) { this.p2pTransport.stopListeningForNewPeers().catch(console.error) } } await this.initInternalTransports() if (!this.postMessageTransport || !this.p2pTransport) { return } this.postMessageTransport.connect().then().catch(console.error) if (activeAccount && activeAccount.origin) { const origin = activeAccount.origin.type // Select the transport that matches the active account if (origin === Origin.EXTENSION) { resolve(await super.init(this.postMessageTransport)) } else if (origin === Origin.P2P) { resolve(await super.init(this.p2pTransport)) } } else { const p2pTransport = this.p2pTransport const postMessageTransport = this.postMessageTransport postMessageTransport .listenForNewPeer((peer) => { logger.log('init', 'postmessage transport peer connected', peer) this.events .emit(BeaconEvent.PAIR_SUCCESS, peer) .catch((emitError) => console.warn(emitError)) this.setActivePeer(peer).catch(console.error) this.setTransport(this.postMessageTransport).catch(console.error) stopListening() resolve(TransportType.POST_MESSAGE) }) .catch(console.error) p2pTransport .listenForNewPeer((peer) => { logger.log('init', 'p2p transport peer connected', peer) this.events .emit(BeaconEvent.PAIR_SUCCESS, peer) .catch((emitError) => console.warn(emitError)) this.setActivePeer(peer).catch(console.error) this.setTransport(this.p2pTransport).catch(console.error) stopListening() resolve(TransportType.P2P) }) .catch(console.error) PostMessageTransport.getAvailableExtensions() .then(async () => { this.events .emit(BeaconEvent.PAIR_INIT, { p2pPeerInfo: () => { p2pTransport.connect().then().catch(console.error) return p2pTransport.getPairingRequestInfo() }, postmessagePeerInfo: () => postMessageTransport.getPairingRequestInfo(), preferredNetwork: this.preferredNetwork, abortedHandler: () => { this._initPromise = undefined }, disclaimerText: this.disclaimerText }) .catch((emitError) => console.warn(emitError)) }) .catch((error) => { this._initPromise = undefined console.error(error) }) } } }) return this._initPromise } /** * Returns the active account */ public async getActiveAccount(): Promise<AccountInfo | undefined> { return this._activeAccount.promise } /** * Sets the active account * * @param account The account that will be set as the active account */ public async setActiveAccount(account?: AccountInfo): Promise<void> { if (this._activeAccount.isSettled()) { // If the promise has already been resolved we need to create a new one. this._activeAccount = ExposedPromise.resolve<AccountInfo | undefined>(account) } else { this._activeAccount.resolve(account) } if (account) { const origin = account.origin.type await this.initInternalTransports() // Select the transport that matches the active account if (origin === Origin.EXTENSION) { await this.setTransport(this.postMessageTransport) } else if (origin === Origin.P2P) { await this.setTransport(this.p2pTransport) } const peer = await this.getPeer(account) await this.setActivePeer(peer as any) } else { await this.setActivePeer(undefined) await this.setTransport(undefined) } await this.storage.set( StorageKey.ACTIVE_ACCOUNT, account ? account.accountIdentifier : undefined ) await this.events.emit(BeaconEvent.ACTIVE_ACCOUNT_SET, account) return } /** * Clear the active account */ public clearActiveAccount(): Promise<void> { return this.setActiveAccount() } public async setColorMode(colorMode: ColorMode): Promise<void> { return setColorMode(colorMode) } public async getColorMode(): Promise<ColorMode> { return getColorMode() } /** * @deprecated * * Use getOwnAppMetadata instead */ public async getAppMetadata(): Promise<AppMetadata> { return this.getOwnAppMetadata() } public async showPrepare(): Promise<void> { const walletInfo = await (async () => { try { return await this.getWalletInfo() } catch { return undefined } })() await this.events.emit(BeaconEvent.SHOW_PREPARE, { walletInfo }) } public async hideUI(elements?: ('alert' | 'toast')[]): Promise<void> { await this.events.emit(BeaconEvent.HIDE_UI, elements) } /** * Will remove the account from the local storage and set a new active account if necessary. * * @param accountIdentifier ID of the account */ public async removeAccount(accountIdentifier: string): Promise<void> { const removeAccountResult = super.removeAccount(accountIdentifier) const activeAccount: AccountInfo | undefined = await this.getActiveAccount() if (activeAccount && activeAccount.accountIdentifier === accountIdentifier) { await this.setActiveAccount(undefined) } return removeAccountResult } /** * Remove all accounts and set active account to undefined */ public async removeAllAccounts(): Promise<void> { await super.removeAllAccounts() await this.setActiveAccount(undefined) } /** * Removes a peer and all the accounts that have been connected through that peer * * @param peer Peer to be removed */ public async removePeer( peer: ExtendedPeerInfo, sendDisconnectToPeer: boolean = false ): Promise<void> { const transport = await this.transport const removePeerResult = transport.removePeer(peer) await this.removeAccountsForPeers([peer]) if (sendDisconnectToPeer) { await this.sendDisconnectToPeer(peer, transport) } return removePeerResult } /** * Remove all peers and all accounts that have been connected through those peers */ public async removeAllPeers(sendDisconnectToPeers: boolean = false): Promise<void> { const transport = await this.transport const peers: ExtendedPeerInfo[] = await transport.getPeers() const removePeerResult = transport.removeAllPeers() await this.removeAccountsForPeers(peers) if (sendDisconnectToPeers) { const disconnectPromises = peers.map((peer) => this.sendDisconnectToPeer(peer, transport)) await Promise.all(disconnectPromises) } return removePeerResult } /** * Allows the user to subscribe to specific events that are fired in the SDK * * @param internalEvent The event to subscribe to * @param eventCallback The callback that will be called when the event occurs */ public async subscribeToEvent<K extends BeaconEvent>( internalEvent: K, eventCallback: BeaconEventHandlerFunction<BeaconEventType[K]> ): Promise<void> { await this.events.on(internalEvent, eventCallback) } /** * Check if we have permissions to send the specific message type to the active account. * If no active account is set, only permission requests are allowed. * * @param type The type of the message */ public async checkPermissions(type: BeaconMessageType): Promise<boolean> { if (type === BeaconMessageType.PermissionRequest) { return true } const activeAccount: AccountInfo | undefined = await this.getActiveAccount() if (!activeAccount) { throw await this.sendInternalError('No active account set!') } const permissions = activeAccount.scopes switch (type) { case BeaconMessageType.OperationRequest: return permissions.includes(PermissionScope.OPERATION_REQUEST) case BeaconMessageType.SignPayloadRequest: return permissions.includes(PermissionScope.SIGN) // TODO: ENCRYPTION // case BeaconMessageType.EncryptPayloadRequest: // return permissions.includes(PermissionScope.ENCRYPT) case BeaconMessageType.BroadcastRequest: return true default: return false } } /** * Send a permission request to the DApp. This should be done as the first step. The wallet will respond * with an publicKey and permissions that were given. The account returned will be set as the "activeAccount" * and will be used for the following requests. * * @param input The message details we need to prepare the PermissionRequest message. */ public async requestPermissions( input?: RequestPermissionInput ): Promise<PermissionResponseOutput> { const request: PermissionRequestInput = { appMetadata: await this.getOwnAppMetadata(), type: BeaconMessageType.PermissionRequest, network: input && input.network ? input.network : { type: NetworkType.MAINNET }, scopes: input && input.scopes ? input.scopes : [PermissionScope.OPERATION_REQUEST, PermissionScope.SIGN] } const { message, connectionInfo } = await this.makeRequest< PermissionRequest, PermissionResponse >(request).catch(async (requestError: ErrorResponse) => { throw await this.handleRequestError(request, requestError) }) // TODO: Migration code. Remove sometime after 1.0.0 release. const publicKey = message.publicKey || (message as any).pubkey || (message as any).pubKey const address = await getAddressFromPublicKey(publicKey) const accountInfo: AccountInfo = { accountIdentifier: await getAccountIdentifier(address, message.network), senderId: message.senderId, origin: { type: connectionInfo.origin, id: connectionInfo.id }, address, publicKey, network: message.network, scopes: message.scopes, threshold: message.threshold, connectedAt: new Date().getTime() } await this.accountManager.addAccount(accountInfo) await this.setActiveAccount(accountInfo) const output: PermissionResponseOutput = { ...message, address, accountInfo } await this.notifySuccess(request, { account: accountInfo, output, blockExplorer: this.blockExplorer, connectionContext: connectionInfo, walletInfo: await this.getWalletInfo() }) return output } /** * This method will send a "SignPayloadRequest" to the wallet. This method is meant to be used to sign * arbitrary data (eg. a string). It will return the signature in the format of "edsig..." * * @param input The message details we need to prepare the SignPayloadRequest message. */ public async requestSignPayload( input: RequestSignPayloadInput ): Promise<SignPayloadResponseOutput> { if (!input.payload) { throw await this.sendInternalError('Payload must be provided') } const activeAccount: AccountInfo | undefined = await this.getActiveAccount() if (!activeAccount) { throw await this.sendInternalError('No active account!') } const payload = input.payload if (typeof payload !== 'string') { throw new Error('Payload must be a string') } const signingType = ((): SigningType => { switch (input.signingType) { case SigningType.OPERATION: if (!payload.startsWith('03')) { throw new Error( 'When using signing type "OPERATION", the payload must start with prefix "03"' ) } return SigningType.OPERATION case SigningType.MICHELINE: if (!payload.startsWith('05')) { throw new Error( 'When using signing type "MICHELINE", the payload must start with prefix "05"' ) } return SigningType.MICHELINE case SigningType.RAW: default: return SigningType.RAW } })() const request: SignPayloadRequestInput = { type: BeaconMessageType.SignPayloadRequest, signingType, payload, sourceAddress: input.sourceAddress || activeAccount.address } const { message, connectionInfo } = await this.makeRequest< SignPayloadRequest, SignPayloadResponse >(request).catch(async (requestError: ErrorResponse) => { throw await this.handleRequestError(request, requestError) }) await this.notifySuccess(request, { account: activeAccount, output: message, connectionContext: connectionInfo, walletInfo: await this.getWalletInfo() }) return message } /** * This method will send an "EncryptPayloadRequest" to the wallet. This method is meant to be used to encrypt or decrypt * arbitrary data (eg. a string). It will return the encrypted or decrypted payload * * @param input The message details we need to prepare the EncryptPayloadRequest message. */ // TODO: ENCRYPTION // public async requestEncryptPayload( // input: RequestEncryptPayloadInput // ): Promise<EncryptPayloadResponseOutput> { // if (!input.payload) { // throw await this.sendInternalError('Payload must be provided') // } // const activeAccount: AccountInfo | undefined = await this.getActiveAccount() // if (!activeAccount) { // throw await this.sendInternalError('No active account!') // } // const payload = input.payload // if (typeof payload !== 'string') { // throw new Error('Payload must be a string') // } // if (typeof input.encryptionCryptoOperation === 'undefined') { // throw new Error('encryptionCryptoOperation must be defined') // } // if (typeof input.encryptionType === 'undefined') { // throw new Error('encryptionType must be defined') // } // const request: EncryptPayloadRequestInput = { // type: BeaconMessageType.EncryptPayloadRequest, // cryptoOperation: input.encryptionCryptoOperation, // encryptionType: input.encryptionType, // payload, // sourceAddress: input.sourceAddress || activeAccount.address // } // const { message, connectionInfo } = await this.makeRequest< // EncryptPayloadRequest, // EncryptPayloadResponse // >(request).catch(async (requestError: ErrorResponse) => { // throw await this.handleRequestError(request, requestError) // }) // await this.notifySuccess(request, { // account: activeAccount, // output: message, // connectionContext: connectionInfo, // walletInfo: await this.getWalletInfo() // }) // return message // } /** * This method sends an OperationRequest to the wallet. This method should be used for all kinds of operations, * eg. transaction or delegation. Not all properties have to be provided. Data like "counter" and fees will be * fetched and calculated by the wallet (but they can still be provided if required). * * @param input The message details we need to prepare the OperationRequest message. */ public async requestOperation(input: RequestOperationInput): Promise<OperationResponseOutput> { if (!input.operationDetails) { throw await this.sendInternalError('Operation details must be provided') } const activeAccount: AccountInfo | undefined = await this.getActiveAccount() if (!activeAccount) { throw await this.sendInternalError('No active account!') } const request: OperationRequestInput = { type: BeaconMessageType.OperationRequest, network: activeAccount.network || { type: NetworkType.MAINNET }, operationDetails: input.operationDetails, sourceAddress: activeAccount.address || '' } const { message, connectionInfo } = await this.makeRequest<OperationRequest, OperationResponse>( request ).catch(async (requestError: ErrorResponse) => { throw await this.handleRequestError(request, requestError) }) await this.notifySuccess(request, { account: activeAccount, output: message, blockExplorer: this.blockExplorer, connectionContext: connectionInfo, walletInfo: await this.getWalletInfo() }) return message } /** * Sends a "BroadcastRequest" to the wallet. This method can be used to inject an already signed transaction * to the network. * * @param input The message details we need to prepare the BroadcastRequest message. */ public async requestBroadcast(input: RequestBroadcastInput): Promise<BroadcastResponseOutput> { if (!input.signedTransaction) { throw await this.sendInternalError('Signed transaction must be provided') } const network = input.network || { type: NetworkType.MAINNET } const request: BroadcastRequestInput = { type: BeaconMessageType.BroadcastRequest, network, signedTransaction: input.signedTransaction } const { message, connectionInfo } = await this.makeRequest<BroadcastRequest, BroadcastResponse>( request ).catch(async (requestError: ErrorResponse) => { throw await this.handleRequestError(request, requestError) }) await this.notifySuccess(request, { network, output: message, blockExplorer: this.blockExplorer, connectionContext: connectionInfo, walletInfo: await this.getWalletInfo() }) return message } protected async setActivePeer( peer?: ExtendedPostMessagePairingResponse | ExtendedP2PPairingResponse ): Promise<void> { if (this._activePeer.isSettled()) { // If the promise has already been resolved we need to create a new one. this._activePeer = ExposedPromise.resolve< ExtendedPostMessagePairingResponse | ExtendedP2PPairingResponse | undefined >(peer) } else { this._activePeer.resolve(peer) } if (peer) { await this.initInternalTransports() if (peer.type === 'postmessage-pairing-response') { await this.setTransport(this.postMessageTransport) } else if (peer.type === 'p2p-pairing-response') { await this.setTransport(this.p2pTransport) } } return } /** * A "setter" for when the transport needs to be changed. */ protected async setTransport(transport?: Transport<any>): Promise<void> { if (!transport) { this._initPromise = undefined } return super.setTransport(transport) } /** * This method will emit an internal error message. * * @param errorMessage The error message to send. */ private async sendInternalError(errorMessage: string): Promise<void> { await this.events.emit(BeaconEvent.INTERNAL_ERROR, { text: errorMessage }) throw new Error(errorMessage) } /** * This method will remove all accounts associated with a specific peer. * * @param peersToRemove An array of peers for which accounts should be removed */ private async removeAccountsForPeers(peersToRemove: ExtendedPeerInfo[]): Promise<void> { const accounts = await this.accountManager.getAccounts() const peerIdsToRemove = peersToRemove.map((peer) => peer.senderId) // Remove all accounts with origin of the specified peer const accountsToRemove = accounts.filter((account) => peerIdsToRemove.includes(account.senderId) ) const accountIdentifiersToRemove = accountsToRemove.map( (accountInfo) => accountInfo.accountIdentifier ) await this.accountManager.removeAccounts(accountIdentifiersToRemove) // Check if one of the accounts that was removed was the active account and if yes, set it to undefined const activeAccount: AccountInfo | undefined = await this.getActiveAccount() if (activeAccount) { if (accountIdentifiersToRemove.includes(activeAccount.accountIdentifier)) { await this.setActiveAccount(undefined) } } } /** * This message handles errors that we receive from the wallet. * * @param request The request we sent * @param beaconError The error we received */ private async handleRequestError( request: BeaconRequestInputMessage, beaconError: ErrorResponse ): Promise<void> { logger.error('handleRequestError', 'error response', beaconError) if (beaconError.errorType) { const buttons: AlertButton[] = [] if (beaconError.errorType === BeaconErrorType.NO_PRIVATE_KEY_FOUND_ERROR) { const actionCallback = async (): Promise<void> => { const operationRequest: OperationRequestInput = request as OperationRequestInput // if the account we requested is not available, we remove it locally let accountInfo: AccountInfo | undefined if (operationRequest.sourceAddress && operationRequest.network) { const accountIdentifier = await getAccountIdentifier( operationRequest.sourceAddress, operationRequest.network ) accountInfo = await this.getAccount(accountIdentifier) if (accountInfo) { await this.removeAccount(accountInfo.accountIdentifier) } } } buttons.push({ text: 'Remove account', actionCallback }) } const peer = await this.getPeer() const activeAccount = await this.getActiveAccount() // If we sent a permission request, received an error and there is no active account, we need to reset the DAppClient. // This most likely means that the user rejected the first permission request after pairing a wallet, so we "forget" the paired wallet to allow the user to pair again. if ( request.type === BeaconMessageType.PermissionRequest && (await this.getActiveAccount()) === undefined ) { this._initPromise = undefined this.postMessageTransport = undefined this.p2pTransport = undefined await this.setTransport() await this.setActivePeer() } this.events .emit( messageEvents[request.type].error, { errorResponse: beaconError, walletInfo: await this.getWalletInfo(peer, activeAccount) }, buttons ) .catch((emitError) => logger.error('handleRequestError', emitError)) throw BeaconError.getError(beaconError.errorType, beaconError.errorData) } throw beaconError } /** * This message will send an event when we receive a successful response to one of the requests we sent. * * @param request The request we sent * @param response The response we received */ private async notifySuccess( request: BeaconRequestInputMessage, response: | { account: AccountInfo output: PermissionResponseOutput blockExplorer: BlockExplorer connectionContext: ConnectionContext walletInfo: WalletInfo } | { account: AccountInfo output: OperationResponseOutput blockExplorer: BlockExplorer connectionContext: ConnectionContext walletInfo: WalletInfo } | { output: SignPayloadResponseOutput connectionContext: ConnectionContext walletInfo: WalletInfo } // | { // output: EncryptPayloadResponseOutput // connectionContext: ConnectionContext // walletInfo: WalletInfo // } | { network: Network output: BroadcastResponseOutput blockExplorer: BlockExplorer connectionContext: ConnectionContext walletInfo: WalletInfo } ): Promise<void> { this.events .emit(messageEvents[request.type].success, response) .catch((emitError) => console.warn(emitError)) } private async getWalletInfo(peer?: PeerInfo, account?: AccountInfo): Promise<WalletInfo> { const selectedAccount = account ? account : await this.getActiveAccount() const selectedPeer = peer ? peer : await this.getPeer(selectedAccount) let walletInfo: WalletInfo | undefined if (selectedAccount) { walletInfo = await this.appMetadataManager.getAppMetadata(selectedAccount.senderId) } const typedPeer: PostMessagePairingResponse = selectedPeer as any if (!walletInfo) { walletInfo = { name: typedPeer.name, icon: typedPeer.icon } } const lowerCaseCompare = (str1?: string, str2?: string): boolean => { if (str1 && str2) { return str1.toLowerCase() === str2.toLowerCase() } return false } let selectedApp: WebApp | App | DesktopApp | ExtensionApp | undefined let type: 'extension' | 'mobile' | 'web' | 'desktop' | undefined // TODO: Remove once all wallets send the icon? if (iOSList.find((app) => lowerCaseCompare(app.name, walletInfo?.name))) { selectedApp = iOSList.find((app) => lowerCaseCompare(app.name, walletInfo?.name)) type = 'mobile' } else if (webList.find((app) => lowerCaseCompare(app.name, walletInfo?.name))) { selectedApp = webList.find((app) => lowerCaseCompare(app.name, walletInfo?.name)) type = 'web' } else if (desktopList.find((app) => lowerCaseCompare(app.name, walletInfo?.name))) { selectedApp = desktopList.find((app) => lowerCaseCompare(app.name, walletInfo?.name)) type = 'desktop' } else if (extensionList.find((app) => lowerCaseCompare(app.name, walletInfo?.name))) { selectedApp = extensionList.find((app) => lowerCaseCompare(app.name, walletInfo?.name)) type = 'extension' } if (selectedApp) { let deeplink: string | undefined if (selectedApp.hasOwnProperty('links')) { deeplink = (selectedApp as WebApp).links[ selectedAccount?.network.type ?? this.preferredNetwork ] } else if (selectedApp.hasOwnProperty('deepLink')) { deeplink = (selectedApp as App).deepLink } return { name: walletInfo.name, icon: walletInfo.icon ?? selectedApp.logo, deeplink, type } } return walletInfo } private async getPeer(account?: AccountInfo): Promise<PeerInfo> { let peer: PeerInfo | undefined if (account) { logger.log('getPeer', 'We have an account', account) const postMessagePeers: ExtendedPostMessagePairingResponse[] = (await this.postMessageTransport?.getPeers()) ?? [] const p2pPeers: ExtendedP2PPairingResponse[] = (await this.p2pTransport?.getPeers()) ?? [] const peers = [...postMessagePeers, ...p2pPeers] logger.log('getPeer', 'Found peers', peers, account) peer = peers.find((peerEl) => peerEl.senderId === account.senderId) if (!peer) { // We could not find an exact match for a sender, so we most likely received it over a relay peer = peers.find((peerEl) => (peerEl as any).extensionId === account.origin.id) } } else { peer = await this._activePeer.promise logger.log('getPeer', 'Active peer', peer) } if (!peer) { throw new Error('No matching peer found.') } return peer } /** * This method handles sending of requests to the DApp. It makes sure that the DAppClient is initialized and connected * to the transport. After that rate limits and permissions will be checked, an ID is attached and the request is sent * to the DApp over the transport. * * @param requestInput The BeaconMessage to be sent to the wallet * @param account The account that the message will be sent to */ private async makeRequest<T extends BeaconRequestInputMessage, U extends BeaconMessage>( requestInput: Optional<T, IgnoredRequestInputProperties> ): Promise<{ message: U connectionInfo: ConnectionContext }> { const messageId = await generateGUID() console.time(messageId) logger.log('makeRequest', 'starting') await this.init() console.timeLog(messageId, 'init done') logger.log('makeRequest', 'after init') if (await this.addRequestAndCheckIfRateLimited()) { this.events .emit(BeaconEvent.LOCAL_RATE_LIMIT_REACHED) .catch((emitError) => console.warn(emitError)) throw new Error('rate limit reached') } if (!(await this.checkPermissions(requestInput.type))) { this.events.emit(BeaconEvent.NO_PERMISSIONS).catch((emitError) => console.warn(emitError)) throw new Error('No permissions to send this request to wallet!') } if (!this.beaconId) { throw await this.sendInternalError('BeaconID not defined') } const request: Optional<T, IgnoredRequestInputProperties> & Pick<U, IgnoredRequestInputProperties> = { id: messageId, version: BEACON_VERSION, senderId: await getSenderId(await this.beaconId), ...requestInput } const exposed = new ExposedPromise< { message: BeaconMessage; connectionInfo: ConnectionContext }, ErrorResponse >() this.addOpenRequest(request.id, exposed) const payload = await new Serializer().serialize(request) const account = await this.getActiveAccount() const peer = await this.getPeer(account) const walletInfo = await this.getWalletInfo(peer, account) logger.log('makeRequest', 'sending message', request) console.timeLog(messageId, 'sending') try { await (await this.transport).send(payload, peer) } catch (sendError) { this.events.emit(BeaconEvent.INTERNAL_ERROR, { text: 'Unable to send message. If this problem persists, please reset the connection and pair your wallet again.', buttons: [ { text: 'Reset Connection', actionCallback: async (): Promise<void> => { await closeToast() this.disconnect() } } ] }) console.timeLog(messageId, 'send error') throw sendError } console.timeLog(messageId, 'sent') this.events .emit(messageEvents[requestInput.type].sent, { walletInfo: { ...walletInfo, name: walletInfo.name ?? 'Wallet' }, extraInfo: { resetCallback: async () => { this.disconnect() } } }) .catch((emitError) => console.warn(emitError)) // eslint-disable-next-line @typescript-eslint/no-explicit-any return exposed.promise as any // TODO: fix type } private async disconnect() { this.postMessageTransport = undefined this.p2pTransport = undefined await Promise.all([this.clearActiveAccount(), (await this.transport).disconnect()]) } /** * Adds a requests to the "openRequests" set so we know what messages have already been answered/handled. * * @param id The ID of the message * @param promise A promise that resolves once the response for that specific message is received */ private addOpenRequest( id: string, promise: ExposedPromise< { message: BeaconMessage; connectionInfo: ConnectionContext }, ErrorResponse > ): void { logger.log('addOpenRequest', this.name, `adding request ${id} and waiting for answer`) this.openRequests.set(id, promise) } }
the_stack
import fs from 'fs'; import path from 'path'; import {WritingMode, shapeIcon, shapeText, fitIconToText, PositionedIcon, Shaping} from './shaping'; import Formatted, {FormattedSection} from '../style-spec/expression/types/formatted'; import ResolvedImage from '../style-spec/expression/types/resolved_image'; import expectedJson from '../../test/expected/text-shaping-linebreak.json'; import {ImagePosition} from '../render/image_atlas'; import {StyleImage} from '../style/style_image'; let UPDATE = false; if (typeof process !== 'undefined' && process.env !== undefined) { UPDATE = !!process.env.UPDATE; } describe('shaping', () => { const oneEm = 24; const layoutTextSize = 16; const layoutTextSizeThisZoom = 16; const fontStack = 'Test'; const glyphs = { 'Test': require('../../test/fixtures/fontstack-glyphs.json') }; const glyphPositions = glyphs; const images = { 'square': new ImagePosition({x: 0, y: 0, w: 16, h: 16}, {pixelRatio: 1, version: 1} as StyleImage), 'tall': new ImagePosition({x: 0, y: 0, w: 16, h: 32}, {pixelRatio: 1, version: 1} as StyleImage), 'wide': new ImagePosition({x: 0, y: 0, w: 32, h: 16}, {pixelRatio: 1, version: 1} as StyleImage), }; const sectionForImage = (name) => { return new FormattedSection('', ResolvedImage.fromString(name), null, null, null); }; const sectionForText = (name, scale?) => { return new FormattedSection(name, null, scale, null, null); }; let shaped; JSON.parse('{}'); shaped = shapeText(Formatted.fromString(`hi${String.fromCharCode(0)}`), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0 * oneEm, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-null.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual( require('../../test/expected/text-shaping-null.json') ); // Default shaping. shaped = shapeText(Formatted.fromString('abcde'), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0 * oneEm, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-default.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual( require('../../test/expected/text-shaping-default.json') ); // Letter spacing. shaped = shapeText(Formatted.fromString('abcde'), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0.125 * oneEm, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-spacing.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual( require('../../test/expected/text-shaping-spacing.json') ); // Line break. shaped = shapeText(Formatted.fromString('abcde abcde'), glyphs, glyphPositions, images, fontStack, 4 * oneEm, oneEm, 'center', 'center', 0 * oneEm, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-linebreak.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual(expectedJson); const expectedNewLine = require('../../test/expected/text-shaping-newline.json'); shaped = shapeText(Formatted.fromString('abcde\nabcde'), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-newline.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual(expectedNewLine); shaped = shapeText(Formatted.fromString('abcde\r\nabcde'), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); expect(shaped.positionedLines).toEqual(expectedNewLine.positionedLines); const expectedNewLinesInMiddle = require('../../test/expected/text-shaping-newlines-in-middle.json'); shaped = shapeText(Formatted.fromString('abcde\n\nabcde'), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-newlines-in-middle.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual(expectedNewLinesInMiddle); // Prefer zero width spaces when breaking lines. Zero width spaces are used by Mapbox data sources as a hint that // a position is ideal for breaking. const expectedZeroWidthSpaceBreak = require('../../test/expected/text-shaping-zero-width-space.json'); shaped = shapeText(Formatted.fromString('三三\u200b三三\u200b三三\u200b三三三三三三\u200b三三'), glyphs, glyphPositions, images, fontStack, 5 * oneEm, oneEm, 'center', 'center', 0, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-zero-width-space.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual(expectedZeroWidthSpaceBreak); // Null shaping. shaped = shapeText(Formatted.fromString(''), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0 * oneEm, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); expect(false).toBe(shaped); shaped = shapeText(Formatted.fromString(String.fromCharCode(0)), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0 * oneEm, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); expect(false).toBe(shaped); // https://github.com/mapbox/mapbox-gl-js/issues/3254 shaped = shapeText(Formatted.fromString(' foo bar\n'), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0 * oneEm, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); const shaped2 = shapeText(Formatted.fromString('foo bar'), glyphs, glyphPositions, images, fontStack, 15 * oneEm, oneEm, 'center', 'center', 0 * oneEm, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom) as Shaping; expect(shaped.positionedLines).toEqual(shaped2.positionedLines); test('basic image shaping', () => { const shaped = shapeText(new Formatted([sectionForImage('square')]), glyphs, glyphPositions, images, fontStack, 5 * oneEm, oneEm, 'center', 'center', 0, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom) as Shaping; expect(shaped.top).toEqual(-12); // 1em line height expect(shaped.left).toEqual(-10.5); // 16 - 2px border * 1.5 scale factor }); test('images in horizontal layout', () => { const expectedImagesHorizontal = require('../../test/expected/text-shaping-images-horizontal.json'); const horizontalFormatted = new Formatted([ sectionForText('Foo'), sectionForImage('square'), sectionForImage('wide'), sectionForText('\n'), sectionForImage('tall'), sectionForImage('square'), sectionForText(' bar'), ]); const shaped = shapeText(horizontalFormatted, glyphs, glyphPositions, images, fontStack, 5 * oneEm, oneEm, 'center', 'center', 0, [0, 0], WritingMode.horizontal, false, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-images-horizontal.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual(expectedImagesHorizontal); }); test('images in vertical layout', () => { const expectedImagesVertical = require('../../test/expected/text-shaping-images-vertical.json'); const horizontalFormatted = new Formatted([ sectionForText('三'), sectionForImage('square'), sectionForImage('wide'), sectionForText('\u200b'), sectionForImage('tall'), sectionForImage('square'), sectionForText('三'), ]); const shaped = shapeText(horizontalFormatted, glyphs, glyphPositions, images, fontStack, 5 * oneEm, oneEm, 'center', 'center', 0, [0, 0], WritingMode.vertical, true, 'point', layoutTextSize, layoutTextSizeThisZoom); if (UPDATE) fs.writeFileSync(path.resolve(__dirname, '../../test/expected/text-shaping-images-vertical.json'), JSON.stringify(shaped, null, 2)); expect(shaped).toEqual(expectedImagesVertical); }); }); describe('shapeIcon', () => { const imagePosition = new ImagePosition({x: 0, y: 0, w: 22, h: 22}, {pixelRatio: 1, version: 1} as StyleImage); const image = Object.freeze({ content: undefined, stretchX: undefined, stretchY: undefined, paddedRect: Object.freeze({x: 0, y: 0, w: 22, h: 22}), pixelRatio: 1, version: 1 }); test('text-anchor: center', () => { expect(shapeIcon(imagePosition, [ 0, 0 ], 'center')).toEqual({ top: -10, bottom: 10, left: -10, right: 10, image }); expect(shapeIcon(imagePosition, [ 4, 7 ], 'center')).toEqual({ top: -3, bottom: 17, left: -6, right: 14, image }); }); test('text-anchor: left', () => { expect(shapeIcon(imagePosition, [ 0, 0 ], 'left')).toEqual({ top: -10, bottom: 10, left: 0, right: 20, image }); expect(shapeIcon(imagePosition, [ 4, 7 ], 'left')).toEqual({ top: -3, bottom: 17, left: 4, right: 24, image }); }); test('text-anchor: bottom-right', () => { expect(shapeIcon(imagePosition, [ 0, 0 ], 'bottom-right')).toEqual({ top: -20, bottom: 0, left: -20, right: 0, image }); expect(shapeIcon(imagePosition, [ 4, 7 ], 'bottom-right')).toEqual({ top: -13, bottom: 7, left: -16, right: 4, image }); }); }); describe('fitIconToText', () => { const glyphSize = 24; const shapedIcon = Object.freeze({ top: -10, bottom: 10, left: -10, right: 10, collisionPadding: undefined, image: Object.freeze({ pixelRatio: 1, displaySize: [ 20, 20 ], paddedRect: Object.freeze({x: 0, y: 0, w: 22, h: 22}) }) }) as PositionedIcon; const shapedText = Object.freeze({ top: -10, bottom: 30, left: -60, right: 20 }) as Shaping; test('icon-text-fit: width', () => { expect( fitIconToText(shapedIcon, shapedText, 'width', [0, 0, 0, 0], [0, 0], 24 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: 0, right: 20, bottom: 20, left: -60 }); expect( fitIconToText(shapedIcon, shapedText, 'width', [0, 0, 0, 0], [3, 7], 24 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: 7, right: 23, bottom: 27, left: -57 }); expect( fitIconToText(shapedIcon, shapedText, 'width', [0, 0, 0, 0], [0, 0], 12 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -5, right: 10, bottom: 15, left: -30 }); // Ignores padding for top/bottom, since the icon is only stretched to the text's width but not height expect( fitIconToText(shapedIcon, shapedText, 'width', [ 5, 10, 5, 10 ], [0, 0], 12 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -5, right: 20, bottom: 15, left: -40 }); }); test('icon-text-fit: height', () => { expect( fitIconToText(shapedIcon, shapedText, 'height', [0, 0, 0, 0], [0, 0], 24 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -10, right: -10, bottom: 30, left: -30 }); expect( fitIconToText(shapedIcon, shapedText, 'height', [0, 0, 0, 0], [3, 7], 24 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -3, right: -7, bottom: 37, left: -27 }); expect( fitIconToText(shapedIcon, shapedText, 'height', [0, 0, 0, 0], [0, 0], 12 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -5, right: 0, bottom: 15, left: -20 }); // Ignores padding for left/right, since the icon is only stretched to the text's height but not width expect( fitIconToText(shapedIcon, shapedText, 'height', [ 5, 10, 5, 10 ], [0, 0], 12 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -10, right: 0, bottom: 20, left: -20 }); }); test('icon-text-fit: both', () => { expect( fitIconToText(shapedIcon, shapedText, 'both', [0, 0, 0, 0], [0, 0], 24 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -10, right: 20, bottom: 30, left: -60 }); expect( fitIconToText(shapedIcon, shapedText, 'both', [0, 0, 0, 0], [3, 7], 24 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -3, right: 23, bottom: 37, left: -57 }); expect( fitIconToText(shapedIcon, shapedText, 'both', [0, 0, 0, 0], [0, 0], 12 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -5, right: 10, bottom: 15, left: -30 }); expect( fitIconToText(shapedIcon, shapedText, 'both', [ 5, 10, 5, 10 ], [0, 0], 12 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -10, right: 20, bottom: 20, left: -40 }); expect( fitIconToText(shapedIcon, shapedText, 'both', [ 0, 5, 10, 15 ], [0, 0], 12 / glyphSize) ).toEqual({ image: shapedIcon.image, collisionPadding: undefined, top: -5, right: 15, bottom: 25, left: -45 }); }); });
the_stack
import { XMLBuilderCB, AttributesObject, PIObject, DTDOptions, XMLBuilder, XMLBuilderCBOptions, XMLBuilderCreateOptions, DefaultXMLBuilderCBOptions, ExpandObject, XMLBuilderCBCreateOptions, XMLBuilderOptions, BaseCBWriterOptions } from "../interfaces" import { applyDefaults, isString, isObject } from "@oozcitak/util" import { fragment, create } from "./BuilderFunctions" import { xml_isName, xml_isLegalChar, xml_isPubidChar } from "@oozcitak/dom/lib/algorithm" import { namespace as infraNamespace } from "@oozcitak/infra" import { NamespacePrefixMap } from "@oozcitak/dom/lib/serializer/NamespacePrefixMap" import { Comment, Text, ProcessingInstruction, CDATASection, DocumentType, Element, Node } from "@oozcitak/dom/lib/dom/interfaces" import { LocalNameSet } from "@oozcitak/dom/lib/serializer/LocalNameSet" import { Guard } from "@oozcitak/dom/lib/util" import { BaseCBWriter } from "../writers/BaseCBWriter" import { XMLCBWriter } from "../writers/XMLCBWriter" import { JSONCBWriter } from "../writers/JSONCBWriter" import { YAMLCBWriter } from "../writers/YAMLCBWriter" import { EventEmitter } from "events" /** * Stores the last generated prefix. An object is used instead of a number so * that the value can be passed by reference. */ type PrefixIndex = { value: number } /** * Represents a readable XML document stream. */ export class XMLBuilderCBImpl extends EventEmitter implements XMLBuilderCB { private static _VoidElementNames = new Set(['area', 'base', 'basefont', 'bgsound', 'br', 'col', 'embed', 'frame', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr']) private _options: Required<XMLBuilderCBOptions> private _builderOptions: XMLBuilderCreateOptions private _writer: BaseCBWriter<BaseCBWriterOptions> private _fragment: boolean private _hasDeclaration = false private _docTypeName = "" private _hasDocumentElement = false private _currentElement?: XMLBuilder private _currentElementSerialized = false private _openTags: Array<[string, string | null, NamespacePrefixMap, boolean]> = [] private _prefixMap: NamespacePrefixMap private _prefixIndex: PrefixIndex private _ended = false /** * Initializes a new instance of `XMLStream`. * * @param options - stream writer options * @param fragment - whether to create fragment stream or a document stream * * @returns XML stream */ public constructor(options?: XMLBuilderCBCreateOptions, fragment = false) { super() this._fragment = fragment // provide default options this._options = applyDefaults(options || {}, DefaultXMLBuilderCBOptions ) as Required<XMLBuilderCBOptions> this._builderOptions = { defaultNamespace: this._options.defaultNamespace, namespaceAlias: this._options.namespaceAlias } if (this._options.format === "json") { this._writer = new JSONCBWriter(this._options) } else if (this._options.format === "yaml") { this._writer = new YAMLCBWriter(this._options) } else { this._writer = new XMLCBWriter(this._options) } // automatically create listeners for callbacks passed via options if (this._options.data !== undefined) { this.on("data", this._options.data) } if (this._options.end !== undefined) { this.on("end", this._options.end) } if (this._options.error !== undefined) { this.on("error", this._options.error) } this._prefixMap = new NamespacePrefixMap() this._prefixMap.set("xml", infraNamespace.XML) this._prefixIndex = { value: 1 } this._push(this._writer.frontMatter()) } /** @inheritdoc */ ele(p1: string | null | ExpandObject, p2?: AttributesObject | string, p3?: AttributesObject): this { // parse if JS object or XML or JSON string if (isObject(p1) || (isString(p1) && (/^\s*</.test(p1) || /^\s*[\{\[]/.test(p1) || /^(\s*|(#.*)|(%.*))*---/.test(p1)))) { const frag = fragment().set(this._options as unknown as Partial<XMLBuilderOptions>) try { frag.ele(p1 as any) } catch (err) { this.emit("error", err) return this } for (const node of frag.node.childNodes) { this._fromNode(node) } return this } this._serializeOpenTag(true) if (!this._fragment && this._hasDocumentElement && this._writer.level === 0) { this.emit("error", new Error("Document cannot have multiple document element nodes.")) return this } try { this._currentElement = fragment(this._builderOptions).ele(p1 as any, p2 as any, p3 as any) } catch (err) { this.emit("error", err) return this } if (!this._fragment && !this._hasDocumentElement && this._docTypeName !== "" && (this._currentElement.node as Element)._qualifiedName !== this._docTypeName) { this.emit("error", new Error("Document element name does not match DocType declaration name.")) return this } this._currentElementSerialized = false if (!this._fragment) { this._hasDocumentElement = true } return this } /** @inheritdoc */ att(p1: AttributesObject | string | null, p2?: string, p3?: string): this { if (this._currentElement === undefined) { this.emit("error", new Error("Cannot insert an attribute node as child of a document node.")) return this } try { this._currentElement.att(p1 as any, p2 as any, p3 as any) } catch (err) { this.emit("error", err) return this } return this } /** @inheritdoc */ com(content: string): this { this._serializeOpenTag(true) let node: Comment try { node = fragment(this._builderOptions).com(content).first().node as Comment } catch (err) { /* istanbul ignore next */ this.emit("error", err) /* istanbul ignore next */ return this } if (this._options.wellFormed && (!xml_isLegalChar(node.data) || node.data.indexOf("--") !== -1 || node.data.endsWith("-"))) { this.emit("error", new Error("Comment data contains invalid characters (well-formed required).")) return this } this._push(this._writer.comment(node.data)) return this } /** @inheritdoc */ txt(content: string): this { if (!this._fragment && this._currentElement === undefined) { this.emit("error", new Error("Cannot insert a text node as child of a document node.")) return this } this._serializeOpenTag(true) let node: Text try { node = fragment(this._builderOptions).txt(content).first().node as Text } catch (err) { /* istanbul ignore next */ this.emit("error", err) /* istanbul ignore next */ return this } if (this._options.wellFormed && !xml_isLegalChar(node.data)) { this.emit("error", new Error("Text data contains invalid characters (well-formed required).")) return this } const markup = node.data.replace(/(?!&(lt|gt|amp|apos|quot);)&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') this._push(this._writer.text(markup)) return this } /** @inheritdoc */ ins(target: string | PIObject, content: string = ''): this { this._serializeOpenTag(true) let node: ProcessingInstruction try { node = fragment(this._builderOptions).ins(target as any, content).first().node as ProcessingInstruction } catch (err) { /* istanbul ignore next */ this.emit("error", err) /* istanbul ignore next */ return this } if (this._options.wellFormed && (node.target.indexOf(":") !== -1 || (/^xml$/i).test(node.target))) { this.emit("error", new Error("Processing instruction target contains invalid characters (well-formed required).")) return this } if (this._options.wellFormed && !xml_isLegalChar(node.data)) { this.emit("error", Error("Processing instruction data contains invalid characters (well-formed required).")) return this } this._push(this._writer.instruction(node.target, node.data)) return this } /** @inheritdoc */ dat(content: string): this { this._serializeOpenTag(true) let node: CDATASection try { node = fragment(this._builderOptions).dat(content).first().node as CDATASection } catch (err) { this.emit("error", err) return this } this._push(this._writer.cdata(node.data)) return this } /** @inheritdoc */ dec(options: { version?: "1.0", encoding?: string, standalone?: boolean } = { version: "1.0" }): this { if (this._fragment) { this.emit("error", Error("Cannot insert an XML declaration into a document fragment.")) return this } if (this._hasDeclaration) { this.emit("error", Error("XML declaration is already inserted.")) return this } this._push(this._writer.declaration(options.version || "1.0", options.encoding, options.standalone)) this._hasDeclaration = true return this } /** @inheritdoc */ dtd(options: DTDOptions & { name: string }): this { if (this._fragment) { this.emit("error", Error("Cannot insert a DocType declaration into a document fragment.")) return this } if (this._docTypeName !== "") { this.emit("error", new Error("DocType declaration is already inserted.")) return this } if (this._hasDocumentElement) { this.emit("error", new Error("Cannot insert DocType declaration after document element.")) return this } let node: DocumentType try { node = create().dtd(options).first().node as DocumentType } catch (err) { this.emit("error", err) return this } if (this._options.wellFormed && !xml_isPubidChar(node.publicId)) { this.emit("error", new Error("DocType public identifier does not match PubidChar construct (well-formed required).")) return this } if (this._options.wellFormed && (!xml_isLegalChar(node.systemId) || (node.systemId.indexOf('"') !== -1 && node.systemId.indexOf("'") !== -1))) { this.emit("error", new Error("DocType system identifier contains invalid characters (well-formed required).")) return this } this._docTypeName = options.name this._push(this._writer.docType(options.name, node.publicId, node.systemId)) return this } /** @inheritdoc */ import(node: XMLBuilder): this { const frag = fragment().set(this._options as unknown as Partial<XMLBuilderOptions>) try { frag.import(node) } catch (err) { this.emit("error", err) return this } for (const node of frag.node.childNodes) { this._fromNode(node) } return this } /** @inheritdoc */ up(): this { this._serializeOpenTag(false) this._serializeCloseTag() return this } /** @inheritdoc */ end(): this { this._serializeOpenTag(false) while (this._openTags.length > 0) { this._serializeCloseTag() } this._push(null) return this } /** * Serializes the opening tag of an element node. * * @param hasChildren - whether the element node has child nodes */ private _serializeOpenTag(hasChildren: boolean): void { if (this._currentElementSerialized) return if (this._currentElement === undefined) return const node = this._currentElement.node as Element if (this._options.wellFormed && (node.localName.indexOf(":") !== -1 || !xml_isName(node.localName))) { this.emit("error", new Error("Node local name contains invalid characters (well-formed required).")) return } let qualifiedName = "" let ignoreNamespaceDefinitionAttribute = false let map = this._prefixMap.copy() let localPrefixesMap: { [key: string]: string } = {} let localDefaultNamespace = this._recordNamespaceInformation(node, map, localPrefixesMap) let inheritedNS = this._openTags.length === 0 ? null : this._openTags[this._openTags.length - 1][1] let ns = node.namespaceURI if (ns === null) ns = inheritedNS if (inheritedNS === ns) { if (localDefaultNamespace !== null) { ignoreNamespaceDefinitionAttribute = true } if (ns === infraNamespace.XML) { qualifiedName = "xml:" + node.localName } else { qualifiedName = node.localName } this._writer.beginElement(qualifiedName) this._push(this._writer.openTagBegin(qualifiedName)) } else { let prefix = node.prefix let candidatePrefix: string | null = null if (prefix !== null || ns !== localDefaultNamespace) { candidatePrefix = map.get(prefix, ns) } if (prefix === "xmlns") { if (this._options.wellFormed) { this.emit("error", new Error("An element cannot have the 'xmlns' prefix (well-formed required).")) return } candidatePrefix = prefix } if (candidatePrefix !== null) { qualifiedName = candidatePrefix + ':' + node.localName if (localDefaultNamespace !== null && localDefaultNamespace !== infraNamespace.XML) { inheritedNS = localDefaultNamespace || null } this._writer.beginElement(qualifiedName) this._push(this._writer.openTagBegin(qualifiedName)) } else if (prefix !== null) { if (prefix in localPrefixesMap) { prefix = this._generatePrefix(ns, map, this._prefixIndex) } map.set(prefix, ns) qualifiedName += prefix + ':' + node.localName this._writer.beginElement(qualifiedName) this._push(this._writer.openTagBegin(qualifiedName)) this._push(this._writer.attribute("xmlns:" + prefix, this._serializeAttributeValue(ns, this._options.wellFormed))) if (localDefaultNamespace !== null) { inheritedNS = localDefaultNamespace || null } } else if (localDefaultNamespace === null || (localDefaultNamespace !== null && localDefaultNamespace !== ns)) { ignoreNamespaceDefinitionAttribute = true qualifiedName += node.localName inheritedNS = ns this._writer.beginElement(qualifiedName) this._push(this._writer.openTagBegin(qualifiedName)) this._push(this._writer.attribute("xmlns", this._serializeAttributeValue(ns, this._options.wellFormed))) } else { qualifiedName += node.localName inheritedNS = ns this._writer.beginElement(qualifiedName) this._push(this._writer.openTagBegin(qualifiedName)) } } this._serializeAttributes(node, map, this._prefixIndex, localPrefixesMap, ignoreNamespaceDefinitionAttribute, this._options.wellFormed) const isHTML = (ns === infraNamespace.HTML) if (isHTML && !hasChildren && XMLBuilderCBImpl._VoidElementNames.has(node.localName)) { this._push(this._writer.openTagEnd(qualifiedName, true, true)) this._writer.endElement(qualifiedName) } else if (!isHTML && !hasChildren) { this._push(this._writer.openTagEnd(qualifiedName, true, false)) this._writer.endElement(qualifiedName) } else { this._push(this._writer.openTagEnd(qualifiedName, false, false)) } this._currentElementSerialized = true /** * Save qualified name, original inherited ns, original prefix map, and * hasChildren flag. */ this._openTags.push([qualifiedName, inheritedNS, this._prefixMap, hasChildren]) /** * New values of inherited namespace and prefix map will be used while * serializing child nodes. They will be returned to their original values * when this node is closed using the _openTags array item we saved above. */ if (this._isPrefixMapModified(this._prefixMap, map)) { this._prefixMap = map } /** * Calls following this will either serialize child nodes or close this tag. */ this._writer.level++ } /** * Serializes the closing tag of an element node. */ private _serializeCloseTag(): void { this._writer.level-- const lastEle = this._openTags.pop() /* istanbul ignore next */ if (lastEle === undefined) { this.emit("error", new Error("Last element is undefined.")) return } const [qualifiedName, ns, map, hasChildren] = lastEle /** * Restore original values of inherited namespace and prefix map. */ this._prefixMap = map if (!hasChildren) return this._push(this._writer.closeTag(qualifiedName)) this._writer.endElement(qualifiedName) } /** * Pushes data to internal buffer. * * @param data - data */ private _push(data: string | null): void { if (data === null) { this._ended = true this.emit("end") } else if (this._ended) { this.emit("error", new Error("Cannot push to ended stream.")) } else if (data.length !== 0) { this._writer.hasData = true this.emit("data", data, this._writer.level) } } /** * Reads and serializes an XML tree. * * @param node - root node */ private _fromNode(node: Node) { if (Guard.isElementNode(node)) { const name = node.prefix ? node.prefix + ":" + node.localName : node.localName if (node.namespaceURI !== null) { this.ele(node.namespaceURI, name) } else { this.ele(name) } for (const attr of node.attributes) { const name = attr.prefix ? attr.prefix + ":" + attr.localName : attr.localName if (attr.namespaceURI !== null) { this.att(attr.namespaceURI, name, attr.value) } else { this.att(name, attr.value) } } for (const child of node.childNodes) { this._fromNode(child) } this.up() } else if (Guard.isExclusiveTextNode(node) && node.data) { this.txt(node.data) } else if (Guard.isCommentNode(node)) { this.com(node.data) } else if (Guard.isCDATASectionNode(node)) { this.dat(node.data) } else if (Guard.isProcessingInstructionNode(node)) { this.ins(node.target, node.data) } } /** * Produces an XML serialization of the attributes of an element node. * * @param node - node to serialize * @param map - namespace prefix map * @param prefixIndex - generated namespace prefix index * @param localPrefixesMap - local prefixes map * @param ignoreNamespaceDefinitionAttribute - whether to ignore namespace * attributes * @param requireWellFormed - whether to check conformance */ private _serializeAttributes(node: Element, map: NamespacePrefixMap, prefixIndex: PrefixIndex, localPrefixesMap: { [key: string]: string }, ignoreNamespaceDefinitionAttribute: boolean, requireWellFormed: boolean): void { const localNameSet = requireWellFormed ? new LocalNameSet() : undefined for (const attr of node.attributes) { // Optimize common case if (!requireWellFormed && !ignoreNamespaceDefinitionAttribute && attr.namespaceURI === null) { this._push(this._writer.attribute(attr.localName, this._serializeAttributeValue(attr.value, this._options.wellFormed))) continue } if (requireWellFormed && localNameSet && localNameSet.has(attr.namespaceURI, attr.localName)) { this.emit("error", new Error("Element contains duplicate attributes (well-formed required).")) return } if (requireWellFormed && localNameSet) localNameSet.set(attr.namespaceURI, attr.localName) let attributeNamespace = attr.namespaceURI let candidatePrefix: string | null = null if (attributeNamespace !== null) { candidatePrefix = map.get(attr.prefix, attributeNamespace) if (attributeNamespace === infraNamespace.XMLNS) { if (attr.value === infraNamespace.XML || (attr.prefix === null && ignoreNamespaceDefinitionAttribute) || (attr.prefix !== null && (!(attr.localName in localPrefixesMap) || localPrefixesMap[attr.localName] !== attr.value) && map.has(attr.localName, attr.value))) continue if (requireWellFormed && attr.value === infraNamespace.XMLNS) { this.emit("error", new Error("XMLNS namespace is reserved (well-formed required).")) return } if (requireWellFormed && attr.value === '') { this.emit("error", new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required).")) return } if (attr.prefix === 'xmlns') candidatePrefix = 'xmlns' /** * _Note:_ The (candidatePrefix === null) check is not in the spec. * We deviate from the spec here. Otherwise a prefix is generated for * all attributes with namespaces. */ } else if (candidatePrefix === null) { if (attr.prefix !== null && (!map.hasPrefix(attr.prefix) || map.has(attr.prefix, attributeNamespace))) { /** * Check if we can use the attribute's own prefix. * We deviate from the spec here. * TODO: This is not an efficient way of searching for prefixes. * Follow developments to the spec. */ candidatePrefix = attr.prefix } else { candidatePrefix = this._generatePrefix(attributeNamespace, map, prefixIndex) } this._push(this._writer.attribute("xmlns:" + candidatePrefix, this._serializeAttributeValue(attributeNamespace, this._options.wellFormed))) } } if (requireWellFormed && (attr.localName.indexOf(":") !== -1 || !xml_isName(attr.localName) || (attr.localName === "xmlns" && attributeNamespace === null))) { this.emit("error", new Error("Attribute local name contains invalid characters (well-formed required).")) return } this._push(this._writer.attribute( (candidatePrefix !== null ? candidatePrefix + ":" : "") + attr.localName, this._serializeAttributeValue(attr.value, this._options.wellFormed))) } } /** * Produces an XML serialization of an attribute value. * * @param value - attribute value * @param requireWellFormed - whether to check conformance */ private _serializeAttributeValue(value: string | null, requireWellFormed: boolean): string { if (requireWellFormed && value !== null && !xml_isLegalChar(value)) { this.emit("error", new Error("Invalid characters in attribute value.")) return "" } if (value === null) return "" return value.replace(/(?!&(lt|gt|amp|apos|quot);)&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') } /** * Records namespace information for the given element and returns the * default namespace attribute value. * * @param node - element node to process * @param map - namespace prefix map * @param localPrefixesMap - local prefixes map */ private _recordNamespaceInformation(node: Element, map: NamespacePrefixMap, localPrefixesMap: { [key: string]: string }): string | null { let defaultNamespaceAttrValue: string | null = null for (const attr of node.attributes) { let attributeNamespace = attr.namespaceURI let attributePrefix = attr.prefix if (attributeNamespace === infraNamespace.XMLNS) { if (attributePrefix === null) { defaultNamespaceAttrValue = attr.value continue } else { let prefixDefinition = attr.localName let namespaceDefinition: string | null = attr.value if (namespaceDefinition === infraNamespace.XML) { continue } if (namespaceDefinition === '') { namespaceDefinition = null } if (map.has(prefixDefinition, namespaceDefinition)) { continue } map.set(prefixDefinition, namespaceDefinition) localPrefixesMap[prefixDefinition] = namespaceDefinition || '' } } } return defaultNamespaceAttrValue } /** * Generates a new prefix for the given namespace. * * @param newNamespace - a namespace to generate prefix for * @param prefixMap - namespace prefix map * @param prefixIndex - generated namespace prefix index */ private _generatePrefix(newNamespace: string | null, prefixMap: NamespacePrefixMap, prefixIndex: PrefixIndex): string { let generatedPrefix = "ns" + prefixIndex.value prefixIndex.value++ prefixMap.set(generatedPrefix, newNamespace) return generatedPrefix } /** * Determines if the namespace prefix map was modified from its original. * * @param originalMap - original namespace prefix map * @param newMap - new namespace prefix map */ private _isPrefixMapModified(originalMap: NamespacePrefixMap, newMap: NamespacePrefixMap) { const items1: { [key: string]: string[] } = (originalMap as any)._items const items2: { [key: string]: string[] } = (newMap as any)._items const nullItems1: string[] = (originalMap as any)._nullItems const nullItems2: string[] = (newMap as any)._nullItems for (const key in items2) { const arr1 = items1[key] if (arr1 === undefined) return true const arr2 = items2[key] if (arr1.length !== arr2.length) return true for (let i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) return true } } if (nullItems1.length !== nullItems2.length) return true for (let i = 0; i < nullItems1.length; i++) { if (nullItems1[i] !== nullItems2[i]) return true } return false } }
the_stack
import axios from 'axios'; import fs from 'fs-extra'; import path from 'path'; import temp from 'temp'; import { minimalConfig } from './minimalConfig'; import { loggerSpy } from '../testhelpers/loggerSpy'; import readlineSync from 'readline-sync'; import { isSupportedFHIRVersion, ensureInputDir, findInputDir, ensureOutputDir, readConfig, loadExternalDependencies, getRawFSHes, hasFshFiles, writeFHIRResources, init, checkNullValuesOnArray, writePreprocessedFSH } from '../../src/utils/Processing'; import * as loadModule from '../../src/fhirdefs/load'; import { FHIRDefinitions } from '../../src/fhirdefs'; import { Package } from '../../src/export'; import { StructureDefinition, ValueSet, CodeSystem, InstanceDefinition } from '../../src/fhirtypes'; import { PackageLoadError } from '../../src/errors'; import { cloneDeep } from 'lodash'; import { FSHTank, FSHDocument } from '../../src/import'; import { Profile, Extension, Instance, FshValueSet, FshCodeSystem, Invariant, RuleSet, Mapping, Logical, Resource } from '../../src/fshtypes'; import { EOL } from 'os'; describe('Processing', () => { temp.track(); describe('#isSupportedFHIRVersion', () => { it('should support published version >= 4.0.1', () => { expect(isSupportedFHIRVersion('4.0.1')).toBe(true); expect(isSupportedFHIRVersion('4.2.0')).toBe(true); expect(isSupportedFHIRVersion('4.4.0')).toBe(true); expect(isSupportedFHIRVersion('4.5.0')).toBe(true); }); it('should support current version', () => { expect(isSupportedFHIRVersion('current')).toBe(true); }); it('should not support published versions < 4.0.1', () => { expect(isSupportedFHIRVersion('4.0.0')).toBe(false); expect(isSupportedFHIRVersion('3.0.2')).toBe(false); expect(isSupportedFHIRVersion('1.0.2')).toBe(false); expect(isSupportedFHIRVersion('0.0.82')).toBe(false); }); }); describe('#findInputDir()', () => { let tempRoot: string; beforeAll(() => { tempRoot = temp.mkdirSync('sushi-test'); fs.mkdirpSync(path.join(tempRoot, 'has-fsh', 'fsh')); // TODO: Tests legacy support. Remove when no longer supported. fs.mkdirpSync(path.join(tempRoot, 'has-input-fsh', 'input', 'fsh')); fs.mkdirpSync(path.join(tempRoot, 'has-input', 'input')); fs.mkdirpSync(path.join(tempRoot, 'has-fsh-and-input-fsh', 'fsh')); // TODO: Tests legacy support. Remove when no longer supported. fs.mkdirpSync(path.join(tempRoot, 'has-fsh-and-input-fsh', 'input', 'fsh')); fs.mkdirpSync(path.join(tempRoot, 'flat-tank', 'ig-data')); // TODO: Tests legacy support. Remove when no longer supported. fs.mkdirSync(path.join(tempRoot, 'no-fsh')); fs.ensureFileSync(path.join(tempRoot, 'no-fsh', 'notfsh.txt')); }); beforeEach(() => { loggerSpy.reset(); }); afterAll(() => { temp.cleanupSync(); }); it('should find a path to the current working directory when no input folder is specified', () => { const foundInput = ensureInputDir(undefined); expect(foundInput).toBe('.'); }); it('should find a path to the input/fsh subdirectory if present', () => { const input = path.join(tempRoot, 'has-input-fsh'); const foundInput = findInputDir(input); expect(foundInput).toBe(path.join(tempRoot, 'has-input-fsh', 'input', 'fsh')); }); it('should use path to input/fsh as input if input/ subdirectory present but no input/fsh present', () => { const input = path.join(tempRoot, 'has-input'); const foundInput = findInputDir(input); expect(foundInput).toBe(path.join(tempRoot, 'has-input', 'input', 'fsh')); expect(loggerSpy.getAllMessages()).toHaveLength(0); }); it('should find a path to input/fsh if no fsh files are present, no root level ig-data folder, and no fsh subdirectory (current tank with no fsh files)', () => { const input = path.join(tempRoot, 'no-fsh'); const foundInput = findInputDir(input); expect(foundInput).toBe(path.join(tempRoot, 'no-fsh', 'input', 'fsh')); }); // TODO: Tests current tank configuration is preferred over legacy. Remove when legacy error handling is removed. it('should prefer path to input/fsh over fsh/ if both present', () => { const input = path.join(tempRoot, 'has-fsh-and-input-fsh'); const foundInput = findInputDir(input); expect(foundInput).toBe(path.join(tempRoot, 'has-fsh-and-input-fsh', 'input', 'fsh')); }); // TODO: Tests legacy case logs error. Remove when error is removed. it('should log an error and not change input directory if the fsh subdirectory if present (legacy ./fsh/)', () => { const input = path.join(tempRoot, 'has-fsh'); const foundInput = findInputDir(input); expect(foundInput).toBe(path.join(tempRoot, 'has-fsh')); expect(loggerSpy.getLastMessage('error')).toMatch( /Use of this folder is NO LONGER SUPPORTED/s ); }); // TODO: Tests legacy case logs error. Remove when error is removed. it('should log an error and not change input directory if the fsh subdirectory is not present and a root ig-data is present (legacy flat tank)', () => { const input = path.join(tempRoot, 'flat-tank'); const foundInput = findInputDir(input); expect(foundInput).toBe(input); expect(loggerSpy.getLastMessage('error')).toMatch( /Support for other folder structures is NO LONGER SUPPORTED/s ); }); }); describe('#ensureOutputDir()', () => { let tempRoot: string; let emptyDirSpy: jest.SpyInstance; beforeAll(() => { tempRoot = temp.mkdirSync('sushi-test'); fs.mkdirSync(path.join(tempRoot, 'my-input')); }); beforeEach(() => { emptyDirSpy = jest.spyOn(fs, 'emptyDirSync').mockImplementation(() => ''); emptyDirSpy.mockReset(); }); afterAll(() => { temp.cleanupSync(); }); it('should use and create the output directory when it is provided', () => { const input = path.join(tempRoot, 'my-input'); const output = path.join(tempRoot, 'my-output'); const outputDir = ensureOutputDir(input, output); expect(outputDir).toBe(output); expect(fs.existsSync(output)).toBeTruthy(); }); it('should default the output directory to the grandparent of the input no output directory provided (e.g. ./input/fsh -> ./)', () => { const input = path.join(tempRoot, 'my-input', 'my-fsh'); const outputDir = ensureOutputDir(input, undefined); expect(outputDir).toBe(tempRoot); expect(fs.existsSync(outputDir)).toBeTruthy(); expect(loggerSpy.getLastMessage('info')).toMatch(/No output path specified/); }); it('should empty the fsh-generated folder if the output directory contains one', () => { jest .spyOn(fs, 'existsSync') .mockImplementationOnce(dir => dir === path.join(tempRoot, 'fsh-generated')); const input = path.join(tempRoot, 'my-input', 'my-fsh'); const outputDir = ensureOutputDir(input, undefined); expect(outputDir).toBe(tempRoot); expect(fs.existsSync(outputDir)).toBeTruthy(); expect(emptyDirSpy.mock.calls).toHaveLength(1); expect(emptyDirSpy.mock.calls[0][0]).toBe(path.join(tempRoot, 'fsh-generated')); }); it('should log an error when emptying the directory fails', () => { emptyDirSpy = emptyDirSpy.mockImplementation(() => { throw Error('foo'); }); jest .spyOn(fs, 'existsSync') .mockImplementationOnce(dir => dir === path.join(tempRoot, 'fsh-generated')); const input = path.join(tempRoot, 'my-input', 'my-fsh'); const outputDir = ensureOutputDir(input, undefined); expect(outputDir).toBe(tempRoot); expect(fs.existsSync(outputDir)).toBeTruthy(); expect(emptyDirSpy.mock.calls).toHaveLength(1); expect(emptyDirSpy.mock.calls[0][0]).toBe(path.join(tempRoot, 'fsh-generated')); expect(loggerSpy.getLastMessage('error')).toMatch( /Unable to empty existing fsh-generated folder.*: foo/ ); }); }); describe('#readConfig()', () => { beforeEach(() => { loggerSpy.reset(); }); it('should return the contents of sushi-config.yaml from the input directory', () => { const input = path.join(__dirname, 'fixtures', 'valid-yaml'); const config = readConfig(input); expect(config).toEqual({ filePath: path.join(__dirname, 'fixtures', 'valid-yaml', 'sushi-config.yaml'), id: 'sushi-test', packageId: 'sushi-test', canonical: 'http://hl7.org/fhir/sushi-test', url: 'http://hl7.org/fhir/sushi-test/ImplementationGuide/sushi-test', version: '0.1.0', name: 'FSHTestIG', title: 'FSH Test IG', status: 'active', contact: [ { name: 'Bill Cod', telecom: [ { system: 'url', value: 'https://capecodfishermen.org/' }, { system: 'email', value: 'cod@reef.gov' } ] } ], description: 'Provides a simple example of how FSH can be used to create an IG', license: 'CC0-1.0', fhirVersion: ['4.0.1'], dependencies: [ { packageId: 'hl7.fhir.us.core', version: '3.1.0' }, { packageId: 'hl7.fhir.uv.vhdir', version: 'current' } ], FSHOnly: false, applyExtensionMetadataToRoot: true, instanceOptions: { setMetaProfile: 'always', setId: 'always' }, parameters: [ { code: 'copyrightyear', value: '2020' }, { code: 'releaselabel', value: 'CI Build' } ] }); }); it('should allow FHIR R5', () => { const input = path.join(__dirname, 'fixtures', 'fhir-r5'); const config = readConfig(input); expect(config.fhirVersion).toEqual(['4.5.0']); }); it('should allow FHIR current', () => { const input = path.join(__dirname, 'fixtures', 'fhir-current'); const config = readConfig(input); expect(config.fhirVersion).toEqual(['current']); }); it('should extract a configuration from an ImplementationGuide JSON when sushi-config.yaml is absent', () => { const input = path.join(__dirname, 'fixtures', 'ig-JSON-only'); const config = readConfig(input); expect(config).toEqual({ FSHOnly: true, canonical: 'http://example.org', fhirVersion: ['4.0.1'] }); }); it('should log and throw an error when sushi-config.yaml is not found in the input directory', () => { const input = path.join(__dirname, 'fixtures', 'no-package'); expect(() => { readConfig(input); }).toThrow(); expect(loggerSpy.getLastMessage('error')).toMatch(/No sushi-config\.yaml/s); }); it('should log and throw an error when the contents of sushi-config.yaml are not valid yaml', () => { const input = path.join(__dirname, 'fixtures', 'invalid-yaml'); expect(() => { readConfig(input); }).toThrow(); expect(loggerSpy.getLastMessage('error')).toMatch(/not a valid YAML object/s); }); it('should log and throw an error when the configuration uses an unsupported FHIR version (DSTU2)', () => { const input = path.join(__dirname, 'fixtures', 'fhir-dstu2'); expect(() => { readConfig(input); }).toThrow(); expect(loggerSpy.getLastMessage('error')).toMatch( /must specify a supported version of FHIR/s ); }); it('should log and throw an error when the configuration uses an unsupported FHIR version (4.0.0)', () => { const input = path.join(__dirname, 'fixtures', 'fhir-four-oh-oh'); expect(() => { readConfig(input); }).toThrow(); expect(loggerSpy.getLastMessage('error')).toMatch( /must specify a supported version of FHIR/s ); }); }); describe('#loadExternalDependencies()', () => { beforeAll(() => { jest .spyOn(loadModule, 'loadDependency') .mockImplementation( async (packageName: string, version: string, FHIRDefs: FHIRDefinitions) => { // the mock loader can find hl7.fhir.(r2|r3|r4|r5|us).core if (/^hl7.fhir.(r2|r3|r4|r4b|r5|us).core$/.test(packageName)) { FHIRDefs.packages.push(`${packageName}#${version}`); return Promise.resolve(FHIRDefs); } else if (/^self-signed.package$/.test(packageName)) { throw new Error('self signed certificate in certificate chain'); } else { throw new PackageLoadError(`${packageName}#${version}`); } } ); }); beforeEach(() => { loggerSpy.reset(); }); it('should load specified dependencies', () => { const usCoreDependencyConfig = cloneDeep(minimalConfig); usCoreDependencyConfig.dependencies = [{ packageId: 'hl7.fhir.us.core', version: '3.1.0' }]; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, usCoreDependencyConfig).then(() => { expect(defs.packages.length).toBe(2); expect(defs.packages).toContain('hl7.fhir.r4.core#4.0.1'); expect(defs.packages).toContain('hl7.fhir.us.core#3.1.0'); expect(loggerSpy.getAllLogs('warn')).toHaveLength(0); }); }); it('should support prerelease FHIR R4B dependencies', () => { const config = cloneDeep(minimalConfig); config.fhirVersion = ['4.1.0']; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, config).then(() => { expect(defs.packages).toEqual(['hl7.fhir.r4b.core#4.1.0']); expect(loggerSpy.getLastMessage('warn')).toMatch( /support for pre-release versions of FHIR is experimental/s ); }); }); it('should support prerelease FHIR R4B snapshot dependencies', () => { const config = cloneDeep(minimalConfig); config.fhirVersion = ['4.3.0-snapshot1']; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, config).then(() => { expect(defs.packages).toEqual(['hl7.fhir.r4b.core#4.3.0-snapshot1']); expect(loggerSpy.getLastMessage('warn')).toMatch( /support for pre-release versions of FHIR is experimental/s ); }); }); it('should support official FHIR R4B dependency (will be 4.3.0)', () => { const config = cloneDeep(minimalConfig); config.fhirVersion = ['4.3.0']; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, config).then(() => { expect(defs.packages).toEqual(['hl7.fhir.r4b.core#4.3.0']); expect(loggerSpy.getAllLogs('warn')).toHaveLength(0); }); }); it('should support prerelease FHIR R5 dependencies', () => { const config = cloneDeep(minimalConfig); config.fhirVersion = ['4.5.0']; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, config).then(() => { expect(defs.packages).toEqual(['hl7.fhir.r5.core#4.5.0']); expect(loggerSpy.getLastMessage('warn')).toMatch( /support for pre-release versions of FHIR is experimental/s ); }); }); it('should support prerelease FHIR R5 snapshot dependencies', () => { const config = cloneDeep(minimalConfig); config.fhirVersion = ['5.0.0-snapshot1']; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, config).then(() => { expect(defs.packages).toEqual(['hl7.fhir.r5.core#5.0.0-snapshot1']); expect(loggerSpy.getLastMessage('warn')).toMatch( /support for pre-release versions of FHIR is experimental/s ); }); }); it('should support official FHIR R5 dependency (will be 5.0.0)', () => { const config = cloneDeep(minimalConfig); config.fhirVersion = ['5.0.0']; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, config).then(() => { expect(defs.packages).toEqual(['hl7.fhir.r5.core#5.0.0']); expect(loggerSpy.getAllLogs('warn')).toHaveLength(0); }); }); it('should support FHIR current dependencies', () => { const config = cloneDeep(minimalConfig); config.fhirVersion = ['current']; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, config).then(() => { expect(defs.packages).toEqual(['hl7.fhir.r5.core#current']); expect(loggerSpy.getLastMessage('warn')).toMatch( /support for pre-release versions of FHIR is experimental/s ); }); }); it('should support virtual FHIR extension packages', () => { // We want to do this for each, so make a function we'll just call for each version const testExtPackage = async ( extId: string, suppFhirId: string, suppFhirVersion: string, fhirId: string, fhirVersion: string ) => { const virtualExtensionsConfig = cloneDeep(minimalConfig); virtualExtensionsConfig.fhirVersion = [fhirVersion]; virtualExtensionsConfig.dependencies = [{ packageId: extId, version: fhirVersion }]; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, virtualExtensionsConfig).then(() => { expect(defs.packages.length).toBe(1); expect(defs.packages).toContain(`${fhirId}#${fhirVersion}`); expect(defs.supplementalFHIRPackages).toEqual([`${suppFhirId}#${suppFhirVersion}`]); expect(loggerSpy.getAllLogs('error')).toHaveLength(0); }); }; return Promise.all([ testExtPackage( 'hl7.fhir.extensions.r2', 'hl7.fhir.r2.core', '1.0.2', 'hl7.fhir.r4.core', '4.0.1' ), testExtPackage( 'hl7.fhir.extensions.r3', 'hl7.fhir.r3.core', '3.0.2', 'hl7.fhir.r4.core', '4.0.1' ), testExtPackage( 'hl7.fhir.extensions.r4', 'hl7.fhir.r4.core', '4.0.1', 'hl7.fhir.r5.core', '4.5.0' ), testExtPackage( 'hl7.fhir.extensions.r5', 'hl7.fhir.r5.core', 'current', 'hl7.fhir.r4.core', '4.0.1' ) ]); }); it('should log a warning if wrong virtual FHIR extension package version is used', () => { const virtualExtensionsConfig = cloneDeep(minimalConfig); virtualExtensionsConfig.fhirVersion = ['4.0.1']; virtualExtensionsConfig.dependencies = [ { packageId: 'hl7.fhir.extensions.r2', version: '1.0.2' } ]; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, virtualExtensionsConfig).then(() => { expect(defs.packages.length).toBe(1); expect(defs.packages).toContain('hl7.fhir.r4.core#4.0.1'); expect(defs.supplementalFHIRPackages).toEqual(['hl7.fhir.r2.core#1.0.2']); expect(loggerSpy.getLastMessage('warn')).toMatch( /Incorrect package version: hl7\.fhir\.extensions\.r2#1\.0\.2\./ ); expect(loggerSpy.getAllLogs('error')).toHaveLength(0); }); }); it('should log an error when it fails to load a dependency', () => { const badDependencyConfig = cloneDeep(minimalConfig); badDependencyConfig.dependencies = [{ packageId: 'hl7.does.not.exist', version: 'current' }]; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, badDependencyConfig).then(() => { expect(defs.packages.length).toBe(1); expect(defs.packages).toContain('hl7.fhir.r4.core#4.0.1'); expect(loggerSpy.getLastMessage('error')).toMatch( /Failed to load hl7\.does\.not\.exist#current/s ); // But don't log the error w/ details about proxies expect(loggerSpy.getLastMessage('error')).not.toMatch(/SSL/s); }); }); it('should log a more detailed error when it fails to load a dependency due to certificate issue', () => { const selfSignedDependencyConfig = cloneDeep(minimalConfig); selfSignedDependencyConfig.dependencies = [ { packageId: 'self-signed.package', version: '1.0.0' } ]; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, selfSignedDependencyConfig).then(() => { expect(defs.packages.length).toBe(1); expect(defs.packages).toContain('hl7.fhir.r4.core#4.0.1'); expect(loggerSpy.getLastMessage('error')).toMatch( /Failed to load self-signed\.package#1\.0\.0/s ); // AND it should log the detailed message about SSL expect(loggerSpy.getLastMessage('error')).toMatch( /Sometimes this error occurs in corporate or educational environments that use proxies and\/or SSL inspection/s ); }); }); it('should log an error when a dependency has no specified version', () => { const badDependencyConfig = cloneDeep(minimalConfig); badDependencyConfig.dependencies = [{ packageId: 'hl7.fhir.r4.core' }]; const defs = new FHIRDefinitions(); return loadExternalDependencies(defs, badDependencyConfig).then(() => { expect(defs.packages.length).toBe(1); expect(defs.packages).toContain('hl7.fhir.r4.core#4.0.1'); expect(loggerSpy.getLastMessage('error')).toMatch( /Failed to load hl7\.fhir\.r4\.core: No version specified\./s ); // But don't log the error w/ details about proxies expect(loggerSpy.getLastMessage('error')).not.toMatch(/SSL/s); }); }); }); describe('#getRawFSHes()', () => { it('should return a RawFSH for each file in the input directory that ends with .fsh', () => { const input = path.join(__dirname, 'fixtures', 'fsh-files'); const rawFSHes = getRawFSHes(input); expect(rawFSHes.length).toBe(2); expect(rawFSHes).toContainEqual({ content: '// Content of first file', path: path.join(input, 'first.fsh') }); expect(rawFSHes).toContainEqual({ content: '// Content of second file', path: path.join(input, 'second.fsh') }); }); it('should log and throw an error when the input path is invalid', () => { const input = path.join(__dirname, 'fixtures', 'wrong-path'); expect(() => { getRawFSHes(input); }).toThrow(); expect(loggerSpy.getLastMessage('error')).toMatch(/Invalid path to FSH definition folder\./s); }); describe('#symlinks', () => { const linkPath = path.join(__dirname, 'fixtures', 'fsh-files', 'myLock.fsh'); const linkTarget = path.join(__dirname, 'fixtures', 'fsh-files', 'meaninglessTarget'); beforeAll(() => { try { fs.removeSync(linkPath); } catch { // This will fail if the link doesn't exist, which is fine. // We just want to be extra sure to clean up before making it. } try { fs.symlinkSync(linkTarget, linkPath); } catch { // This may fail if the user running the test doesn't have permission to create a symbolic link. // On Windows systems, normal users do not have this permission. } }); it('should return a RawFSH for each real file in the input directory that ends with .fsh', () => { const input = path.join(__dirname, 'fixtures', 'fsh-files'); const rawFSHes = getRawFSHes(input); expect(rawFSHes.length).toBe(2); expect(rawFSHes).toContainEqual({ content: '// Content of first file', path: path.join(input, 'first.fsh') }); expect(rawFSHes).toContainEqual({ content: '// Content of second file', path: path.join(input, 'second.fsh') }); }); afterAll(() => { try { fs.removeSync(linkPath); } catch { // This will fail if someone removed the link in the middle of the test. } }); }); }); describe('#hasFshFiles()', () => { let tempRoot: string; beforeAll(() => { tempRoot = temp.mkdirSync('sushi-test'); fs.mkdirSync(path.join(tempRoot, 'some-fsh')); fs.mkdirSync(path.join(tempRoot, 'some-fsh', 'nested')); fs.ensureFileSync(path.join(tempRoot, 'some-fsh', 'notfsh.txt')); fs.ensureFileSync(path.join(tempRoot, 'some-fsh', 'nested', 'myfsh.fsh')); fs.mkdirSync(path.join(tempRoot, 'no-fsh')); fs.mkdirSync(path.join(tempRoot, 'no-fsh', 'nested')); fs.ensureFileSync(path.join(tempRoot, 'no-fsh', 'notfsh.txt')); fs.ensureFileSync(path.join(tempRoot, 'no-fsh', 'nested', 'notfsh.txt')); }); afterAll(() => { temp.cleanupSync(); }); it('should return true if FSH files exist in any subdirectory', () => { const result = hasFshFiles(path.join(tempRoot, 'some-fsh')); expect(result).toBe(true); }); it('should return false if there are no FSH files in any subdirectory', () => { const result = hasFshFiles(path.join(tempRoot, 'no-fsh')); expect(result).toBe(false); }); }); describe('#checkNullValuesOnArray', () => { beforeEach(() => { loggerSpy.reset(); }); it('should log a warning when a resource includes null values in a top-level array', () => { const exInstance = new InstanceDefinition(); exInstance.resourceType = 'Profile'; exInstance.id = 'example-instance'; exInstance.name = [null, 'John', null, 'Doe', null]; checkNullValuesOnArray(exInstance); expect(loggerSpy.getAllMessages()).toHaveLength(1); expect(loggerSpy.getLastMessage('warn')).toEqual( "The array 'name' in example-instance is missing values at the following indices: 0,2,4" ); }); it('should log a warning when a resource includes null values in a nested array', () => { const exInstance = new InstanceDefinition(); exInstance.resourceType = 'Profile'; exInstance.id = 'example-instance'; const nameObj = { testNames: [null, 'John', null, 'Doe', null] }; exInstance.name = nameObj; checkNullValuesOnArray(exInstance); expect(loggerSpy.getAllMessages()).toHaveLength(1); expect(loggerSpy.getLastMessage('warn')).toEqual( "The array 'name.testNames' in example-instance is missing values at the following indices: 0,2,4" ); }); it('should log a warning when a resource includes null values in an array, nested within both objects and arrays ', () => { const exInstance = new InstanceDefinition(); exInstance.resourceType = 'Profile'; exInstance.id = 'example-instance'; const nameObj = { foo: [ { coding: [ null, // this is bad { system: 'http://foo.org', code: 'bar' } ] } ] }; exInstance.name = nameObj; checkNullValuesOnArray(exInstance); expect(loggerSpy.getAllMessages()).toHaveLength(1); expect(loggerSpy.getLastMessage('warn')).toEqual( "The array 'name.foo[0].coding' in example-instance is missing values at the following indices: 0" ); }); it('should ignore null values on primitive arrays, but warn on null values in nested arrays', () => { const exInstance = new InstanceDefinition(); exInstance.resourceType = 'Profile'; exInstance.id = 'example-instance'; const nameObj = { _foo: [ null, // this is ok { extension: [ null, // this is NOT ok { url: 'http://foo.org', valueBoolean: true } ] } ] }; exInstance.name = nameObj; checkNullValuesOnArray(exInstance); expect(loggerSpy.getAllMessages()).toHaveLength(1); expect(loggerSpy.getLastMessage('warn')).toEqual( "The array 'name._foo[1].extension' in example-instance is missing values at the following indices: 0" ); }); it('should not log a warning when a resource includes null values in an array prefixed with an underscore', () => { const exInstance = new InstanceDefinition(); exInstance.resourceType = 'Profile'; exInstance.id = 'example-instance'; exInstance._name = [null, 'John', null, 'Doe', null]; checkNullValuesOnArray(exInstance); expect(loggerSpy.getAllMessages()).toHaveLength(0); }); it('should log a warning when a resource includes null values in an array nested within an object prefixed with an underscore', () => { const exInstance = new InstanceDefinition(); exInstance.resourceType = 'Profile'; exInstance.id = 'example-instance'; const nameObj = { testNames: [null, 'John', null, 'Doe', null] }; exInstance._name = nameObj; checkNullValuesOnArray(exInstance); expect(loggerSpy.getAllMessages()).toHaveLength(1); expect(loggerSpy.getLastMessage('warn')).toEqual( "The array '_name.testNames' in example-instance is missing values at the following indices: 0,2,4" ); }); }); describe('#writeFHIRResources()', () => { let tempIGPubRoot: string; let outPackage: Package; let defs: FHIRDefinitions; beforeAll(() => { tempIGPubRoot = temp.mkdirSync('output-ig-dir'); const input = path.join(__dirname, 'fixtures', 'valid-yaml'); const config = readConfig(input); outPackage = new Package(config); defs = new FHIRDefinitions(); const myProfile = new StructureDefinition(); myProfile.id = 'my-profile'; const myExtension = new StructureDefinition(); myExtension.id = 'my-extension'; const myLogical = new StructureDefinition(); myLogical.id = 'my-logical'; const myResource = new StructureDefinition(); myResource.id = 'my-resource'; const myValueSet = new ValueSet(); myValueSet.id = 'my-value-set'; const myCodeSystem = new CodeSystem(); myCodeSystem.id = 'my-code-system'; const myInlineInstance = new InstanceDefinition(); myInlineInstance.id = 'my-inline-instance'; myInlineInstance._instanceMeta.usage = 'Inline'; const myExampleInstance = new InstanceDefinition(); myExampleInstance.id = 'my-example'; myExampleInstance.resourceType = 'Observation'; myExampleInstance._instanceMeta.usage = 'Example'; const myCapabilityStatement = new InstanceDefinition(); myCapabilityStatement.id = 'my-capabilities'; myCapabilityStatement.resourceType = 'CapabilityStatement'; const myConceptMap = new InstanceDefinition(); myConceptMap.id = 'my-concept-map'; myConceptMap.resourceType = 'ConceptMap'; const myModelInstance = new InstanceDefinition(); myModelInstance.id = 'my-model'; myModelInstance.resourceType = 'StructureDefinition'; myModelInstance.kind = 'logical'; const myOperationDefinition = new InstanceDefinition(); myOperationDefinition.id = 'my-operation'; myOperationDefinition.resourceType = 'OperationDefinition'; const myExtensionInstance = new InstanceDefinition(); myExtensionInstance.id = 'my-extension-instance'; myExtensionInstance.resourceType = 'StructureDefinition'; myExtensionInstance.kind = 'resource'; myExtensionInstance.type = 'Extension'; const myProfileInstance = new InstanceDefinition(); myProfileInstance.id = 'my-profile-instance'; myProfileInstance.resourceType = 'StructureDefinition'; myProfileInstance.kind = 'resource'; myProfileInstance.type = 'Observation'; const myOtherInstance = new InstanceDefinition(); myOtherInstance.id = 'my-other-instance'; myOtherInstance.resourceType = 'Observation'; const myPredefinedProfile = new StructureDefinition(); myPredefinedProfile.id = 'my-duplicate-profile'; myPredefinedProfile.url = 'http://example.com/StructureDefinition/my-duplicate-profile'; defs.addPredefinedResource( 'StructureDefinition-my-duplicate-profile.json', myPredefinedProfile ); const myFSHDefinedProfile = new StructureDefinition(); myFSHDefinedProfile.id = 'my-duplicate-profile'; myFSHDefinedProfile.url = 'http://example.com/StructureDefinition/my-duplicate-profile'; const myPredefinedInstance = new InstanceDefinition(); myPredefinedInstance.id = 'my-duplicate-instance'; myPredefinedInstance.resourceType = 'Patient'; defs.addPredefinedResource('Patient-my-duplicate-instance.json', myPredefinedInstance); const myFSHDefinedInstance = new InstanceDefinition(); myFSHDefinedInstance.id = 'my-duplicate-instance'; myFSHDefinedInstance.resourceType = 'Patient'; outPackage.profiles.push(myProfile, myFSHDefinedProfile); outPackage.extensions.push(myExtension); outPackage.logicals.push(myLogical); outPackage.resources.push(myResource); outPackage.valueSets.push(myValueSet); outPackage.codeSystems.push(myCodeSystem); outPackage.instances.push( myInlineInstance, myExampleInstance, myCapabilityStatement, myConceptMap, myModelInstance, myOperationDefinition, myExtensionInstance, myProfileInstance, myOtherInstance, myFSHDefinedInstance ); }); afterAll(() => { temp.cleanupSync(); }); describe('IG Publisher mode', () => { beforeAll(() => { writeFHIRResources(tempIGPubRoot, outPackage, defs, false); }); afterAll(() => { temp.cleanupSync(); }); it('should write all resources to the "fsh-generated/resources" directory', () => { const generatedPath = path.join(tempIGPubRoot, 'fsh-generated', 'resources'); expect(fs.existsSync(generatedPath)).toBeTruthy(); const allGeneratedFiles = fs.readdirSync(generatedPath); expect(allGeneratedFiles.length).toBe(14); expect(allGeneratedFiles).toContain('StructureDefinition-my-profile.json'); expect(allGeneratedFiles).toContain('StructureDefinition-my-profile-instance.json'); expect(allGeneratedFiles).toContain('StructureDefinition-my-extension.json'); expect(allGeneratedFiles).toContain('StructureDefinition-my-extension-instance.json'); expect(allGeneratedFiles).toContain('StructureDefinition-my-logical.json'); expect(allGeneratedFiles).toContain('StructureDefinition-my-resource.json'); expect(allGeneratedFiles).toContain('ValueSet-my-value-set.json'); expect(allGeneratedFiles).toContain('CodeSystem-my-code-system.json'); expect(allGeneratedFiles).toContain('ConceptMap-my-concept-map.json'); expect(allGeneratedFiles).toContain('Observation-my-example.json'); expect(allGeneratedFiles).toContain('CapabilityStatement-my-capabilities.json'); expect(allGeneratedFiles).toContain('StructureDefinition-my-model.json'); expect(allGeneratedFiles).toContain('OperationDefinition-my-operation.json'); expect(allGeneratedFiles).toContain('Observation-my-other-instance.json'); expect(loggerSpy.getLastMessage('info')).toMatch(/Exported 14 FHIR resources/s); }); it('should not allow devious characters in the resource file names', () => { const tempDeviousIGPubRoot = temp.mkdirSync('output-ig-dir'); const deviousOutPackage = cloneDeep(outPackage); deviousOutPackage.profiles.forEach(d => (d.id = `/../../devious/${d.id}`)); deviousOutPackage.extensions.forEach(d => (d.id = `/../../devious/${d.id}`)); deviousOutPackage.logicals.forEach(d => (d.id = `/../../devious/${d.id}`)); deviousOutPackage.resources.forEach(d => (d.id = `/../../devious/${d.id}`)); deviousOutPackage.valueSets.forEach(d => (d.id = `/../../devious/${d.id}`)); deviousOutPackage.codeSystems.forEach(d => (d.id = `/../../devious/${d.id}`)); deviousOutPackage.instances.forEach(d => (d.id = `/../../devious/${d.id}`)); writeFHIRResources(tempDeviousIGPubRoot, deviousOutPackage, defs, false); // Make sure we didn't create the devious path const deviousPath = path.join(tempDeviousIGPubRoot, 'fsh-generated', 'devious'); expect(fs.existsSync(deviousPath)).toBeFalse(); // Make sure we do have all the good file names const angelicPath = path.join(tempDeviousIGPubRoot, 'fsh-generated', 'resources'); expect(fs.existsSync(angelicPath)).toBeTruthy(); const allAngelicFiles = fs.readdirSync(angelicPath); expect(allAngelicFiles.length).toBe(16); expect(allAngelicFiles).toContain( 'CapabilityStatement--..-..-devious-my-capabilities.json' ); expect(allAngelicFiles).toContain('CodeSystem--..-..-devious-my-code-system.json'); expect(allAngelicFiles).toContain('ConceptMap--..-..-devious-my-concept-map.json'); expect(allAngelicFiles).toContain('Observation--..-..-devious-my-example.json'); expect(allAngelicFiles).toContain('Observation--..-..-devious-my-other-instance.json'); expect(allAngelicFiles).toContain('OperationDefinition--..-..-devious-my-operation.json'); expect(allAngelicFiles).toContain('Patient--..-..-devious-my-duplicate-instance.json'); expect(allAngelicFiles).toContain( 'StructureDefinition--..-..-devious-my-duplicate-profile.json' ); expect(allAngelicFiles).toContain( 'StructureDefinition--..-..-devious-my-extension-instance.json' ); expect(allAngelicFiles).toContain('StructureDefinition--..-..-devious-my-extension.json'); expect(allAngelicFiles).toContain('StructureDefinition--..-..-devious-my-logical.json'); expect(allAngelicFiles).toContain('StructureDefinition--..-..-devious-my-model.json'); expect(allAngelicFiles).toContain( 'StructureDefinition--..-..-devious-my-profile-instance.json' ); expect(allAngelicFiles).toContain('StructureDefinition--..-..-devious-my-profile.json'); expect(allAngelicFiles).toContain('StructureDefinition--..-..-devious-my-resource.json'); expect(allAngelicFiles).toContain('ValueSet--..-..-devious-my-value-set.json'); expect(loggerSpy.getLastMessage('info')).toMatch(/Exported 16 FHIR resources/s); }); it('should not write a resource if that resource already exists in the "input" folder', () => { expect( fs.existsSync( path.join( tempIGPubRoot, 'fsh-generated', 'resources', 'StructureDefinition-my-duplicate-profile.json' ) ) ).toBeFalsy(); expect( loggerSpy .getAllMessages('error') .some(error => error.match(/Ignoring FSH definition for .*my-duplicate-profile/)) ).toBeTruthy(); expect( fs.existsSync( path.join( tempIGPubRoot, 'fsh-generated', 'resources', 'Patient-my-duplicate-instance.json' ) ) ).toBeFalsy(); expect( loggerSpy .getAllMessages('error') .some(error => error.match(/Ignoring FSH definition for .*my-duplicate-instance/)) ).toBeTruthy(); }); }); }); describe('#writePreprocessedFSH', () => { let tank: FSHTank; let tempIn: string; let tempOut: string; beforeAll(() => { tempIn = temp.mkdirSync('input-dir'); tempOut = temp.mkdirSync('output-dir'); const firstDoc = new FSHDocument(path.join(tempIn, 'first.fsh')); firstDoc.aliases.set('LOINC', 'http://loinc.org'); firstDoc.profiles.set('MyProfile', new Profile('MyProfile').withLocation([3, 0, 15, 7])); firstDoc.extensions.set( 'MyExtension', new Extension('MyExtension').withLocation([17, 0, 20, 8]) ); firstDoc.logicals.set('MyLogical', new Logical('MyLogical').withLocation([31, 0, 39, 23])); const secondDoc = new FSHDocument(path.join(tempIn, 'second.fsh')); secondDoc.instances.set( 'MyInstance', new Instance('MyInstance').withLocation([20, 0, 25, 5]) ); secondDoc.valueSets.set( 'MyValueSet', new FshValueSet('MyValueSet').withLocation([30, 0, 35, 9]) ); secondDoc.codeSystems.set( 'MyCodeSystem', new FshCodeSystem('MyCodeSystem').withLocation([10, 0, 15, 18]) ); const thirdDoc = new FSHDocument(path.join(tempIn, 'extra', 'third.fsh')); thirdDoc.invariants.set('inv-1', new Invariant('inv-1').withLocation([222, 0, 224, 9])); thirdDoc.ruleSets.set('MyRuleSet', new RuleSet('MyRuleSet').withLocation([33, 0, 39, 15])); thirdDoc.mappings.set('MyMapping', new Mapping('MyMapping').withLocation([10, 0, 21, 18])); thirdDoc.resources.set( 'MyResource', new Resource('MyResource').withLocation([55, 0, 69, 31]) ); const ruleSetDoc = new FSHDocument(path.join(tempIn, 'extra', 'rulesets.fsh')); ruleSetDoc.ruleSets.set('OneRuleSet', new RuleSet('OneRuleSet').withLocation([8, 0, 18, 35])); ruleSetDoc.ruleSets.set( 'TwoRuleSet', new RuleSet('TwoRuleSet').withLocation([20, 0, 35, 21]) ); tank = new FSHTank([firstDoc, secondDoc, thirdDoc, ruleSetDoc], null); writePreprocessedFSH(tempOut, tempIn, tank); }); afterAll(() => { temp.cleanupSync(); }); it('should produce files in a structure that mirrors the input', () => { expect(fs.existsSync(path.join(tempOut, '_preprocessed', 'first.fsh'))); expect(fs.existsSync(path.join(tempOut, '_preprocessed', 'second.fsh'))); expect(fs.existsSync(path.join(tempOut, '_preprocessed', 'extra', 'third.fsh'))); expect(fs.existsSync(path.join(tempOut, '_preprocessed', 'extra', 'aliases.fsh'))); }); it('should write all entities that exist after preprocessing', () => { // first.fsh should contain LOINC (an Alias), MyProfile, and MyExtension const firstContents = fs.readFileSync( path.join(tempOut, '_preprocessed', 'first.fsh'), 'utf-8' ); expect(firstContents).toMatch('Alias: LOINC'); expect(firstContents).toMatch( `// Originally defined on lines 3 - 15${EOL}Profile: MyProfile` ); expect(firstContents).toMatch( `// Originally defined on lines 17 - 20${EOL}Extension: MyExtension` ); expect(firstContents).toMatch( `// Originally defined on lines 31 - 39${EOL}Logical: MyLogical` ); // second.fsh should contain MyCodeSystem, MyInstance, and MyValueSet const secondContents = fs.readFileSync( path.join(tempOut, '_preprocessed', 'second.fsh'), 'utf-8' ); expect(secondContents).toMatch( `// Originally defined on lines 10 - 15${EOL}CodeSystem: MyCodeSystem` ); expect(secondContents).toMatch( `// Originally defined on lines 20 - 25${EOL}Instance: MyInstance` ); expect(secondContents).toMatch( `// Originally defined on lines 30 - 35${EOL}ValueSet: MyValueSet` ); // third.fsh should contain MyMapping and inv-1 const thirdContents = fs.readFileSync( path.join(tempOut, '_preprocessed', 'extra', 'third.fsh'), 'utf-8' ); expect(thirdContents).toMatch( `// Originally defined on lines 10 - 21${EOL}Mapping: MyMapping` ); expect(thirdContents).toMatch( `// Originally defined on lines 222 - 224${EOL}Invariant: inv-1` ); expect(thirdContents).toMatch( `// Originally defined on lines 55 - 69${EOL}Resource: MyResource` ); // RuleSets do not exist after preprocessing expect(thirdContents).not.toMatch('RuleSet: MyRuleSet'); }); it('should write entities in their original order', () => { const secondContents = fs.readFileSync( path.join(tempOut, '_preprocessed', 'second.fsh'), 'utf-8' ); const instanceLocation = secondContents.indexOf('Instance: MyInstance'); const valueSetLocation = secondContents.indexOf('ValueSet: MyValueSet'); const codeSystemLocation = secondContents.indexOf('CodeSystem: MyCodeSystem'); expect(instanceLocation).toBeGreaterThan(-1); expect(valueSetLocation).toBeGreaterThan(-1); expect(codeSystemLocation).toBeGreaterThan(-1); expect(codeSystemLocation).toBeLessThan(instanceLocation); expect(instanceLocation).toBeLessThan(valueSetLocation); }); it('should write a comment for a file with no entities after preprocessing', () => { // A file with only RuleSet definitions will have no content after preprocessing. const ruleSetContent = fs.readFileSync( path.join(tempOut, '_preprocessed', 'extra', 'rulesets.fsh'), 'utf-8' ); expect(ruleSetContent).toBe('// This file has no content after preprocessing.'); }); }); describe('#init()', () => { let readlineSpy: jest.SpyInstance; let yesNoSpy: jest.SpyInstance; let writeSpy: jest.SpyInstance; let copyFileSpy: jest.SpyInstance; let ensureDirSpy: jest.SpyInstance; let consoleSpy: jest.SpyInstance; let getSpy: jest.SpyInstance; beforeEach(() => { readlineSpy = jest.spyOn(readlineSync, 'question').mockImplementation(() => ''); yesNoSpy = jest.spyOn(readlineSync, 'keyInYN').mockImplementation(() => true); writeSpy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => {}); copyFileSpy = jest.spyOn(fs, 'copyFileSync').mockImplementation(() => {}); ensureDirSpy = jest.spyOn(fs, 'ensureDirSync').mockImplementation(() => undefined); consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); getSpy = jest.spyOn(axios, 'get').mockImplementation(url => { return Promise.resolve({ data: url.slice(url.lastIndexOf('/') + 1) }); }); readlineSpy.mockClear(); yesNoSpy.mockClear(); writeSpy.mockClear(); copyFileSpy.mockClear(); ensureDirSpy.mockClear(); consoleSpy.mockClear(); getSpy.mockClear(); }); it('should initialize a default project when no user input is given', async () => { await init(); expect(readlineSpy.mock.calls).toEqual([ ['Name (Default: ExampleIG): '], ['Id (Default: fhir.example): '], ['Canonical (Default: http://example.org): '], ['Status (Default: draft): '], ['Version (Default: 0.1.0): '], ['Publisher Name (Default: Example Publisher): '], ['Publisher Url (Default: http://example.org/example-publisher): '] ]); expect(yesNoSpy.mock.calls).toHaveLength(1); expect(yesNoSpy.mock.calls[0][0]).toMatch(/Initialize SUSHI project in .*ExampleIG/); expect(ensureDirSpy.mock.calls).toHaveLength(2); expect(ensureDirSpy.mock.calls[0][0]).toMatch(/.*ExampleIG.*input.*pagecontent/); expect(ensureDirSpy.mock.calls[1][0]).toMatch(/.*ExampleIG.*input.*fsh/); expect(writeSpy.mock.calls).toHaveLength(7); expect(writeSpy.mock.calls[0][0]).toMatch(/.*index\.md/); expect(writeSpy.mock.calls[0][1]).toMatch(/# ExampleIG/); expect(writeSpy.mock.calls[1][0]).toMatch(/.*ig\.ini/); expect(writeSpy.mock.calls[1][1]).toMatch(/fhir.example/); expect(writeSpy.mock.calls[2][0]).toMatch(/.*sushi-config\.yaml/); expect(writeSpy.mock.calls[2][1].replace(/[\n\r]/g, '')).toBe( fs .readFileSync( path.join(__dirname, 'fixtures', 'init-config', 'default-config.yaml'), 'utf-8' ) .replace(/[\n\r]/g, '') ); expect(copyFileSpy.mock.calls).toHaveLength(3); expect(copyFileSpy.mock.calls[0][1]).toMatch(/.*ExampleIG.*fsh.*patient.fsh/); expect(copyFileSpy.mock.calls[1][1]).toMatch(/.*ExampleIG.*\.gitignore/); expect(copyFileSpy.mock.calls[2][1]).toMatch(/.*ExampleIG.*input.*ignoreWarnings\.txt/); expect(getSpy.mock.calls).toHaveLength(4); const base = 'http://raw.githubusercontent.com/HL7/ig-publisher-scripts/main/'; expect(getSpy.mock.calls[0][0]).toBe(base + '_genonce.bat'); expect(getSpy.mock.calls[1][0]).toBe(base + '_genonce.sh'); expect(getSpy.mock.calls[2][0]).toBe(base + '_updatePublisher.bat'); expect(getSpy.mock.calls[3][0]).toBe(base + '_updatePublisher.sh'); expect(writeSpy.mock.calls[3][0]).toMatch(/.*_genonce\.bat/); expect(writeSpy.mock.calls[3][1]).toMatch(/_genonce\.bat/); expect(writeSpy.mock.calls[4][0]).toMatch(/.*_genonce\.sh/); expect(writeSpy.mock.calls[4][1]).toMatch(/_genonce\.sh/); expect(writeSpy.mock.calls[5][0]).toMatch(/.*_updatePublisher\.bat/); expect(writeSpy.mock.calls[5][1]).toMatch(/_updatePublisher\.bat/); expect(writeSpy.mock.calls[6][0]).toMatch(/.*_updatePublisher\.sh/); expect(writeSpy.mock.calls[6][1]).toMatch(/_updatePublisher\.sh/); }); it('should initialize a project with user input', async () => { readlineSpy.mockImplementation((question: string) => { if (question.startsWith('Name')) { return 'MyNonDefaultName'; } else if (question.startsWith('Id')) { return 'foo.bar'; } else if (question.startsWith('Canonical')) { return 'http://foo.com'; } else if (question.startsWith('Status')) { return 'active'; } else if (question.startsWith('Version')) { return '2.0.0'; } else if (question.startsWith('Publisher Name')) { return 'SUSHI Chefs'; } else if (question.startsWith('Publisher Url')) { return 'http://custom-publisher.org'; } }); await init(); expect(readlineSpy.mock.calls).toEqual([ ['Name (Default: ExampleIG): '], ['Id (Default: fhir.example): '], ['Canonical (Default: http://example.org): '], ['Status (Default: draft): '], ['Version (Default: 0.1.0): '], ['Publisher Name (Default: Example Publisher): '], ['Publisher Url (Default: http://example.org/example-publisher): '] ]); expect(yesNoSpy.mock.calls).toHaveLength(1); expect(yesNoSpy.mock.calls[0][0]).toMatch(/Initialize SUSHI project in .*MyNonDefaultName/); expect(ensureDirSpy.mock.calls).toHaveLength(2); expect(ensureDirSpy.mock.calls[0][0]).toMatch(/.*MyNonDefaultName.*input.*pagecontent/); expect(ensureDirSpy.mock.calls[1][0]).toMatch(/.*MyNonDefaultName.*input.*fsh/); expect(writeSpy.mock.calls).toHaveLength(7); expect(writeSpy.mock.calls[0][0]).toMatch(/.*index\.md/); expect(writeSpy.mock.calls[0][1]).toMatch(/# MyNonDefaultName/); expect(writeSpy.mock.calls[1][0]).toMatch(/.*ig\.ini/); expect(writeSpy.mock.calls[1][1]).toMatch(/foo.bar/); expect(writeSpy.mock.calls[2][0]).toMatch(/.*sushi-config\.yaml/); expect(writeSpy.mock.calls[2][1].replace(/[\n\r]/g, '')).toBe( fs .readFileSync( path.join(__dirname, 'fixtures', 'init-config', 'user-input-config.yaml'), 'utf-8' ) .replace(/[\n\r]/g, '') ); expect(copyFileSpy.mock.calls).toHaveLength(3); expect(copyFileSpy.mock.calls[0][1]).toMatch(/.*MyNonDefaultName.*fsh.*patient.fsh/); expect(copyFileSpy.mock.calls[1][1]).toMatch(/.*MyNonDefaultName.*\.gitignore/); expect(copyFileSpy.mock.calls[2][1]).toMatch( /.*MyNonDefaultName.*input.*ignoreWarnings\.txt/ ); expect(getSpy.mock.calls).toHaveLength(4); const base = 'http://raw.githubusercontent.com/HL7/ig-publisher-scripts/main/'; expect(getSpy.mock.calls[0][0]).toBe(base + '_genonce.bat'); expect(getSpy.mock.calls[1][0]).toBe(base + '_genonce.sh'); expect(getSpy.mock.calls[2][0]).toBe(base + '_updatePublisher.bat'); expect(getSpy.mock.calls[3][0]).toBe(base + '_updatePublisher.sh'); expect(writeSpy.mock.calls[3][0]).toMatch(/.*_genonce\.bat/); expect(writeSpy.mock.calls[3][1]).toMatch(/_genonce\.bat/); expect(writeSpy.mock.calls[4][0]).toMatch(/.*_genonce\.sh/); expect(writeSpy.mock.calls[4][1]).toMatch(/_genonce\.sh/); expect(writeSpy.mock.calls[5][0]).toMatch(/.*_updatePublisher\.bat/); expect(writeSpy.mock.calls[5][1]).toMatch(/_updatePublisher\.bat/); expect(writeSpy.mock.calls[6][0]).toMatch(/.*_updatePublisher\.sh/); expect(writeSpy.mock.calls[6][1]).toMatch(/_updatePublisher\.sh/); }); it('should abort initalizing a project when the user does not confirm', async () => { yesNoSpy.mockImplementation(() => false); await init(); expect(readlineSpy.mock.calls).toEqual([ ['Name (Default: ExampleIG): '], ['Id (Default: fhir.example): '], ['Canonical (Default: http://example.org): '], ['Status (Default: draft): '], ['Version (Default: 0.1.0): '], ['Publisher Name (Default: Example Publisher): '], ['Publisher Url (Default: http://example.org/example-publisher): '] ]); expect(yesNoSpy.mock.calls).toHaveLength(1); expect(yesNoSpy.mock.calls[0][0]).toMatch(/Initialize SUSHI project in .*ExampleIG/); expect(ensureDirSpy.mock.calls).toHaveLength(0); expect(writeSpy.mock.calls).toHaveLength(0); expect(copyFileSpy.mock.calls).toHaveLength(0); expect(consoleSpy.mock.calls.slice(-1)[0]).toEqual(['\nAborting Initialization.\n']); }); }); });
the_stack
import {parallel} from './change-detection'; import {TestElement} from './test-element'; /** An async function that returns a promise when called. */ export type AsyncFactoryFn<T> = () => Promise<T>; /** An async function that takes an item and returns a boolean promise */ export type AsyncPredicate<T> = (item: T) => Promise<boolean>; /** An async function that takes an item and an option value and returns a boolean promise. */ export type AsyncOptionPredicate<T, O> = (item: T, option: O) => Promise<boolean>; /** * A query for a `ComponentHarness`, which is expressed as either a `ComponentHarnessConstructor` or * a `HarnessPredicate`. */ export type HarnessQuery<T extends ComponentHarness> = | ComponentHarnessConstructor<T> | HarnessPredicate<T>; /** * The result type obtained when searching using a particular list of queries. This type depends on * the particular items being queried. * - If one of the queries is for a `ComponentHarnessConstructor<C1>`, it means that the result * might be a harness of type `C1` * - If one of the queries is for a `HarnessPredicate<C2>`, it means that the result might be a * harness of type `C2` * - If one of the queries is for a `string`, it means that the result might be a `TestElement`. * * Since we don't know for sure which query will match, the result type if the union of the types * for all possible results. * * e.g. * The type: * `LocatorFnResult&lt;[ * ComponentHarnessConstructor&lt;MyHarness&gt;, * HarnessPredicate&lt;MyOtherHarness&gt;, * string * ]&gt;` * is equivalent to: * `MyHarness | MyOtherHarness | TestElement`. */ export type LocatorFnResult<T extends (HarnessQuery<any> | string)[]> = { [I in keyof T]: T[I] extends new (...args: any[]) => infer C // Map `ComponentHarnessConstructor<C>` to `C`. ? C : // Map `HarnessPredicate<C>` to `C`. T[I] extends {harnessType: new (...args: any[]) => infer C} ? C : // Map `string` to `TestElement`. T[I] extends string ? TestElement : // Map everything else to `never` (should not happen due to the type constraint on `T`). never; }[number]; /** * Interface used to load ComponentHarness objects. This interface is used by test authors to * instantiate `ComponentHarness`es. */ export interface HarnessLoader { /** * Searches for an element with the given selector under the current instances's root element, * and returns a `HarnessLoader` rooted at the matching element. If multiple elements match the * selector, the first is used. If no elements match, an error is thrown. * @param selector The selector for the root element of the new `HarnessLoader` * @return A `HarnessLoader` rooted at the element matching the given selector. * @throws If a matching element can't be found. */ getChildLoader(selector: string): Promise<HarnessLoader>; /** * Searches for all elements with the given selector under the current instances's root element, * and returns an array of `HarnessLoader`s, one for each matching element, rooted at that * element. * @param selector The selector for the root element of the new `HarnessLoader` * @return A list of `HarnessLoader`s, one for each matching element, rooted at that element. */ getAllChildLoaders(selector: string): Promise<HarnessLoader[]>; /** * Searches for an instance of the component corresponding to the given harness type under the * `HarnessLoader`'s root element, and returns a `ComponentHarness` for that instance. If multiple * matching components are found, a harness for the first one is returned. If no matching * component is found, an error is thrown. * @param query A query for a harness to create * @return An instance of the given harness type * @throws If a matching component instance can't be found. */ getHarness<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T>; /** * Searches for an instance of the component corresponding to the given harness type under the * `HarnessLoader`'s root element, and returns a `ComponentHarness` for that instance. If multiple * matching components are found, a harness for the first one is returned. If no matching * component is found, null is returned. * @param query A query for a harness to create * @return An instance of the given harness type (or null if not found). */ getHarnessOrNull<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T | null>; /** * Searches for all instances of the component corresponding to the given harness type under the * `HarnessLoader`'s root element, and returns a list `ComponentHarness` for each instance. * @param query A query for a harness to create * @return A list instances of the given harness type. */ getAllHarnesses<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T[]>; /** * Searches for an instance of the component corresponding to the given harness type under the * `HarnessLoader`'s root element, and returns a boolean indicating if any were found. * @param query A query for a harness to create * @return A boolean indicating if an instance was found. */ hasHarness<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<boolean>; } /** * Interface used to create asynchronous locator functions used find elements and component * harnesses. This interface is used by `ComponentHarness` authors to create locator functions for * their `ComponentHarness` subclass. */ export interface LocatorFactory { /** Gets a locator factory rooted at the document root. */ documentRootLocatorFactory(): LocatorFactory; /** The root element of this `LocatorFactory` as a `TestElement`. */ rootElement: TestElement; /** * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance * or element under the root element of this `LocatorFactory`. * @param queries A list of queries specifying which harnesses and elements to search for: * - A `string` searches for elements matching the CSS selector specified by the string. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the * given class. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given * predicate. * @return An asynchronous locator function that searches for and returns a `Promise` for the * first element or harness matching the given search criteria. Matches are ordered first by * order in the DOM, and second by order in the queries list. If no matches are found, the * `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for * each query. * * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming * `DivHarness.hostSelector === 'div'`: * - `await lf.locatorFor(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1` * - `await lf.locatorFor('div', DivHarness)()` gets a `TestElement` instance for `#d1` * - `await lf.locatorFor('span')()` throws because the `Promise` rejects. */ locatorFor<T extends (HarnessQuery<any> | string)[]>( ...queries: T ): AsyncFactoryFn<LocatorFnResult<T>>; /** * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance * or element under the root element of this `LocatorFactory`. * @param queries A list of queries specifying which harnesses and elements to search for: * - A `string` searches for elements matching the CSS selector specified by the string. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the * given class. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given * predicate. * @return An asynchronous locator function that searches for and returns a `Promise` for the * first element or harness matching the given search criteria. Matches are ordered first by * order in the DOM, and second by order in the queries list. If no matches are found, the * `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all * result types for each query or null. * * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming * `DivHarness.hostSelector === 'div'`: * - `await lf.locatorForOptional(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1` * - `await lf.locatorForOptional('div', DivHarness)()` gets a `TestElement` instance for `#d1` * - `await lf.locatorForOptional('span')()` gets `null`. */ locatorForOptional<T extends (HarnessQuery<any> | string)[]>( ...queries: T ): AsyncFactoryFn<LocatorFnResult<T> | null>; /** * Creates an asynchronous locator function that can be used to find `ComponentHarness` instances * or elements under the root element of this `LocatorFactory`. * @param queries A list of queries specifying which harnesses and elements to search for: * - A `string` searches for elements matching the CSS selector specified by the string. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the * given class. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given * predicate. * @return An asynchronous locator function that searches for and returns a `Promise` for all * elements and harnesses matching the given search criteria. Matches are ordered first by * order in the DOM, and second by order in the queries list. If an element matches more than * one `ComponentHarness` class, the locator gets an instance of each for the same element. If * an element matches multiple `string` selectors, only one `TestElement` instance is returned * for that element. The type that the `Promise` resolves to is an array where each element is * the union of all result types for each query. * * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming * `DivHarness.hostSelector === 'div'` and `IdIsD1Harness.hostSelector === '#d1'`: * - `await lf.locatorForAll(DivHarness, 'div')()` gets `[ * DivHarness, // for #d1 * TestElement, // for #d1 * DivHarness, // for #d2 * TestElement // for #d2 * ]` * - `await lf.locatorForAll('div', '#d1')()` gets `[ * TestElement, // for #d1 * TestElement // for #d2 * ]` * - `await lf.locatorForAll(DivHarness, IdIsD1Harness)()` gets `[ * DivHarness, // for #d1 * IdIsD1Harness, // for #d1 * DivHarness // for #d2 * ]` * - `await lf.locatorForAll('span')()` gets `[]`. */ locatorForAll<T extends (HarnessQuery<any> | string)[]>( ...queries: T ): AsyncFactoryFn<LocatorFnResult<T>[]>; /** @return A `HarnessLoader` rooted at the root element of this `LocatorFactory`. */ rootHarnessLoader(): Promise<HarnessLoader>; /** * Gets a `HarnessLoader` instance for an element under the root of this `LocatorFactory`. * @param selector The selector for the root element. * @return A `HarnessLoader` rooted at the first element matching the given selector. * @throws If no matching element is found for the given selector. */ harnessLoaderFor(selector: string): Promise<HarnessLoader>; /** * Gets a `HarnessLoader` instance for an element under the root of this `LocatorFactory` * @param selector The selector for the root element. * @return A `HarnessLoader` rooted at the first element matching the given selector, or null if * no matching element is found. */ harnessLoaderForOptional(selector: string): Promise<HarnessLoader | null>; /** * Gets a list of `HarnessLoader` instances, one for each matching element. * @param selector The selector for the root element. * @return A list of `HarnessLoader`, one rooted at each element matching the given selector. */ harnessLoaderForAll(selector: string): Promise<HarnessLoader[]>; /** * Flushes change detection and async tasks captured in the Angular zone. * In most cases it should not be necessary to call this manually. However, there may be some edge * cases where it is needed to fully flush animation events. */ forceStabilize(): Promise<void>; /** * Waits for all scheduled or running async tasks to complete. This allows harness * authors to wait for async tasks outside of the Angular zone. */ waitForTasksOutsideAngular(): Promise<void>; } /** * Base class for component harnesses that all component harness authors should extend. This base * component harness provides the basic ability to locate element and sub-component harness. It * should be inherited when defining user's own harness. */ export abstract class ComponentHarness { constructor(protected readonly locatorFactory: LocatorFactory) {} /** Gets a `Promise` for the `TestElement` representing the host element of the component. */ async host(): Promise<TestElement> { return this.locatorFactory.rootElement; } /** * Gets a `LocatorFactory` for the document root element. This factory can be used to create * locators for elements that a component creates outside of its own root element. (e.g. by * appending to document.body). */ protected documentRootLocatorFactory(): LocatorFactory { return this.locatorFactory.documentRootLocatorFactory(); } /** * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance * or element under the host element of this `ComponentHarness`. * @param queries A list of queries specifying which harnesses and elements to search for: * - A `string` searches for elements matching the CSS selector specified by the string. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the * given class. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given * predicate. * @return An asynchronous locator function that searches for and returns a `Promise` for the * first element or harness matching the given search criteria. Matches are ordered first by * order in the DOM, and second by order in the queries list. If no matches are found, the * `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for * each query. * * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming * `DivHarness.hostSelector === 'div'`: * - `await ch.locatorFor(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1` * - `await ch.locatorFor('div', DivHarness)()` gets a `TestElement` instance for `#d1` * - `await ch.locatorFor('span')()` throws because the `Promise` rejects. */ protected locatorFor<T extends (HarnessQuery<any> | string)[]>( ...queries: T ): AsyncFactoryFn<LocatorFnResult<T>> { return this.locatorFactory.locatorFor(...queries); } /** * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance * or element under the host element of this `ComponentHarness`. * @param queries A list of queries specifying which harnesses and elements to search for: * - A `string` searches for elements matching the CSS selector specified by the string. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the * given class. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given * predicate. * @return An asynchronous locator function that searches for and returns a `Promise` for the * first element or harness matching the given search criteria. Matches are ordered first by * order in the DOM, and second by order in the queries list. If no matches are found, the * `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all * result types for each query or null. * * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming * `DivHarness.hostSelector === 'div'`: * - `await ch.locatorForOptional(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1` * - `await ch.locatorForOptional('div', DivHarness)()` gets a `TestElement` instance for `#d1` * - `await ch.locatorForOptional('span')()` gets `null`. */ protected locatorForOptional<T extends (HarnessQuery<any> | string)[]>( ...queries: T ): AsyncFactoryFn<LocatorFnResult<T> | null> { return this.locatorFactory.locatorForOptional(...queries); } /** * Creates an asynchronous locator function that can be used to find `ComponentHarness` instances * or elements under the host element of this `ComponentHarness`. * @param queries A list of queries specifying which harnesses and elements to search for: * - A `string` searches for elements matching the CSS selector specified by the string. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the * given class. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given * predicate. * @return An asynchronous locator function that searches for and returns a `Promise` for all * elements and harnesses matching the given search criteria. Matches are ordered first by * order in the DOM, and second by order in the queries list. If an element matches more than * one `ComponentHarness` class, the locator gets an instance of each for the same element. If * an element matches multiple `string` selectors, only one `TestElement` instance is returned * for that element. The type that the `Promise` resolves to is an array where each element is * the union of all result types for each query. * * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming * `DivHarness.hostSelector === 'div'` and `IdIsD1Harness.hostSelector === '#d1'`: * - `await ch.locatorForAll(DivHarness, 'div')()` gets `[ * DivHarness, // for #d1 * TestElement, // for #d1 * DivHarness, // for #d2 * TestElement // for #d2 * ]` * - `await ch.locatorForAll('div', '#d1')()` gets `[ * TestElement, // for #d1 * TestElement // for #d2 * ]` * - `await ch.locatorForAll(DivHarness, IdIsD1Harness)()` gets `[ * DivHarness, // for #d1 * IdIsD1Harness, // for #d1 * DivHarness // for #d2 * ]` * - `await ch.locatorForAll('span')()` gets `[]`. */ protected locatorForAll<T extends (HarnessQuery<any> | string)[]>( ...queries: T ): AsyncFactoryFn<LocatorFnResult<T>[]> { return this.locatorFactory.locatorForAll(...queries); } /** * Flushes change detection and async tasks in the Angular zone. * In most cases it should not be necessary to call this manually. However, there may be some edge * cases where it is needed to fully flush animation events. */ protected async forceStabilize() { return this.locatorFactory.forceStabilize(); } /** * Waits for all scheduled or running async tasks to complete. This allows harness * authors to wait for async tasks outside of the Angular zone. */ protected async waitForTasksOutsideAngular() { return this.locatorFactory.waitForTasksOutsideAngular(); } } /** * Base class for component harnesses that authors should extend if they anticipate that consumers * of the harness may want to access other harnesses within the `<ng-content>` of the component. */ export abstract class ContentContainerComponentHarness<S extends string = string> extends ComponentHarness implements HarnessLoader { async getChildLoader(selector: S): Promise<HarnessLoader> { return (await this.getRootHarnessLoader()).getChildLoader(selector); } async getAllChildLoaders(selector: S): Promise<HarnessLoader[]> { return (await this.getRootHarnessLoader()).getAllChildLoaders(selector); } async getHarness<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T> { return (await this.getRootHarnessLoader()).getHarness(query); } async getHarnessOrNull<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T | null> { return (await this.getRootHarnessLoader()).getHarnessOrNull(query); } async getAllHarnesses<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T[]> { return (await this.getRootHarnessLoader()).getAllHarnesses(query); } async hasHarness<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<boolean> { return (await this.getRootHarnessLoader()).hasHarness(query); } /** * Gets the root harness loader from which to start * searching for content contained by this harness. */ protected async getRootHarnessLoader(): Promise<HarnessLoader> { return this.locatorFactory.rootHarnessLoader(); } } /** Constructor for a ComponentHarness subclass. */ export interface ComponentHarnessConstructor<T extends ComponentHarness> { new (locatorFactory: LocatorFactory): T; /** * `ComponentHarness` subclasses must specify a static `hostSelector` property that is used to * find the host element for the corresponding component. This property should match the selector * for the Angular component. */ hostSelector: string; } /** A set of criteria that can be used to filter a list of `ComponentHarness` instances. */ export interface BaseHarnessFilters { /** Only find instances whose host element matches the given selector. */ selector?: string; /** Only find instances that are nested under an element with the given selector. */ ancestor?: string; } /** * A class used to associate a ComponentHarness class with predicates functions that can be used to * filter instances of the class. */ export class HarnessPredicate<T extends ComponentHarness> { private _predicates: AsyncPredicate<T>[] = []; private _descriptions: string[] = []; private _ancestor: string; constructor(public harnessType: ComponentHarnessConstructor<T>, options: BaseHarnessFilters) { this._addBaseOptions(options); } /** * Checks if the specified nullable string value matches the given pattern. * @param value The nullable string value to check, or a Promise resolving to the * nullable string value. * @param pattern The pattern the value is expected to match. If `pattern` is a string, * `value` is expected to match exactly. If `pattern` is a regex, a partial match is * allowed. If `pattern` is `null`, the value is expected to be `null`. * @return Whether the value matches the pattern. */ static async stringMatches( value: string | null | Promise<string | null>, pattern: string | RegExp | null, ): Promise<boolean> { value = await value; if (pattern === null) { return value === null; } else if (value === null) { return false; } return typeof pattern === 'string' ? value === pattern : pattern.test(value); } /** * Adds a predicate function to be run against candidate harnesses. * @param description A description of this predicate that may be used in error messages. * @param predicate An async predicate function. * @return this (for method chaining). */ add(description: string, predicate: AsyncPredicate<T>) { this._descriptions.push(description); this._predicates.push(predicate); return this; } /** * Adds a predicate function that depends on an option value to be run against candidate * harnesses. If the option value is undefined, the predicate will be ignored. * @param name The name of the option (may be used in error messages). * @param option The option value. * @param predicate The predicate function to run if the option value is not undefined. * @return this (for method chaining). */ addOption<O>(name: string, option: O | undefined, predicate: AsyncOptionPredicate<T, O>) { if (option !== undefined) { this.add(`${name} = ${_valueAsString(option)}`, item => predicate(item, option)); } return this; } /** * Filters a list of harnesses on this predicate. * @param harnesses The list of harnesses to filter. * @return A list of harnesses that satisfy this predicate. */ async filter(harnesses: T[]): Promise<T[]> { if (harnesses.length === 0) { return []; } const results = await parallel(() => harnesses.map(h => this.evaluate(h))); return harnesses.filter((_, i) => results[i]); } /** * Evaluates whether the given harness satisfies this predicate. * @param harness The harness to check * @return A promise that resolves to true if the harness satisfies this predicate, * and resolves to false otherwise. */ async evaluate(harness: T): Promise<boolean> { const results = await parallel(() => this._predicates.map(p => p(harness))); return results.reduce((combined, current) => combined && current, true); } /** Gets a description of this predicate for use in error messages. */ getDescription() { return this._descriptions.join(', '); } /** Gets the selector used to find candidate elements. */ getSelector() { // We don't have to go through the extra trouble if there are no ancestors. if (!this._ancestor) { return (this.harnessType.hostSelector || '').trim(); } const [ancestors, ancestorPlaceholders] = _splitAndEscapeSelector(this._ancestor); const [selectors, selectorPlaceholders] = _splitAndEscapeSelector( this.harnessType.hostSelector || '', ); const result: string[] = []; // We have to add the ancestor to each part of the host compound selector, otherwise we can get // incorrect results. E.g. `.ancestor .a, .ancestor .b` vs `.ancestor .a, .b`. ancestors.forEach(escapedAncestor => { const ancestor = _restoreSelector(escapedAncestor, ancestorPlaceholders); return selectors.forEach(escapedSelector => result.push(`${ancestor} ${_restoreSelector(escapedSelector, selectorPlaceholders)}`), ); }); return result.join(', '); } /** Adds base options common to all harness types. */ private _addBaseOptions(options: BaseHarnessFilters) { this._ancestor = options.ancestor || ''; if (this._ancestor) { this._descriptions.push(`has ancestor matching selector "${this._ancestor}"`); } const selector = options.selector; if (selector !== undefined) { this.add(`host matches selector "${selector}"`, async item => { return (await item.host()).matchesSelector(selector); }); } } } /** Represent a value as a string for the purpose of logging. */ function _valueAsString(value: unknown) { if (value === undefined) { return 'undefined'; } try { // `JSON.stringify` doesn't handle RegExp properly, so we need a custom replacer. // Use a character that is unlikely to appear in real strings to denote the start and end of // the regex. This allows us to strip out the extra quotes around the value added by // `JSON.stringify`. Also do custom escaping on `"` characters to prevent `JSON.stringify` // from escaping them as if they were part of a string. const stringifiedValue = JSON.stringify(value, (_, v) => v instanceof RegExp ? `◬MAT_RE_ESCAPE◬${v.toString().replace(/"/g, '◬MAT_RE_ESCAPE◬')}◬MAT_RE_ESCAPE◬` : v, ); // Strip out the extra quotes around regexes and put back the manually escaped `"` characters. return stringifiedValue .replace(/"◬MAT_RE_ESCAPE◬|◬MAT_RE_ESCAPE◬"/g, '') .replace(/◬MAT_RE_ESCAPE◬/g, '"'); } catch { // `JSON.stringify` will throw if the object is cyclical, // in this case the best we can do is report the value as `{...}`. return '{...}'; } } /** * Splits up a compound selector into its parts and escapes any quoted content. The quoted content * has to be escaped, because it can contain commas which will throw throw us off when trying to * split it. * @param selector Selector to be split. * @returns The escaped string where any quoted content is replaced with a placeholder. E.g. * `[foo="bar"]` turns into `[foo=__cdkPlaceholder-0__]`. Use `_restoreSelector` to restore * the placeholders. */ function _splitAndEscapeSelector(selector: string): [parts: string[], placeholders: string[]] { const placeholders: string[] = []; // Note that the regex doesn't account for nested quotes so something like `"ab'cd'e"` will be // considered as two blocks. It's a bit of an edge case, but if we find that it's a problem, // we can make it a bit smarter using a loop. Use this for now since it's more readable and // compact. More complete implementation: // https://github.com/angular/angular/blob/bd34bc9e89f18a/packages/compiler/src/shadow_css.ts#L655 const result = selector.replace(/(["'][^["']*["'])/g, (_, keep) => { const replaceBy = `__cdkPlaceholder-${placeholders.length}__`; placeholders.push(keep); return replaceBy; }); return [result.split(',').map(part => part.trim()), placeholders]; } /** Restores a selector whose content was escaped in `_splitAndEscapeSelector`. */ function _restoreSelector(selector: string, placeholders: string[]): string { return selector.replace(/__cdkPlaceholder-(\d+)__/g, (_, index) => placeholders[+index]); }
the_stack
import { IUserDataSyncService, SyncStatus, IUserDataSyncStoreService, SyncResource, IUserDataSyncLogService, IUserDataSynchroniser, UserDataSyncErrorCode, UserDataSyncError, ISyncResourceHandle, IUserDataManifest, ISyncTask, IResourcePreview, IManualSyncTask, ISyncResourcePreview, MergeState, Change, IUserDataSyncStoreManagementService, UserDataSyncStoreError, createSyncHeaders } from 'vs/platform/userDataSync/common/userDataSync'; import { Disposable } from 'vs/base/common/lifecycle'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Emitter, Event } from 'vs/base/common/event'; import { ExtensionsSynchroniser } from 'vs/platform/userDataSync/common/extensionsSync'; import { KeybindingsSynchroniser } from 'vs/platform/userDataSync/common/keybindingsSync'; import { GlobalStateSynchroniser } from 'vs/platform/userDataSync/common/globalStateSync'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { equals } from 'vs/base/common/arrays'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { URI } from 'vs/base/common/uri'; import { SettingsSynchroniser } from 'vs/platform/userDataSync/common/settingsSync'; import { isEqual } from 'vs/base/common/resources'; import { SnippetsSynchroniser } from 'vs/platform/userDataSync/common/snippetsSync'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IHeaders } from 'vs/base/parts/request/common/request'; import { generateUuid } from 'vs/base/common/uuid'; import { createCancelablePromise, CancelablePromise } from 'vs/base/common/async'; import { isPromiseCanceledError } from 'vs/base/common/errors'; type SyncErrorClassification = { code: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; service: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; url?: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; resource?: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; executionId?: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; }; const LAST_SYNC_TIME_KEY = 'sync.lastSyncTime'; export class UserDataSyncService extends Disposable implements IUserDataSyncService { _serviceBrand: any; private readonly synchronisers: IUserDataSynchroniser[]; private _status: SyncStatus = SyncStatus.Uninitialized; get status(): SyncStatus { return this._status; } private _onDidChangeStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>()); readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangeStatus.event; readonly onDidChangeLocal: Event<SyncResource>; private _conflicts: [SyncResource, IResourcePreview[]][] = []; get conflicts(): [SyncResource, IResourcePreview[]][] { return this._conflicts; } private _onDidChangeConflicts: Emitter<[SyncResource, IResourcePreview[]][]> = this._register(new Emitter<[SyncResource, IResourcePreview[]][]>()); readonly onDidChangeConflicts: Event<[SyncResource, IResourcePreview[]][]> = this._onDidChangeConflicts.event; private _syncErrors: [SyncResource, UserDataSyncError][] = []; private _onSyncErrors: Emitter<[SyncResource, UserDataSyncError][]> = this._register(new Emitter<[SyncResource, UserDataSyncError][]>()); readonly onSyncErrors: Event<[SyncResource, UserDataSyncError][]> = this._onSyncErrors.event; private _lastSyncTime: number | undefined = undefined; get lastSyncTime(): number | undefined { return this._lastSyncTime; } private _onDidChangeLastSyncTime: Emitter<number> = this._register(new Emitter<number>()); readonly onDidChangeLastSyncTime: Event<number> = this._onDidChangeLastSyncTime.event; private _onDidResetLocal = this._register(new Emitter<void>()); readonly onDidResetLocal = this._onDidResetLocal.event; private _onDidResetRemote = this._register(new Emitter<void>()); readonly onDidResetRemote = this._onDidResetRemote.event; private readonly settingsSynchroniser: SettingsSynchroniser; private readonly keybindingsSynchroniser: KeybindingsSynchroniser; private readonly snippetsSynchroniser: SnippetsSynchroniser; private readonly extensionsSynchroniser: ExtensionsSynchroniser; private readonly globalStateSynchroniser: GlobalStateSynchroniser; constructor( @IUserDataSyncStoreService private readonly userDataSyncStoreService: IUserDataSyncStoreService, @IUserDataSyncStoreManagementService private readonly userDataSyncStoreManagementService: IUserDataSyncStoreManagementService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IStorageService private readonly storageService: IStorageService, ) { super(); this.settingsSynchroniser = this._register(this.instantiationService.createInstance(SettingsSynchroniser)); this.keybindingsSynchroniser = this._register(this.instantiationService.createInstance(KeybindingsSynchroniser)); this.snippetsSynchroniser = this._register(this.instantiationService.createInstance(SnippetsSynchroniser)); this.globalStateSynchroniser = this._register(this.instantiationService.createInstance(GlobalStateSynchroniser)); this.extensionsSynchroniser = this._register(this.instantiationService.createInstance(ExtensionsSynchroniser)); this.synchronisers = [this.settingsSynchroniser, this.keybindingsSynchroniser, this.snippetsSynchroniser, this.globalStateSynchroniser, this.extensionsSynchroniser]; this.updateStatus(); if (this.userDataSyncStoreManagementService.userDataSyncStore) { this._register(Event.any(...this.synchronisers.map(s => Event.map(s.onDidChangeStatus, () => undefined)))(() => this.updateStatus())); this._register(Event.any(...this.synchronisers.map(s => Event.map(s.onDidChangeConflicts, () => undefined)))(() => this.updateConflicts())); } this._lastSyncTime = this.storageService.getNumber(LAST_SYNC_TIME_KEY, StorageScope.GLOBAL, undefined); this.onDidChangeLocal = Event.any(...this.synchronisers.map(s => Event.map(s.onDidChangeLocal, () => s.resource))); } async createSyncTask(disableCache?: boolean): Promise<ISyncTask> { await this.checkEnablement(); const executionId = generateUuid(); let manifest: IUserDataManifest | null; try { const syncHeaders = createSyncHeaders(executionId); if (disableCache) { syncHeaders['Cache-Control'] = 'no-cache'; } manifest = await this.userDataSyncStoreService.manifest(syncHeaders); } catch (error) { const userDataSyncError = UserDataSyncError.toUserDataSyncError(error); this.reportUserDataSyncError(userDataSyncError, executionId); throw userDataSyncError; } let executed = false; const that = this; let cancellablePromise: CancelablePromise<void> | undefined; return { manifest, run(): Promise<void> { if (executed) { throw new Error('Can run a task only once'); } cancellablePromise = createCancelablePromise(token => that.sync(manifest, executionId, token)); return cancellablePromise.finally(() => cancellablePromise = undefined); }, async stop(): Promise<void> { if (cancellablePromise) { cancellablePromise.cancel(); } if (that.status !== SyncStatus.Idle) { return that.stop(); } } }; } async createManualSyncTask(): Promise<IManualSyncTask> { await this.checkEnablement(); const executionId = generateUuid(); const syncHeaders = createSyncHeaders(executionId); let manifest: IUserDataManifest | null; try { manifest = await this.userDataSyncStoreService.manifest(syncHeaders); } catch (error) { const userDataSyncError = UserDataSyncError.toUserDataSyncError(error); this.reportUserDataSyncError(userDataSyncError, executionId); throw userDataSyncError; } return new ManualSyncTask(executionId, manifest, syncHeaders, this.synchronisers, this.logService); } private recoveredSettings: boolean = false; private async sync(manifest: IUserDataManifest | null, executionId: string, token: CancellationToken): Promise<void> { if (!this.recoveredSettings) { await this.settingsSynchroniser.recoverSettings(); this.recoveredSettings = true; } // Return if cancellation is requested if (token.isCancellationRequested) { return; } const startTime = new Date().getTime(); this._syncErrors = []; try { this.logService.trace('Sync started.'); if (this.status !== SyncStatus.HasConflicts) { this.setStatus(SyncStatus.Syncing); } const syncHeaders = createSyncHeaders(executionId); for (const synchroniser of this.synchronisers) { // Return if cancellation is requested if (token.isCancellationRequested) { return; } try { await synchroniser.sync(manifest, syncHeaders); } catch (e) { if (e instanceof UserDataSyncError) { // Bail out for following errors switch (e.code) { case UserDataSyncErrorCode.TooLarge: throw new UserDataSyncError(e.message, e.code, synchroniser.resource); case UserDataSyncErrorCode.TooManyRequests: case UserDataSyncErrorCode.TooManyRequestsAndRetryAfter: case UserDataSyncErrorCode.LocalTooManyRequests: case UserDataSyncErrorCode.Gone: case UserDataSyncErrorCode.UpgradeRequired: case UserDataSyncErrorCode.IncompatibleRemoteContent: case UserDataSyncErrorCode.IncompatibleLocalContent: throw e; } } // Log and report other errors and continue const userDataSyncError = UserDataSyncError.toUserDataSyncError(e); this.reportUserDataSyncError(userDataSyncError, executionId); this.logService.error(e); this.logService.error(`${synchroniser.resource}: ${toErrorMessage(e)}`); this._syncErrors.push([synchroniser.resource, userDataSyncError]); } } this.logService.info(`Sync done. Took ${new Date().getTime() - startTime}ms`); this.updateLastSyncTime(); } catch (error) { const userDataSyncError = UserDataSyncError.toUserDataSyncError(error); this.reportUserDataSyncError(userDataSyncError, executionId); throw userDataSyncError; } finally { this.updateStatus(); this._onSyncErrors.fire(this._syncErrors); } } private async stop(): Promise<void> { if (this.status === SyncStatus.Idle) { return; } for (const synchroniser of this.synchronisers) { try { if (synchroniser.status !== SyncStatus.Idle) { await synchroniser.stop(); } } catch (e) { this.logService.error(e); } } } async replace(uri: URI): Promise<void> { await this.checkEnablement(); for (const synchroniser of this.synchronisers) { if (await synchroniser.replace(uri)) { return; } } } async accept(syncResource: SyncResource, resource: URI, content: string | null | undefined, apply: boolean): Promise<void> { await this.checkEnablement(); const synchroniser = this.getSynchroniser(syncResource); await synchroniser.accept(resource, content); if (apply) { await synchroniser.apply(false, createSyncHeaders(generateUuid())); } } async resolveContent(resource: URI): Promise<string | null> { for (const synchroniser of this.synchronisers) { const content = await synchroniser.resolveContent(resource); if (content) { return content; } } return null; } getRemoteSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> { return this.getSynchroniser(resource).getRemoteSyncResourceHandles(); } getLocalSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> { return this.getSynchroniser(resource).getLocalSyncResourceHandles(); } getAssociatedResources(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<{ resource: URI, comparableResource: URI }[]> { return this.getSynchroniser(resource).getAssociatedResources(syncResourceHandle); } getMachineId(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<string | undefined> { return this.getSynchroniser(resource).getMachineId(syncResourceHandle); } async hasLocalData(): Promise<boolean> { // skip global state synchronizer const synchronizers = [this.settingsSynchroniser, this.keybindingsSynchroniser, this.snippetsSynchroniser, this.extensionsSynchroniser]; for (const synchroniser of synchronizers) { if (await synchroniser.hasLocalData()) { return true; } } return false; } async reset(): Promise<void> { await this.checkEnablement(); await this.resetRemote(); await this.resetLocal(); } async resetRemote(): Promise<void> { await this.checkEnablement(); try { await this.userDataSyncStoreService.clear(); this.logService.info('Cleared data on server'); } catch (e) { this.logService.error(e); } this._onDidResetRemote.fire(); } async resetLocal(): Promise<void> { await this.checkEnablement(); this.storageService.remove(LAST_SYNC_TIME_KEY, StorageScope.GLOBAL); for (const synchroniser of this.synchronisers) { try { await synchroniser.resetLocal(); } catch (e) { this.logService.error(`${synchroniser.resource}: ${toErrorMessage(e)}`); this.logService.error(e); } } this._onDidResetLocal.fire(); this.logService.info('Did reset the local sync state.'); } async hasPreviouslySynced(): Promise<boolean> { for (const synchroniser of this.synchronisers) { if (await synchroniser.hasPreviouslySynced()) { return true; } } return false; } private setStatus(status: SyncStatus): void { const oldStatus = this._status; if (this._status !== status) { this._status = status; this._onDidChangeStatus.fire(status); if (oldStatus === SyncStatus.HasConflicts) { this.updateLastSyncTime(); } } } private updateStatus(): void { this.updateConflicts(); const status = this.computeStatus(); this.setStatus(status); } private updateConflicts(): void { const conflicts = this.computeConflicts(); if (!equals(this._conflicts, conflicts, ([syncResourceA, conflictsA], [syncResourceB, conflictsB]) => syncResourceA === syncResourceA && equals(conflictsA, conflictsB, (a, b) => isEqual(a.previewResource, b.previewResource)))) { this._conflicts = this.computeConflicts(); this._onDidChangeConflicts.fire(conflicts); } } private computeStatus(): SyncStatus { if (!this.userDataSyncStoreManagementService.userDataSyncStore) { return SyncStatus.Uninitialized; } if (this.synchronisers.some(s => s.status === SyncStatus.HasConflicts)) { return SyncStatus.HasConflicts; } if (this.synchronisers.some(s => s.status === SyncStatus.Syncing)) { return SyncStatus.Syncing; } return SyncStatus.Idle; } private updateLastSyncTime(): void { if (this.status === SyncStatus.Idle) { this._lastSyncTime = new Date().getTime(); this.storageService.store(LAST_SYNC_TIME_KEY, this._lastSyncTime, StorageScope.GLOBAL, StorageTarget.MACHINE); this._onDidChangeLastSyncTime.fire(this._lastSyncTime); } } private reportUserDataSyncError(userDataSyncError: UserDataSyncError, executionId: string) { this.telemetryService.publicLog2<{ code: string, service: string, url?: string, resource?: string, executionId?: string }, SyncErrorClassification>('sync/error', { code: userDataSyncError.code, url: userDataSyncError instanceof UserDataSyncStoreError ? userDataSyncError.url : undefined, resource: userDataSyncError.resource, executionId, service: this.userDataSyncStoreManagementService.userDataSyncStore!.url.toString() }); } private computeConflicts(): [SyncResource, IResourcePreview[]][] { return this.synchronisers.filter(s => s.status === SyncStatus.HasConflicts) .map(s => ([s.resource, s.conflicts.map(toStrictResourcePreview)])); } getSynchroniser(source: SyncResource): IUserDataSynchroniser { return this.synchronisers.find(s => s.resource === source)!; } private async checkEnablement(): Promise<void> { if (!this.userDataSyncStoreManagementService.userDataSyncStore) { throw new Error('Not enabled'); } } } class ManualSyncTask extends Disposable implements IManualSyncTask { private previewsPromise: CancelablePromise<[SyncResource, ISyncResourcePreview][]> | undefined; private previews: [SyncResource, ISyncResourcePreview][] | undefined; private synchronizingResources: [SyncResource, URI[]][] = []; private _onSynchronizeResources = this._register(new Emitter<[SyncResource, URI[]][]>()); readonly onSynchronizeResources = this._onSynchronizeResources.event; private isDisposed: boolean = false; get status(): SyncStatus { if (this.synchronisers.some(s => s.status === SyncStatus.HasConflicts)) { return SyncStatus.HasConflicts; } if (this.synchronisers.some(s => s.status === SyncStatus.Syncing)) { return SyncStatus.Syncing; } return SyncStatus.Idle; } constructor( readonly id: string, readonly manifest: IUserDataManifest | null, private readonly syncHeaders: IHeaders, private readonly synchronisers: IUserDataSynchroniser[], private readonly logService: IUserDataSyncLogService, ) { super(); } async preview(): Promise<[SyncResource, ISyncResourcePreview][]> { try { if (this.isDisposed) { throw new Error('Disposed'); } if (!this.previewsPromise) { this.previewsPromise = createCancelablePromise(token => this.getPreviews(token)); } if (!this.previews) { this.previews = await this.previewsPromise; } return this.previews; } catch (error) { this.logService.error(error); throw error; } } async accept(resource: URI, content?: string | null): Promise<[SyncResource, ISyncResourcePreview][]> { try { return await this.performAction(resource, sychronizer => sychronizer.accept(resource, content)); } catch (error) { this.logService.error(error); throw error; } } async merge(resource?: URI): Promise<[SyncResource, ISyncResourcePreview][]> { try { if (resource) { return await this.performAction(resource, sychronizer => sychronizer.merge(resource)); } else { return await this.mergeAll(); } } catch (error) { this.logService.error(error); throw error; } } async discard(resource: URI): Promise<[SyncResource, ISyncResourcePreview][]> { try { return await this.performAction(resource, sychronizer => sychronizer.discard(resource)); } catch (error) { this.logService.error(error); throw error; } } async discardConflicts(): Promise<[SyncResource, ISyncResourcePreview][]> { try { if (!this.previews) { throw new Error('Missing preview. Create preview and try again.'); } if (this.synchronizingResources.length) { throw new Error('Cannot discard while synchronizing resources'); } const conflictResources: URI[] = []; for (const [, syncResourcePreview] of this.previews) { for (const resourcePreview of syncResourcePreview.resourcePreviews) { if (resourcePreview.mergeState === MergeState.Conflict) { conflictResources.push(resourcePreview.previewResource); } } } for (const resource of conflictResources) { await this.discard(resource); } return this.previews; } catch (error) { this.logService.error(error); throw error; } } async apply(): Promise<[SyncResource, ISyncResourcePreview][]> { try { if (!this.previews) { throw new Error('You need to create preview before applying'); } if (this.synchronizingResources.length) { throw new Error('Cannot pull while synchronizing resources'); } const previews: [SyncResource, ISyncResourcePreview][] = []; for (const [syncResource, preview] of this.previews) { this.synchronizingResources.push([syncResource, preview.resourcePreviews.map(r => r.localResource)]); this._onSynchronizeResources.fire(this.synchronizingResources); const synchroniser = this.synchronisers.find(s => s.resource === syncResource)!; /* merge those which are not yet merged */ for (const resourcePreview of preview.resourcePreviews) { if ((resourcePreview.localChange !== Change.None || resourcePreview.remoteChange !== Change.None) && resourcePreview.mergeState === MergeState.Preview) { await synchroniser.merge(resourcePreview.previewResource); } } /* apply */ const newPreview = await synchroniser.apply(false, this.syncHeaders); if (newPreview) { previews.push(this.toSyncResourcePreview(synchroniser.resource, newPreview)); } this.synchronizingResources.splice(this.synchronizingResources.findIndex(s => s[0] === syncResource), 1); this._onSynchronizeResources.fire(this.synchronizingResources); } this.previews = previews; return this.previews; } catch (error) { this.logService.error(error); throw error; } } async pull(): Promise<void> { try { if (!this.previews) { throw new Error('You need to create preview before applying'); } if (this.synchronizingResources.length) { throw new Error('Cannot pull while synchronizing resources'); } for (const [syncResource, preview] of this.previews) { this.synchronizingResources.push([syncResource, preview.resourcePreviews.map(r => r.localResource)]); this._onSynchronizeResources.fire(this.synchronizingResources); const synchroniser = this.synchronisers.find(s => s.resource === syncResource)!; for (const resourcePreview of preview.resourcePreviews) { await synchroniser.accept(resourcePreview.remoteResource); } await synchroniser.apply(true, this.syncHeaders); this.synchronizingResources.splice(this.synchronizingResources.findIndex(s => s[0] === syncResource), 1); this._onSynchronizeResources.fire(this.synchronizingResources); } this.previews = []; } catch (error) { this.logService.error(error); throw error; } } async push(): Promise<void> { try { if (!this.previews) { throw new Error('You need to create preview before applying'); } if (this.synchronizingResources.length) { throw new Error('Cannot pull while synchronizing resources'); } for (const [syncResource, preview] of this.previews) { this.synchronizingResources.push([syncResource, preview.resourcePreviews.map(r => r.localResource)]); this._onSynchronizeResources.fire(this.synchronizingResources); const synchroniser = this.synchronisers.find(s => s.resource === syncResource)!; for (const resourcePreview of preview.resourcePreviews) { await synchroniser.accept(resourcePreview.localResource); } await synchroniser.apply(true, this.syncHeaders); this.synchronizingResources.splice(this.synchronizingResources.findIndex(s => s[0] === syncResource), 1); this._onSynchronizeResources.fire(this.synchronizingResources); } this.previews = []; } catch (error) { this.logService.error(error); throw error; } } async stop(): Promise<void> { for (const synchroniser of this.synchronisers) { try { await synchroniser.stop(); } catch (error) { if (!isPromiseCanceledError(error)) { this.logService.error(error); } } } this.reset(); } private async performAction(resource: URI, action: (synchroniser: IUserDataSynchroniser) => Promise<ISyncResourcePreview | null>): Promise<[SyncResource, ISyncResourcePreview][]> { if (!this.previews) { throw new Error('Missing preview. Create preview and try again.'); } const index = this.previews.findIndex(([, preview]) => preview.resourcePreviews.some(({ localResource, previewResource, remoteResource }) => isEqual(resource, localResource) || isEqual(resource, previewResource) || isEqual(resource, remoteResource))); if (index === -1) { return this.previews; } const [syncResource, previews] = this.previews[index]; const resourcePreview = previews.resourcePreviews.find(({ localResource, remoteResource, previewResource }) => isEqual(localResource, resource) || isEqual(remoteResource, resource) || isEqual(previewResource, resource)); if (!resourcePreview) { return this.previews; } let synchronizingResources = this.synchronizingResources.find(s => s[0] === syncResource); if (!synchronizingResources) { synchronizingResources = [syncResource, []]; this.synchronizingResources.push(synchronizingResources); } if (!synchronizingResources[1].some(s => isEqual(s, resourcePreview.localResource))) { synchronizingResources[1].push(resourcePreview.localResource); this._onSynchronizeResources.fire(this.synchronizingResources); } const synchroniser = this.synchronisers.find(s => s.resource === this.previews![index][0])!; const preview = await action(synchroniser); preview ? this.previews.splice(index, 1, this.toSyncResourcePreview(synchroniser.resource, preview)) : this.previews.splice(index, 1); const i = this.synchronizingResources.findIndex(s => s[0] === syncResource); this.synchronizingResources[i][1].splice(synchronizingResources[1].findIndex(r => isEqual(r, resourcePreview.localResource)), 1); if (!synchronizingResources[1].length) { this.synchronizingResources.splice(i, 1); this._onSynchronizeResources.fire(this.synchronizingResources); } return this.previews; } private async mergeAll(): Promise<[SyncResource, ISyncResourcePreview][]> { if (!this.previews) { throw new Error('You need to create preview before merging or applying'); } if (this.synchronizingResources.length) { throw new Error('Cannot merge or apply while synchronizing resources'); } const previews: [SyncResource, ISyncResourcePreview][] = []; for (const [syncResource, preview] of this.previews) { this.synchronizingResources.push([syncResource, preview.resourcePreviews.map(r => r.localResource)]); this._onSynchronizeResources.fire(this.synchronizingResources); const synchroniser = this.synchronisers.find(s => s.resource === syncResource)!; /* merge those which are not yet merged */ let newPreview: ISyncResourcePreview | null = preview; for (const resourcePreview of preview.resourcePreviews) { if ((resourcePreview.localChange !== Change.None || resourcePreview.remoteChange !== Change.None) && resourcePreview.mergeState === MergeState.Preview) { newPreview = await synchroniser.merge(resourcePreview.previewResource); } } if (newPreview) { previews.push(this.toSyncResourcePreview(synchroniser.resource, newPreview)); } this.synchronizingResources.splice(this.synchronizingResources.findIndex(s => s[0] === syncResource), 1); this._onSynchronizeResources.fire(this.synchronizingResources); } this.previews = previews; return this.previews; } private async getPreviews(token: CancellationToken): Promise<[SyncResource, ISyncResourcePreview][]> { const result: [SyncResource, ISyncResourcePreview][] = []; for (const synchroniser of this.synchronisers) { if (token.isCancellationRequested) { return []; } const preview = await synchroniser.preview(this.manifest, this.syncHeaders); if (preview) { result.push(this.toSyncResourcePreview(synchroniser.resource, preview)); } } return result; } private toSyncResourcePreview(syncResource: SyncResource, preview: ISyncResourcePreview): [SyncResource, ISyncResourcePreview] { return [ syncResource, { isLastSyncFromCurrentMachine: preview.isLastSyncFromCurrentMachine, resourcePreviews: preview.resourcePreviews.map(toStrictResourcePreview) } ]; } private reset(): void { if (this.previewsPromise) { this.previewsPromise.cancel(); this.previewsPromise = undefined; } this.previews = undefined; this.synchronizingResources = []; } override dispose(): void { this.reset(); this.isDisposed = true; } } function toStrictResourcePreview(resourcePreview: IResourcePreview): IResourcePreview { return { localResource: resourcePreview.localResource, previewResource: resourcePreview.previewResource, remoteResource: resourcePreview.remoteResource, acceptedResource: resourcePreview.acceptedResource, localChange: resourcePreview.localChange, remoteChange: resourcePreview.remoteChange, mergeState: resourcePreview.mergeState, }; }
the_stack
import * as path from 'path'; import { DebugProtocol } from 'vscode-debugprotocol'; import { ISetBreakpointsArgs, ILaunchRequestArgs, IAttachRequestArgs, IInternalStackTraceResponseBody, IScopesResponseBody, IInternalStackFrame } from '../debugAdapterInterfaces'; import { MappedPosition, ISourcePathDetails } from '../sourceMaps/sourceMap'; import { SourceMaps } from '../sourceMaps/sourceMaps'; import * as utils from '../utils'; import { logger } from 'vscode-debugadapter'; import * as nls from 'vscode-nls'; import { ScriptContainer } from '../chrome/scripts'; import { isInternalRemotePath } from '../remoteMapper'; const localize = nls.loadMessageBundle(); interface ISavedSetBreakpointsArgs { generatedPath: string; authoredPath: string; originalBPs: DebugProtocol.Breakpoint[]; } export interface ISourceLocation { source: DebugProtocol.Source; line: number; column: number; isSourceMapped?: boolean; // compat with stack frame } /** * If sourcemaps are enabled, converts from source files on the client side to runtime files on the target side */ export class BaseSourceMapTransformer { protected _sourceMaps: SourceMaps; protected _scriptContainer: ScriptContainer; private _enableSourceMapCaching: boolean; private _requestSeqToSetBreakpointsArgs: Map<number, ISavedSetBreakpointsArgs>; private _allRuntimeScriptPaths: Set<string>; private _authoredPathsToMappedBPs: Map<string, DebugProtocol.SourceBreakpoint[]>; private _authoredPathsToClientBreakpointIds: Map<string, number[]>; protected _preLoad = Promise.resolve(); private _processingNewSourceMap: Promise<any> = Promise.resolve(); public caseSensitivePaths: boolean; protected _isVSClient = false; constructor(sourceHandles: ScriptContainer) { this._scriptContainer = sourceHandles; } public get sourceMaps(): SourceMaps { return this._sourceMaps; } public set isVSClient(newValue: boolean) { this._isVSClient = newValue; } public launch(args: ILaunchRequestArgs): void { this.init(args); } public attach(args: IAttachRequestArgs): void { this.init(args); } protected init(args: ILaunchRequestArgs | IAttachRequestArgs): void { if (args.sourceMaps) { this._enableSourceMapCaching = args.enableSourceMapCaching; this._sourceMaps = new SourceMaps(args.pathMapping, args.sourceMapPathOverrides, this._enableSourceMapCaching); this._requestSeqToSetBreakpointsArgs = new Map<number, ISavedSetBreakpointsArgs>(); this._allRuntimeScriptPaths = new Set<string>(); this._authoredPathsToMappedBPs = new Map<string, DebugProtocol.SourceBreakpoint[]>(); this._authoredPathsToClientBreakpointIds = new Map<string, number[]>(); } } public clearTargetContext(): void { this._allRuntimeScriptPaths = new Set<string>(); } /** * Apply sourcemapping to the setBreakpoints request path/lines. * Returns true if completed successfully, and setBreakpoint should continue. */ public setBreakpoints(args: ISetBreakpointsArgs, requestSeq: number, ids?: number[]): { args: ISetBreakpointsArgs, ids: number[] } { if (!this._sourceMaps) { return { args, ids }; } const originalBPs = JSON.parse(JSON.stringify(args.breakpoints)); if (args.source.sourceReference) { // If the source contents were inlined, then args.source has no path, but we // stored it in the handle const handle = this._scriptContainer.getSource(args.source.sourceReference); if (handle && handle.mappedPath) { args.source.path = handle.mappedPath; } } if (args.source.path) { const argsPath = args.source.path; const mappedPath = this._sourceMaps.getGeneratedPathFromAuthoredPath(argsPath); if (mappedPath) { logger.log(`SourceMaps.setBP: Mapped ${argsPath} to ${mappedPath}`); args.authoredPath = argsPath; args.source.path = mappedPath; // DebugProtocol doesn't send cols yet, but they need to be added from sourcemaps args.breakpoints.forEach(bp => { const { line, column = 0 } = bp; const mapped = this._sourceMaps.mapToGenerated(argsPath, line, column); if (mapped) { logger.log(`SourceMaps.setBP: Mapped ${argsPath}:${line + 1}:${column + 1} to ${mappedPath}:${mapped.line + 1}:${mapped.column + 1}`); bp.line = mapped.line; bp.column = mapped.column; } else { logger.log(`SourceMaps.setBP: Mapped ${argsPath} but not line ${line + 1}, column 1`); bp.column = column; // take 0 default if needed } }); this._authoredPathsToMappedBPs.set(argsPath, args.breakpoints); // Store the client breakpoint Ids for the mapped BPs as well if (ids) { this._authoredPathsToClientBreakpointIds.set(argsPath, ids); } // Include BPs from other files that map to the same file. Ensure the current file's breakpoints go first this._sourceMaps.allMappedSources(mappedPath).forEach(sourcePath => { if (sourcePath === argsPath) { return; } const sourceBPs = this._authoredPathsToMappedBPs.get(sourcePath); if (sourceBPs) { // Don't modify the cached array args.breakpoints = args.breakpoints.concat(sourceBPs); // We need to assign the client IDs we generated for the mapped breakpoints becuase the runtime IDs may change // So make sure we concat the client ids to the ids array so that they get mapped to the respective breakpoints later const clientBreakpointIds = this._authoredPathsToClientBreakpointIds.get(sourcePath); if (ids) { ids = ids.concat(clientBreakpointIds); } } }); } else if (this.isRuntimeScript(argsPath)) { // It's a generated file which is loaded logger.log(`SourceMaps.setBP: SourceMaps are enabled but ${argsPath} is a runtime script`); } else { // Source (or generated) file which is not loaded. logger.log(`SourceMaps.setBP: ${argsPath} can't be resolved to a loaded script. It may just not be loaded yet.`); } } else { // No source.path } this._requestSeqToSetBreakpointsArgs.set(requestSeq, { originalBPs, authoredPath: args.authoredPath, generatedPath: args.source.path }); return { args, ids }; } /** * Apply sourcemapping back to authored files from the response */ public setBreakpointsResponse(breakpoints: DebugProtocol.Breakpoint[], shouldFilter: boolean, requestSeq: number): DebugProtocol.Breakpoint[] { if (this._sourceMaps && this._requestSeqToSetBreakpointsArgs.has(requestSeq)) { const args = this._requestSeqToSetBreakpointsArgs.get(requestSeq); if (args.authoredPath) { // authoredPath is set, so the file was mapped to source. // Remove breakpoints from files that map to the same file, and map back to source. if (shouldFilter) { breakpoints = breakpoints.filter((_, i) => i < args.originalBPs.length); } breakpoints.forEach((bp, i) => { const mapped = this._sourceMaps.mapToAuthored(args.generatedPath, bp.line, bp.column); if (mapped) { logger.log(`SourceMaps.setBP: Mapped ${args.generatedPath}:${bp.line + 1}:${bp.column + 1} to ${mapped.source}:${mapped.line + 1}`); bp.line = mapped.line; bp.column = mapped.column; } else { logger.log(`SourceMaps.setBP: Can't map ${args.generatedPath}:${bp.line + 1}:${bp.column + 1}, keeping original line numbers.`); if (args.originalBPs[i]) { bp.line = args.originalBPs[i].line; bp.column = args.originalBPs[i].column; } } this._requestSeqToSetBreakpointsArgs.delete(requestSeq); }); } } return breakpoints; } /** * Apply sourcemapping to the stacktrace response */ public async stackTraceResponse(response: IInternalStackTraceResponseBody): Promise<void> { if (this._sourceMaps) { await this._processingNewSourceMap; for (let stackFrame of response.stackFrames) { await this.fixSourceLocation(stackFrame); } } } public async fixSourceLocation(sourceLocation: ISourceLocation|IInternalStackFrame): Promise<void> { if (!this._sourceMaps) { return; } if (!sourceLocation.source) { return; } await this._processingNewSourceMap; const mapped = this._sourceMaps.mapToAuthored(sourceLocation.source.path, sourceLocation.line, sourceLocation.column); if (mapped && (isInternalRemotePath(mapped.source) || utils.existsSync(mapped.source))) { // Script was mapped to a valid local path or internal path sourceLocation.source.path = mapped.source; sourceLocation.source.sourceReference = undefined; sourceLocation.source.name = path.basename(mapped.source); sourceLocation.line = mapped.line; sourceLocation.column = mapped.column; sourceLocation.isSourceMapped = true; return; } const inlinedSource = mapped && this._sourceMaps.sourceContentFor(mapped.source); if (mapped && inlinedSource) { // Clear the path and set the sourceReference - the client will ask for // the source later and it will be returned from the sourcemap sourceLocation.source.name = path.basename(mapped.source); sourceLocation.source.path = mapped.source; sourceLocation.source.sourceReference = this._scriptContainer.getSourceReferenceForScriptPath(mapped.source, inlinedSource); sourceLocation.source.origin = localize('origin.inlined.source.map', 'read-only inlined content from source map'); sourceLocation.line = mapped.line; sourceLocation.column = mapped.column; sourceLocation.isSourceMapped = true; return; } if (utils.existsSync(sourceLocation.source.path)) { // Script could not be mapped, but does exist on disk. Keep it and clear the sourceReference. sourceLocation.source.sourceReference = undefined; sourceLocation.source.origin = undefined; return; } } public async scriptParsed(pathToGenerated: string, originalUrlToGenerated: string | undefined, sourceMapURL: string): Promise<string[]> { if (this._sourceMaps) { this._allRuntimeScriptPaths.add(this.fixPathCasing(pathToGenerated)); if (!sourceMapURL) return null; // Load the sourcemap for this new script and log its sources const processNewSourceMapP = this._sourceMaps.processNewSourceMap(pathToGenerated, originalUrlToGenerated, sourceMapURL, this._isVSClient); this._processingNewSourceMap = Promise.all([this._processingNewSourceMap, processNewSourceMapP]); await processNewSourceMapP; const sources = this._sourceMaps.allMappedSources(pathToGenerated); if (sources) { logger.log(`SourceMaps.scriptParsed: ${pathToGenerated} was just loaded and has mapped sources: ${JSON.stringify(sources) }`); } return sources; } else { return null; } } public breakpointResolved(bp: DebugProtocol.Breakpoint, scriptPath: string): void { if (this._sourceMaps) { const mapped = this._sourceMaps.mapToAuthored(scriptPath, bp.line, bp.column); if (mapped) { // No need to send back the path, the bp can only move within its script bp.line = mapped.line; bp.column = mapped.column; } } } public scopesResponse(pathToGenerated: string, scopesResponse: IScopesResponseBody): void { if (this._sourceMaps) { scopesResponse.scopes.forEach(scope => this.mapScopeLocations(pathToGenerated, scope)); } } private mapScopeLocations(pathToGenerated: string, scope: DebugProtocol.Scope): void { // The runtime can return invalid scope locations. Just skip those scopes. https://github.com/Microsoft/vscode-chrome-debug-core/issues/333 if (typeof scope.line !== 'number' || scope.line < 0 || scope.endLine < 0 || scope.column < 0 || scope.endColumn < 0) { return; } let mappedStart = this._sourceMaps.mapToAuthored(pathToGenerated, scope.line, scope.column); let shiftedScopeStartForward = false; // If the scope is an async function, then the function declaration line may be missing a source mapping. // So if we failed, try to get the next line. if (!mappedStart) { mappedStart = this._sourceMaps.mapToAuthored(pathToGenerated, scope.line + 1, scope.column); shiftedScopeStartForward = true; } if (mappedStart) { // Only apply changes if both mappings are found const mappedEnd = this._sourceMaps.mapToAuthored(pathToGenerated, scope.endLine, scope.endColumn); if (mappedEnd) { scope.line = mappedStart.line; if (shiftedScopeStartForward) { scope.line--; } scope.column = mappedStart.column; scope.endLine = mappedEnd.line; scope.endColumn = mappedEnd.column; } } } public async mapToGenerated(authoredPath: string, line: number, column: number): Promise<MappedPosition> { if (!this._sourceMaps) return null; await this.wait(); return this._sourceMaps.mapToGenerated(authoredPath, line, column); } public async mapToAuthored(pathToGenerated: string, line: number, column: number): Promise<MappedPosition> { if (!this._sourceMaps) return null; await this.wait(); return this._sourceMaps.mapToAuthored(pathToGenerated, line, column); } public async getGeneratedPathFromAuthoredPath(authoredPath: string): Promise<string> { if (!this._sourceMaps) return authoredPath; await this.wait(); // Find the generated path, or check whether this script is actually a runtime path - if so, return that return this._sourceMaps.getGeneratedPathFromAuthoredPath(authoredPath) || (this.isRuntimeScript(authoredPath) ? authoredPath : null); } public async allSources(pathToGenerated: string): Promise<string[]> { if (!this._sourceMaps) return []; await this.wait(); return this._sourceMaps.allMappedSources(pathToGenerated) || []; } public async allSourcePathDetails(pathToGenerated: string): Promise<ISourcePathDetails[]> { if (!this._sourceMaps) return []; await this.wait(); return this._sourceMaps.allSourcePathDetails(pathToGenerated) || []; } private wait(): Promise<any> { return Promise.all([this._preLoad, this._processingNewSourceMap]); } private isRuntimeScript(scriptPath: string): boolean { return this._allRuntimeScriptPaths.has(this.fixPathCasing(scriptPath)); } private fixPathCasing(str: string): string { return str && (this.caseSensitivePaths ? str : str.toLowerCase()); } }
the_stack
import * as nls from 'vs/nls'; import * as Objects from 'vs/base/common/objects'; import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema'; import commonSchema from './jsonSchemaCommon'; import { ProblemMatcherRegistry } from 'vs/workbench/contrib/tasks/common/problemMatcher'; import { TaskDefinitionRegistry } from './taskDefinitionRegistry'; import * as ConfigurationResolverUtils from 'vs/workbench/services/configurationResolver/common/configurationResolverUtils'; import { inputsSchema } from 'vs/workbench/services/configurationResolver/common/configurationResolverSchema'; function fixReferences(literal: any) { if (Array.isArray(literal)) { literal.forEach(fixReferences); } else if (typeof literal === 'object') { if (literal['$ref']) { literal['$ref'] = literal['$ref'] + '2'; } Object.getOwnPropertyNames(literal).forEach(property => { let value = literal[property]; if (Array.isArray(value) || typeof value === 'object') { fixReferences(value); } }); } } const shellCommand: IJSONSchema = { anyOf: [ { type: 'boolean', default: true, description: nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.') }, { $ref: '#definitions/shellConfiguration' } ], deprecationMessage: nls.localize('JsonSchema.tasks.isShellCommand.deprecated', 'The property isShellCommand is deprecated. Use the type property of the task and the shell property in the options instead. See also the 1.14 release notes.') }; const taskIdentifier: IJSONSchema = { type: 'object', additionalProperties: true, properties: { type: { type: 'string', description: nls.localize('JsonSchema.tasks.dependsOn.identifier', 'The task identifier.') } } }; const dependsOn: IJSONSchema = { anyOf: [ { type: 'string', description: nls.localize('JsonSchema.tasks.dependsOn.string', 'Another task this task depends on.') }, taskIdentifier, { type: 'array', description: nls.localize('JsonSchema.tasks.dependsOn.array', 'The other tasks this task depends on.'), items: { anyOf: [ { type: 'string', }, taskIdentifier ] } } ], description: nls.localize('JsonSchema.tasks.dependsOn', 'Either a string representing another task or an array of other tasks that this task depends on.') }; const dependsOrder: IJSONSchema = { type: 'string', enum: ['parallel', 'sequence'], enumDescriptions: [ nls.localize('JsonSchema.tasks.dependsOrder.parallel', 'Run all dependsOn tasks in parallel.'), nls.localize('JsonSchema.tasks.dependsOrder.sequence', 'Run all dependsOn tasks in sequence.'), ], default: 'parallel', description: nls.localize('JsonSchema.tasks.dependsOrder', 'Determines the order of the dependsOn tasks for this task. Note that this property is not recursive.') }; const detail: IJSONSchema = { type: 'string', description: nls.localize('JsonSchema.tasks.detail', 'An optional description of a task that shows in the Run Task quick pick as a detail.') }; const presentation: IJSONSchema = { type: 'object', default: { echo: true, reveal: 'always', focus: false, panel: 'shared', showReuseMessage: true, clear: false, }, description: nls.localize('JsonSchema.tasks.presentation', 'Configures the panel that is used to present the task\'s output and reads its input.'), additionalProperties: false, properties: { echo: { type: 'boolean', default: true, description: nls.localize('JsonSchema.tasks.presentation.echo', 'Controls whether the executed command is echoed to the panel. Default is true.') }, focus: { type: 'boolean', default: false, description: nls.localize('JsonSchema.tasks.presentation.focus', 'Controls whether the panel takes focus. Default is false. If set to true the panel is revealed as well.') }, revealProblems: { type: 'string', enum: ['always', 'onProblem', 'never'], enumDescriptions: [ nls.localize('JsonSchema.tasks.presentation.revealProblems.always', 'Always reveals the problems panel when this task is executed.'), nls.localize('JsonSchema.tasks.presentation.revealProblems.onProblem', 'Only reveals the problems panel if a problem is found.'), nls.localize('JsonSchema.tasks.presentation.revealProblems.never', 'Never reveals the problems panel when this task is executed.'), ], default: 'never', description: nls.localize('JsonSchema.tasks.presentation.revealProblems', 'Controls whether the problems panel is revealed when running this task or not. Takes precedence over option \"reveal\". Default is \"never\".') }, reveal: { type: 'string', enum: ['always', 'silent', 'never'], enumDescriptions: [ nls.localize('JsonSchema.tasks.presentation.reveal.always', 'Always reveals the terminal when this task is executed.'), nls.localize('JsonSchema.tasks.presentation.reveal.silent', 'Only reveals the terminal if the task exits with an error or the problem matcher finds an error.'), nls.localize('JsonSchema.tasks.presentation.reveal.never', 'Never reveals the terminal when this task is executed.'), ], default: 'always', description: nls.localize('JsonSchema.tasks.presentation.reveal', 'Controls whether the terminal running the task is revealed or not. May be overridden by option \"revealProblems\". Default is \"always\".') }, panel: { type: 'string', enum: ['shared', 'dedicated', 'new'], default: 'shared', description: nls.localize('JsonSchema.tasks.presentation.instance', 'Controls if the panel is shared between tasks, dedicated to this task or a new one is created on every run.') }, showReuseMessage: { type: 'boolean', default: true, description: nls.localize('JsonSchema.tasks.presentation.showReuseMessage', 'Controls whether to show the `Terminal will be reused by tasks, press any key to close it` message.') }, clear: { type: 'boolean', default: false, description: nls.localize('JsonSchema.tasks.presentation.clear', 'Controls whether the terminal is cleared before executing the task.') }, group: { type: 'string', description: nls.localize('JsonSchema.tasks.presentation.group', 'Controls whether the task is executed in a specific terminal group using split panes.') }, close: { type: 'boolean', description: nls.localize('JsonSchema.tasks.presentation.close', 'Controls whether the terminal the task runs in is closed when the task exits.') } } }; const terminal: IJSONSchema = Objects.deepClone(presentation); terminal.deprecationMessage = nls.localize('JsonSchema.tasks.terminal', 'The terminal property is deprecated. Use presentation instead'); const group: IJSONSchema = { oneOf: [ { type: 'string', }, { type: 'object', properties: { kind: { type: 'string', default: 'none', description: nls.localize('JsonSchema.tasks.group.kind', 'The task\'s execution group.') }, isDefault: { type: 'boolean', default: false, description: nls.localize('JsonSchema.tasks.group.isDefault', 'Defines if this task is the default task in the group.') } } }, ], enum: [ { kind: 'build', isDefault: true }, { kind: 'test', isDefault: true }, 'build', 'test', 'none' ], enumDescriptions: [ nls.localize('JsonSchema.tasks.group.defaultBuild', 'Marks the task as the default build task.'), nls.localize('JsonSchema.tasks.group.defaultTest', 'Marks the task as the default test task.'), nls.localize('JsonSchema.tasks.group.build', 'Marks the task as a build task accessible through the \'Run Build Task\' command.'), nls.localize('JsonSchema.tasks.group.test', 'Marks the task as a test task accessible through the \'Run Test Task\' command.'), nls.localize('JsonSchema.tasks.group.none', 'Assigns the task to no group') ], description: nls.localize('JsonSchema.tasks.group', 'Defines to which execution group this task belongs to. It supports "build" to add it to the build group and "test" to add it to the test group.') }; const taskType: IJSONSchema = { type: 'string', enum: ['shell'], default: 'process', description: nls.localize('JsonSchema.tasks.type', 'Defines whether the task is run as a process or as a command inside a shell.') }; const command: IJSONSchema = { oneOf: [ { oneOf: [ { type: 'string' }, { type: 'array', items: { type: 'string' }, description: nls.localize('JsonSchema.commandArray', 'The shell command to be executed. Array items will be joined using a space character') } ] }, { type: 'object', required: ['value', 'quoting'], properties: { value: { oneOf: [ { type: 'string' }, { type: 'array', items: { type: 'string' }, description: nls.localize('JsonSchema.commandArray', 'The shell command to be executed. Array items will be joined using a space character') } ], description: nls.localize('JsonSchema.command.quotedString.value', 'The actual command value') }, quoting: { type: 'string', enum: ['escape', 'strong', 'weak'], enumDescriptions: [ nls.localize('JsonSchema.tasks.quoting.escape', 'Escapes characters using the shell\'s escape character (e.g. ` under PowerShell and \\ under bash).'), nls.localize('JsonSchema.tasks.quoting.strong', 'Quotes the argument using the shell\'s strong quote character (e.g. \' under PowerShell and bash).'), nls.localize('JsonSchema.tasks.quoting.weak', 'Quotes the argument using the shell\'s weak quote character (e.g. " under PowerShell and bash).'), ], default: 'strong', description: nls.localize('JsonSchema.command.quotesString.quote', 'How the command value should be quoted.') } } } ], description: nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.') }; const args: IJSONSchema = { type: 'array', items: { oneOf: [ { type: 'string', }, { type: 'object', required: ['value', 'quoting'], properties: { value: { type: 'string', description: nls.localize('JsonSchema.args.quotedString.value', 'The actual argument value') }, quoting: { type: 'string', enum: ['escape', 'strong', 'weak'], enumDescriptions: [ nls.localize('JsonSchema.tasks.quoting.escape', 'Escapes characters using the shell\'s escape character (e.g. ` under PowerShell and \\ under bash).'), nls.localize('JsonSchema.tasks.quoting.strong', 'Quotes the argument using the shell\'s strong quote character (e.g. \' under PowerShell and bash).'), nls.localize('JsonSchema.tasks.quoting.weak', 'Quotes the argument using the shell\'s weak quote character (e.g. " under PowerShell and bash).'), ], default: 'strong', description: nls.localize('JsonSchema.args.quotesString.quote', 'How the argument value should be quoted.') } } } ] }, description: nls.localize('JsonSchema.tasks.args', 'Arguments passed to the command when this task is invoked.') }; const label: IJSONSchema = { type: 'string', description: nls.localize('JsonSchema.tasks.label', "The task's user interface label") }; const version: IJSONSchema = { type: 'string', enum: ['2.0.0'], description: nls.localize('JsonSchema.version', 'The config\'s version number.') }; const identifier: IJSONSchema = { type: 'string', description: nls.localize('JsonSchema.tasks.identifier', 'A user defined identifier to reference the task in launch.json or a dependsOn clause.'), deprecationMessage: nls.localize('JsonSchema.tasks.identifier.deprecated', 'User defined identifiers are deprecated. For custom task use the name as a reference and for tasks provided by extensions use their defined task identifier.') }; const runOptions: IJSONSchema = { type: 'object', additionalProperties: false, properties: { reevaluateOnRerun: { type: 'boolean', description: nls.localize('JsonSchema.tasks.reevaluateOnRerun', 'Whether to reevaluate task variables on rerun.'), default: true }, runOn: { type: 'string', enum: ['default', 'folderOpen'], description: nls.localize('JsonSchema.tasks.runOn', 'Configures when the task should be run. If set to folderOpen, then the task will be run automatically when the folder is opened.'), default: 'default' }, instanceLimit: { type: 'number', description: nls.localize('JsonSchema.tasks.instanceLimit', 'The number of instances of the task that are allowed to run simultaneously.'), default: 1 }, }, description: nls.localize('JsonSchema.tasks.runOptions', 'The task\'s run related options') }; const commonSchemaDefinitions = commonSchema.definitions!; const options: IJSONSchema = Objects.deepClone(commonSchemaDefinitions.options); const optionsProperties = options.properties!; optionsProperties.shell = Objects.deepClone(commonSchemaDefinitions.shellConfiguration); let taskConfiguration: IJSONSchema = { type: 'object', additionalProperties: false, properties: { label: { type: 'string', description: nls.localize('JsonSchema.tasks.taskLabel', "The task's label") }, taskName: { type: 'string', description: nls.localize('JsonSchema.tasks.taskName', 'The task\'s name'), deprecationMessage: nls.localize('JsonSchema.tasks.taskName.deprecated', 'The task\'s name property is deprecated. Use the label property instead.') }, identifier: Objects.deepClone(identifier), group: Objects.deepClone(group), isBackground: { type: 'boolean', description: nls.localize('JsonSchema.tasks.background', 'Whether the executed task is kept alive and is running in the background.'), default: true }, promptOnClose: { type: 'boolean', description: nls.localize('JsonSchema.tasks.promptOnClose', 'Whether the user is prompted when VS Code closes with a running task.'), default: false }, presentation: Objects.deepClone(presentation), options: options, problemMatcher: { $ref: '#/definitions/problemMatcherType', description: nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.') }, runOptions: Objects.deepClone(runOptions), dependsOn: Objects.deepClone(dependsOn), dependsOrder: Objects.deepClone(dependsOrder), detail: Objects.deepClone(detail), } }; let taskDefinitions: IJSONSchema[] = []; TaskDefinitionRegistry.onReady().then(() => { updateTaskDefinitions(); }); export function updateTaskDefinitions() { for (let taskType of TaskDefinitionRegistry.all()) { // Check that we haven't already added this task type if (taskDefinitions.find(schema => { return schema.properties?.type?.enum?.find ? schema.properties?.type.enum.find(element => element === taskType.taskType) : undefined; })) { continue; } let schema: IJSONSchema = Objects.deepClone(taskConfiguration); const schemaProperties = schema.properties!; // Since we do this after the schema is assigned we need to patch the refs. schemaProperties.type = { type: 'string', description: nls.localize('JsonSchema.customizations.customizes.type', 'The task type to customize'), enum: [taskType.taskType] }; if (taskType.required) { schema.required = taskType.required.slice(); } else { schema.required = []; } // Customized tasks require that the task type be set. schema.required.push('type'); if (taskType.properties) { for (let key of Object.keys(taskType.properties)) { let property = taskType.properties[key]; schemaProperties[key] = Objects.deepClone(property); } } fixReferences(schema); taskDefinitions.push(schema); } } let customize = Objects.deepClone(taskConfiguration); customize.properties!.customize = { type: 'string', deprecationMessage: nls.localize('JsonSchema.tasks.customize.deprecated', 'The customize property is deprecated. See the 1.14 release notes on how to migrate to the new task customization approach') }; if (!customize.required) { customize.required = []; } customize.required.push('customize'); taskDefinitions.push(customize); let definitions = Objects.deepClone(commonSchemaDefinitions); let taskDescription: IJSONSchema = definitions.taskDescription; taskDescription.required = ['label']; const taskDescriptionProperties = taskDescription.properties!; taskDescriptionProperties.label = Objects.deepClone(label); taskDescriptionProperties.command = Objects.deepClone(command); taskDescriptionProperties.args = Objects.deepClone(args); taskDescriptionProperties.isShellCommand = Objects.deepClone(shellCommand); taskDescriptionProperties.dependsOn = dependsOn; taskDescriptionProperties.dependsOrder = dependsOrder; taskDescriptionProperties.identifier = Objects.deepClone(identifier); taskDescriptionProperties.type = Objects.deepClone(taskType); taskDescriptionProperties.presentation = Objects.deepClone(presentation); taskDescriptionProperties.terminal = terminal; taskDescriptionProperties.group = Objects.deepClone(group); taskDescriptionProperties.runOptions = Objects.deepClone(runOptions); taskDescriptionProperties.detail = detail; taskDescriptionProperties.taskName.deprecationMessage = nls.localize( 'JsonSchema.tasks.taskName.deprecated', 'The task\'s name property is deprecated. Use the label property instead.' ); // Clone the taskDescription for process task before setting a default to prevent two defaults #115281 const processTask = Objects.deepClone(taskDescription); taskDescription.default = { label: 'My Task', type: 'shell', command: 'echo Hello', problemMatcher: [] }; definitions.showOutputType.deprecationMessage = nls.localize( 'JsonSchema.tasks.showOutput.deprecated', 'The property showOutput is deprecated. Use the reveal property inside the presentation property instead. See also the 1.14 release notes.' ); taskDescriptionProperties.echoCommand.deprecationMessage = nls.localize( 'JsonSchema.tasks.echoCommand.deprecated', 'The property echoCommand is deprecated. Use the echo property inside the presentation property instead. See also the 1.14 release notes.' ); taskDescriptionProperties.suppressTaskName.deprecationMessage = nls.localize( 'JsonSchema.tasks.suppressTaskName.deprecated', 'The property suppressTaskName is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.' ); taskDescriptionProperties.isBuildCommand.deprecationMessage = nls.localize( 'JsonSchema.tasks.isBuildCommand.deprecated', 'The property isBuildCommand is deprecated. Use the group property instead. See also the 1.14 release notes.' ); taskDescriptionProperties.isTestCommand.deprecationMessage = nls.localize( 'JsonSchema.tasks.isTestCommand.deprecated', 'The property isTestCommand is deprecated. Use the group property instead. See also the 1.14 release notes.' ); // Process tasks are almost identical schema-wise to shell tasks, but they are required to have a command processTask.properties!.type = { type: 'string', enum: ['process'], default: 'process', description: nls.localize('JsonSchema.tasks.type', 'Defines whether the task is run as a process or as a command inside a shell.') }; processTask.required!.push('command'); processTask.required!.push('type'); taskDefinitions.push(processTask); taskDefinitions.push({ $ref: '#/definitions/taskDescription' } as IJSONSchema); const definitionsTaskRunnerConfigurationProperties = definitions.taskRunnerConfiguration.properties!; let tasks = definitionsTaskRunnerConfigurationProperties.tasks; tasks.items = { oneOf: taskDefinitions }; definitionsTaskRunnerConfigurationProperties.inputs = inputsSchema.definitions!.inputs; definitions.commandConfiguration.properties!.isShellCommand = Objects.deepClone(shellCommand); definitions.commandConfiguration.properties!.args = Objects.deepClone(args); definitions.options.properties!.shell = { $ref: '#/definitions/shellConfiguration' }; definitionsTaskRunnerConfigurationProperties.isShellCommand = Objects.deepClone(shellCommand); definitionsTaskRunnerConfigurationProperties.type = Objects.deepClone(taskType); definitionsTaskRunnerConfigurationProperties.group = Objects.deepClone(group); definitionsTaskRunnerConfigurationProperties.presentation = Objects.deepClone(presentation); definitionsTaskRunnerConfigurationProperties.suppressTaskName.deprecationMessage = nls.localize( 'JsonSchema.tasks.suppressTaskName.deprecated', 'The property suppressTaskName is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.' ); definitionsTaskRunnerConfigurationProperties.taskSelector.deprecationMessage = nls.localize( 'JsonSchema.tasks.taskSelector.deprecated', 'The property taskSelector is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.' ); let osSpecificTaskRunnerConfiguration = Objects.deepClone(definitions.taskRunnerConfiguration); delete osSpecificTaskRunnerConfiguration.properties!.tasks; osSpecificTaskRunnerConfiguration.additionalProperties = false; definitions.osSpecificTaskRunnerConfiguration = osSpecificTaskRunnerConfiguration; definitionsTaskRunnerConfigurationProperties.version = Objects.deepClone(version); const schema: IJSONSchema = { oneOf: [ { 'allOf': [ { type: 'object', required: ['version'], properties: { version: Objects.deepClone(version), windows: { '$ref': '#/definitions/osSpecificTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.windows', 'Windows specific command configuration') }, osx: { '$ref': '#/definitions/osSpecificTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.mac', 'Mac specific command configuration') }, linux: { '$ref': '#/definitions/osSpecificTaskRunnerConfiguration', 'description': nls.localize('JsonSchema.linux', 'Linux specific command configuration') } } }, { $ref: '#/definitions/taskRunnerConfiguration' } ] } ] }; schema.definitions = definitions; function deprecatedVariableMessage(schemaMap: IJSONSchemaMap, property: string) { const mapAtProperty = schemaMap[property].properties!; if (mapAtProperty) { Object.keys(mapAtProperty).forEach(name => { deprecatedVariableMessage(mapAtProperty, name); }); } else { ConfigurationResolverUtils.applyDeprecatedVariableMessage(schemaMap[property]); } } Object.getOwnPropertyNames(definitions).forEach(key => { let newKey = key + '2'; definitions[newKey] = definitions[key]; delete definitions[key]; deprecatedVariableMessage(definitions, newKey); }); fixReferences(schema); export function updateProblemMatchers() { try { let matcherIds = ProblemMatcherRegistry.keys().map(key => '$' + key); definitions.problemMatcherType2.oneOf![0].enum = matcherIds; (definitions.problemMatcherType2.oneOf![2].items as IJSONSchema).anyOf![0].enum = matcherIds; } catch (err) { console.log('Installing problem matcher ids failed'); } } ProblemMatcherRegistry.onReady().then(() => { updateProblemMatchers(); }); export default schema;
the_stack
import type { OverrideBundleDefinition } from '@polkadot/types/types'; // structs need to be in order /* eslint-disable sort-keys */ const definitions: OverrideBundleDefinition = { types: [ { // on all versions minmax: [0, undefined], types: { AccountInfo: 'AccountInfoWithDualRefCount', Date: 'i64', Keys: 'SessionKeys2', Address: 'MultiAddress', LookupSource: 'MultiAddress', RoamingOperator: '[u8; 16]', RoamingOperatorIndex: 'u64', RoamingNetwork: '[u8; 16]', RoamingNetworkIndex: 'u64', RoamingOrganization: '[u8; 16]', RoamingOrganizationIndex: 'u64', RoamingNetworkServer: '[u8; 16]', RoamingNetworkServerIndex: 'u64', RoamingDevice: '[u8; 16]', RoamingDeviceIndex: 'u64', RoamingRoutingProfile: '[u8; 16]', RoamingRoutingProfileIndex: 'u64', RoamingRoutingProfileAppServer: 'Text', RoamingServiceProfile: '[u8; 16]', RoamingServiceProfileIndex: 'u64', RoamingServiceProfileUplinkRate: 'u32', RoamingServiceProfileDownlinkRate: 'u32', RoamingAccountingPolicy: '[u8; 16]', RoamingAccountingPolicyIndex: 'u64', RoamingAccountingPolicyType: 'Text', RoamingAccountingPolicyUplinkFeeFactor: 'u32', RoamingAccountingPolicyDownlinkFeeFactor: 'u32', RoamingAccountingPolicySetting: { policy_type: 'Text', subscription_fee: 'Balance', uplink_fee_factor: 'u32', downlink_fee_factor: 'u32' }, RoamingAgreementPolicy: '[u8; 16]', RoamingAgreementPolicyIndex: 'u64', RoamingAgreementPolicyActivationType: 'Text', RoamingAgreementPolicySetting: { policy_activation_type: 'Text', policy_expiry_block: 'Moment' }, RoamingNetworkProfile: '[u8; 16]', RoamingNetworkProfileIndex: 'u64', RoamingDeviceProfile: '[u8; 16]', RoamingDeviceProfileIndex: 'u64', RoamingDeviceProfileDevAddr: 'Text', RoamingDeviceProfileDevEUI: 'Text', RoamingDeviceProfileJoinEUI: 'Text', RoamingDeviceProfileVendorID: 'Text', RoamingDeviceProfileSetting: { device_profile_devaddr: 'Text', device_profile_deveui: 'Text', device_profile_joineui: 'Text', device_profile_vendorid: 'Text' }, RoamingSession: '[u8; 16]', RoamingSessionIndex: 'u64', RoamingSessionJoinRequest: { session_network_server_id: 'Moment', session_join_requested_at_block: 'Moment' }, RoamingSessionJoinAccept: { session_join_request_accept_expiry: 'Moment', session_join_request_accept_accepted_at_block: 'Moment' }, RoamingBillingPolicy: '[u8; 16]', RoamingBillingPolicyIndex: 'u64', RoamingBillingPolicySetting: { policy_next_billing_at_block: 'Moment', policy_frequency_in_blocks: 'Moment' }, RoamingChargingPolicy: '[u8; 16]', RoamingChargingPolicyIndex: 'u64', RoamingChargingPolicySetting: { policy_next_charging_at_block: 'Moment', policy_delay_after_billing_in_blocks: 'u64' }, RoamingPacketBundle: '[u8; 16]', RoamingPacketBundleIndex: 'u64', RoamingPacketBundleReceivedAtHome: 'bool', RoamingPacketBundleReceivedPacketsCount: 'u64', RoamingPacketBundleReceivedPacketsOkCount: 'u64', RoamingPacketBundleExternalDataStorageHash: 'Hash', RoamingPacketBundleReceiver: { packet_bundle_received_at_home: 'bool', packet_bundle_received_packets_count: 'u64', packet_bundle_received_packets_ok_count: 'u64', packet_bundle_received_started_at_block: 'Moment', packet_bundle_received_ended_at_block: 'Moment', packet_bundle_external_data_storage_hash: 'Hash' }, MiningRatesToken: '[u8; 16]', MiningRatesTokenIndex: 'u64', MiningRatesTokenTokenDOT: 'u32', MiningRatesTokenTokenMXC: 'u32', MiningRatesTokenTokenIOTA: 'u32', MiningRatesTokenMaxToken: 'u32', MiningRatesTokenMaxLoyalty: 'u32', MiningRatesTokenSetting: { token_token_mxc: 'u32', token_token_iota: 'u32', token_token_dot: 'u32', token_max_token: 'u32', token_max_loyalty: 'u32' }, MiningRatesHardware: '[u8; 16]', MiningRatesHardwareIndex: 'u64', MiningRatesHardwareSecure: 'u32', MiningRatesHardwareInsecure: 'u32', MiningRatesHardwareMaxHardware: 'u32', MiningRatesHardwareCategory1MaxTokenBonusPerGateway: 'u32', MiningRatesHardwareCategory2MaxTokenBonusPerGateway: 'u32', MiningRatesHardwareCategory3MaxTokenBonusPerGateway: 'u32', MiningRatesHardwareSetting: { hardware_hardware_secure: 'u32', hardware_hardware_insecure: 'u32', hardware_max_hardware: 'u32', hardware_category_1_max_token_bonus_per_gateway: 'u32', hardware_category_2_max_token_bonus_per_gateway: 'u32', hardware_category_3_max_token_bonus_per_gateway: 'u32' }, MiningSettingToken: '[u8; 16]', MiningSettingTokenIndex: 'u64', MiningSettingTokenType: 'Text', MiningSettingTokenLockAmount: 'u64', MiningSettingTokenSetting: { token_type: 'Text', token_lock_amount: 'u64', token_lock_start_block: 'Moment', token_lock_interval_blocks: 'Moment' }, MiningSettingTokenRequirementsSetting: { token_type: 'Text', token_lock_min_amount: 'u64', token_lock_min_blocks: 'u32' }, MiningSettingHardware: '[u8; 16]', MiningSettingHardwareIndex: 'u64', MiningSettingHardwareSecure: 'bool', MiningSettingHardwareType: 'Text', MiningSettingHardwareID: 'u64', MiningSettingHardwareDevEUI: 'u64', MiningSettingHardwareSetting: { hardware_secure: 'bool', hardware_type: 'Text', hardware_id: 'u64', hardware_dev_eui: 'u64', hardware_lock_start_block: 'Moment', hardware_lock_interval_blocks: 'Moment' }, MiningSamplingToken: '[u8; 16]', MiningSamplingTokenIndex: 'u64', MiningSamplingTokenSampleLockedAmount: 'u64', MiningSamplingTokenSetting: { token_sample_block: 'Moment', token_sample_locked_amount: 'u64' }, MiningSamplingHardware: '[u8; 16]', MiningSamplingHardwareIndex: 'u64', MiningSamplingHardwareSampleHardwareOnline: 'u64', MiningSamplingHardwareSetting: { hardware_sample_block: 'Moment', hardware_sample_hardware_online: 'bool' }, MiningEligibilityToken: '[u8; 16]', MiningEligibilityTokenIndex: 'u64', MiningEligibilityTokenCalculatedEligibility: 'u64', MiningEligibilityTokenLockedPercentage: 'u32', MiningEligibilityTokenAuditorAccountID: 'u64', MiningEligibilityTokenResult: { token_calculated_eligibility: 'u64', token_token_locked_percentage: 'u32', token_date_audited: 'Moment', token_auditor_account_id: 'u64' }, MiningEligibilityHardware: '[u8; 16]', MiningEligibilityHardwareIndex: 'u64', MiningEligibilityHardwareCalculatedEligibility: 'u64', MiningEligibilityHardwareUptimePercentage: 'u32', MiningEligibilityHardwareAuditorAccountID: 'u64', MiningEligibilityHardwareResult: { hardware_calculated_eligibility: 'u64', hardware_uptime_percentage: 'u32', hardware_block_audited: 'Moment', hardware_auditor_account_id: 'u64' }, MiningEligibilityProxy: '[u8; 16]', MiningEligibilityProxyIndex: 'u64', MiningEligibilityProxyRewardRequest: { proxy_claim_requestor_account_id: 'AccountId', proxy_claim_total_reward_amount: 'Balance', proxy_claim_timestamp_redeemed: 'Moment' }, MiningEligibilityProxyClaimRewardeeData: { proxy_claim_rewardee_account_id: 'AccountId', proxy_claim_reward_amount: 'Balance', proxy_claim_start_date: 'Date', proxy_claim_end_date: 'Date' }, RewardeeData: { proxy_claim_rewardee_account_id: 'AccountId', proxy_claim_reward_amount: 'Balance', proxy_claim_start_date: 'Date', proxy_claim_end_date: 'Date' }, RewardRequestorData: { mining_eligibility_proxy_id: 'MiningEligibilityProxyIndex', total_amt: 'Balance', rewardee_count: 'u64', member_kind: 'u32', requested_date: 'Moment' }, RequestorData: { mining_eligibility_proxy_id: 'MiningEligibilityProxyIndex', total_amt: 'Balance', rewardee_count: 'u64', member_kind: 'u32', requested_date: 'Moment' }, RewardTransferData: { mining_eligibility_proxy_id: 'MiningEligibilityProxyIndex', is_sent: 'bool', total_amt: 'Balance', rewardee_count: 'u64', member_kind: 'u32', requested_date: 'Moment' }, TransferData: { mining_eligibility_proxy_id: 'MiningEligibilityProxyIndex', is_sent: 'bool', total_amt: 'Balance', rewardee_count: 'u64', member_kind: 'u32', requested_date: 'Moment' }, RewardDailyData: { mining_eligibility_proxy_id: 'MiningEligibilityProxyIndex', total_amt: 'Balance', proxy_claim_requestor_account_id: 'AccountId', member_kind: 'u32', rewarded_date: 'Date' }, DailyData: { mining_eligibility_proxy_id: 'MiningEligibilityProxyIndex', total_amt: 'Balance', proxy_claim_requestor_account_id: 'AccountId', member_kind: 'u32', rewarded_date: 'Date' }, MiningClaimsToken: '[u8; 16]', MiningClaimsTokenIndex: 'u64', MiningClaimsTokenClaimAmount: 'u64', MiningClaimsTokenClaimResult: { token_claim_amount: 'u64', token_claim_block_redeemed: 'u64' }, MiningClaimsHardware: '[u8; 16]', MiningClaimsHardwareIndex: 'u64', MiningClaimsHardwareClaimAmount: 'u64', MiningClaimsHardwareClaimResult: { hardware_claim_amount: 'u64', hardware_claim_block_redeemed: 'u64' }, MiningExecutionToken: '[u8; 16]', MiningExecutionTokenIndex: 'u64', MiningExecutionTokenExecutorAccountID: 'u64', MiningExecutionTokenExecutionResult: { token_execution_exector_account_id: 'u64', token_execution_started_block: 'Moment', token_execution_ended_block: 'Moment' }, ExchangeRateIndex: 'u64', ExchangeRateSetting: { hbtc: 'u64', dot: 'u64', iota: 'u64', fil: 'u64', decimals_after_point: 'u32' }, HBTCRate: 'u64', DOTRate: 'u64', IOTARate: 'u64', FILRate: 'u64', DecimalsAfterPoint: 'u32' } } ] }; export default definitions;
the_stack
import {ModelAttributes} from './galleries/AbstractGallery'; import {getIcon} from './Utility'; export declare interface ItemOptions { lightbox?: boolean; selectable?: boolean; activable?: boolean; gap?: number; showLabels?: 'hover' | 'never' | 'always'; } export interface ItemTitle { title: string; link: string; linkTarget: '_blank' | '_self' | '_parent' | '_top'; } export type ItemActivateEventDetail<Model extends ModelAttributes> = { clickEvent: MouseEvent; item: Item<Model> }; export class Item<Model extends ModelAttributes> { /** * Cleaned title, used for label / button */ public readonly title: string; /** * Actual row index in the list */ private _row!: number; /** * If is actually the last element of a row */ private _last!: boolean; /** * Computed size (real used size) */ private _width!: number; private _height!: number; /** * Wherever item is selected or not * @type {boolean} * @private */ private _selected = false; /** * Item root element reference (figure) */ private _element!: HTMLElement; /** * Image container reference (child div, containing the image) */ private _image!: HTMLElement; /** * Reference to the select button */ private _selectBtn!: HTMLElement; /** * * @param {ItemOptions} options * @param model Contains the source data given for an item (e.g object instance from database with id etc..) */ public constructor( private readonly document: Document, private readonly options: ItemOptions, public readonly model: Model, ) { this.title = this.getTitleDetails(model.title); } /** * Cleans html, and returns only the text from all eventual tags * @param {string} term * @returns {ItemTitle} */ private getTitleDetails(term: string | undefined): string { return term ? term.replace(/<(?!\s*br\s*\/?)[^>]+>/gi, '') : ''; } /** * Create DOM elements according to element raw data (thumbnail and enlarged urls) * Also apply border-radius at this level because it never changed threw time */ public init(): HTMLElement { let showLabel = false; let label: HTMLElement | null = null; // Test if label should be added to dom const showLabelValues = ['always', 'hover']; if (this.title && this.options.showLabels && showLabelValues.includes(this.options.showLabels)) { showLabel = true; } const element = this.document.createElement('div') as HTMLElement; let image: HTMLElement = this.document.createElement('div'); const link = this.getLinkElement(); let zoomable: HTMLElement | null = null; // Activation is listened on label/button or on whole image if lightbox is off. // If label is not a button, it becomes a button let activable: HTMLElement | null = null; if (this.options.lightbox && showLabel && link) { label = link; label.classList.add('button'); zoomable = image; activable = link; } else if (this.options.lightbox && showLabel && !link) { label = this.document.createElement('div'); if (this.options.activable) { activable = label; label.classList.add('button'); zoomable = image; } else { zoomable = element; } } else if (this.options.lightbox && !showLabel) { // Actually, lightbox has priority on the link that is ignored... zoomable = element; // May be dangerous to consider image as activation, because opening the lightbox is already an action and we could have two... // It's ok if activate event is used for tracking, but not if it's used to do an action. // In the doubt, for now it's not allowed // activable = element; } else if (!this.options.lightbox && showLabel && link) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion image = this.getLinkElement()!; label = link; label.classList.add('button'); activable = element; } else if (!this.options.lightbox && showLabel && !link) { label = this.document.createElement('div'); if (this.options.activable) { activable = element; label.classList.add('button'); } } else if (!this.options.lightbox && !showLabel && link) { image = link; activable = link; } if (zoomable) { zoomable.classList.add('zoomable'); zoomable.addEventListener('click', () => { const event = new CustomEvent<Item<Model>>('zoom', {detail: this}); this._element.dispatchEvent(event); }); } if (activable) { activable.classList.add('activable'); activable.addEventListener('click', (ev) => { const data: ItemActivateEventDetail<Model> = { item: this, clickEvent: ev, }; const activableEvent = new CustomEvent<ItemActivateEventDetail<Model>>('activate', {detail: data}); this._element.dispatchEvent(activableEvent); }); } image.style.backgroundSize = this.model.backgroundSize || 'cover'; image.style.backgroundPosition = this.model.backgroundPosition || 'center'; image.classList.add('image'); element.classList.add('figure'); element.appendChild(image); if (this.model.color) { element.style.backgroundColor = this.model.color + '11'; } this._element = element; this._image = image; if (label) { label.innerHTML = this.title; label.classList.add('title'); if (this.options.showLabels === 'hover') { label.classList.add('hover'); } element.appendChild(label); } if (this.options.selectable) { if (this.model.selected) { this.select(); } this._selectBtn = this.document.createElement('div'); this._selectBtn.appendChild(getIcon(this.document, 'natural-gallery-icon-select')); this._selectBtn.classList.add('selectBtn'); this._selectBtn.addEventListener('click', (e) => { e.stopPropagation(); this.toggleSelect(); const event = new CustomEvent<Item<Model>>('select', {detail: this}); this._element.dispatchEvent(event); }); this._element.appendChild(this._selectBtn); } this.style(); return element; } /** * Use computed (organized) data to apply style (size and margin) to elements on DOM * Does not apply border-radius because is used to restyle data on browser resize, and border-radius don't change. */ public style(): void { if (!this._element) { return; } this._element.style.width = String(this.width + 'px'); this._element.style.height = String(this.height + 'px'); this._element.style.marginBottom = String(this.options.gap + 'px'); if (this.last) { this._element.style.marginRight = '0'; } else { this._element.style.marginRight = String(this.options.gap + 'px'); } } /** * This function prepare loaded/loading status and return root element. * @returns {HTMLElement} */ public loadImage(): void { const img = this.document.createElement('img'); img.setAttribute('src', this.model.thumbnailSrc); this._image.style.backgroundImage = 'url(' + this.model.thumbnailSrc + ')'; img.addEventListener('load', () => { this._element.classList.add('loaded'); }); // Detect errored images and hide them smartly img.addEventListener('error', () => { this._element.classList.add('errored'); }); } public toggleSelect(): void { if (this._selected) { this.unselect(); } else { this.select(); } } public select(): void { this._selected = true; this._element.classList.add('selected'); } public unselect(): void { this._selected = false; this._element.classList.remove('selected'); } private getLinkElement(): HTMLElement | null { if (this.model.link) { const link = this.document.createElement('a'); link.setAttribute('href', this.model.link); link.classList.add('link'); if (this.model.linkTarget) { link.setAttribute('target', this.model.linkTarget); } return link; } return null; } public remove(): void { if (this._element.parentNode) { this._element.parentNode.removeChild(this._element); } } get last(): boolean { return this._last; } set last(value: boolean) { this._last = value; } get row(): number { return this._row; } set row(value: number) { this._row = value; } get height(): number { return this._height; } set height(value: number) { this._height = value; } get width(): number { return this._width; } set width(value: number) { this._width = value; } get enlargedWidth(): number { return this.model.enlargedWidth; } get enlargedHeight(): number { return this.model.enlargedHeight; } get selected(): boolean { return this._selected; } get element(): HTMLElement { return this._element; } }
the_stack
declare module 'stripe' { namespace Stripe { /** * The Capability object. */ interface Capability { /** * The identifier for the capability. */ id: string; /** * String representing the object's type. Objects of the same type share the same value. */ object: 'capability'; /** * The account for which the capability enables functionality. */ account: string | Stripe.Account; future_requirements?: Capability.FutureRequirements; /** * Whether the capability has been requested. */ requested: boolean; /** * Time at which the capability was requested. Measured in seconds since the Unix epoch. */ requested_at: number | null; requirements?: Capability.Requirements; /** * The status of the capability. Can be `active`, `inactive`, `pending`, or `unrequested`. */ status: Capability.Status; } namespace Capability { interface FutureRequirements { /** * Fields that are due and can be satisfied by providing the corresponding alternative fields instead. */ alternatives: Array<FutureRequirements.Alternative> | null; /** * Date on which `future_requirements` merges with the main `requirements` hash and `future_requirements` becomes empty. After the transition, `currently_due` requirements may immediately become `past_due`, but the account may also be given a grace period depending on the capability's enablement state prior to transitioning. */ current_deadline: number | null; /** * Fields that need to be collected to keep the capability enabled. If not collected by `future_requirements[current_deadline]`, these fields will transition to the main `requirements` hash. */ currently_due: Array<string>; /** * This is typed as a string for consistency with `requirements.disabled_reason`, but it safe to assume `future_requirements.disabled_reason` is empty because fields in `future_requirements` will never disable the account. */ disabled_reason: string | null; /** * Fields that are `currently_due` and need to be collected again because validation or verification failed. */ errors: Array<FutureRequirements.Error>; /** * Fields that need to be collected assuming all volume thresholds are reached. As they become required, they appear in `currently_due` as well. */ eventually_due: Array<string>; /** * Fields that weren't collected by `requirements.current_deadline`. These fields need to be collected to enable the capability on the account. New fields will never appear here; `future_requirements.past_due` will always be a subset of `requirements.past_due`. */ past_due: Array<string>; /** * Fields that may become required depending on the results of verification or review. Will be an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due` or `currently_due`. */ pending_verification: Array<string>; } namespace FutureRequirements { interface Alternative { /** * Fields that can be provided to satisfy all fields in `original_fields_due`. */ alternative_fields_due: Array<string>; /** * Fields that are due and can be satisfied by providing all fields in `alternative_fields_due`. */ original_fields_due: Array<string>; } interface Error { /** * The code for the type of error. */ code: Error.Code; /** * An informative message that indicates the error type and provides additional details about the error. */ reason: string; /** * The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. */ requirement: string; } namespace Error { type Code = | 'invalid_address_city_state_postal_code' | 'invalid_street_address' | 'invalid_value_other' | 'verification_document_address_mismatch' | 'verification_document_address_missing' | 'verification_document_corrupt' | 'verification_document_country_not_supported' | 'verification_document_dob_mismatch' | 'verification_document_duplicate_type' | 'verification_document_expired' | 'verification_document_failed_copy' | 'verification_document_failed_greyscale' | 'verification_document_failed_other' | 'verification_document_failed_test_mode' | 'verification_document_fraudulent' | 'verification_document_id_number_mismatch' | 'verification_document_id_number_missing' | 'verification_document_incomplete' | 'verification_document_invalid' | 'verification_document_issue_or_expiry_date_missing' | 'verification_document_manipulated' | 'verification_document_missing_back' | 'verification_document_missing_front' | 'verification_document_name_mismatch' | 'verification_document_name_missing' | 'verification_document_nationality_mismatch' | 'verification_document_not_readable' | 'verification_document_not_signed' | 'verification_document_not_uploaded' | 'verification_document_photo_mismatch' | 'verification_document_too_large' | 'verification_document_type_not_supported' | 'verification_failed_address_match' | 'verification_failed_business_iec_number' | 'verification_failed_document_match' | 'verification_failed_id_number_match' | 'verification_failed_keyed_identity' | 'verification_failed_keyed_match' | 'verification_failed_name_match' | 'verification_failed_other' | 'verification_failed_tax_id_match' | 'verification_failed_tax_id_not_issued' | 'verification_missing_executives' | 'verification_missing_owners' | 'verification_requires_additional_memorandum_of_associations'; } } interface Requirements { /** * Fields that are due and can be satisfied by providing the corresponding alternative fields instead. */ alternatives: Array<Requirements.Alternative> | null; /** * Date by which the fields in `currently_due` must be collected to keep the capability enabled for the account. These fields may disable the capability sooner if the next threshold is reached before they are collected. */ current_deadline: number | null; /** * Fields that need to be collected to keep the capability enabled. If not collected by `current_deadline`, these fields appear in `past_due` as well, and the capability is disabled. */ currently_due: Array<string>; /** * If the capability is disabled, this string describes why. Can be `requirements.past_due`, `requirements.pending_verification`, `listed`, `platform_paused`, `rejected.fraud`, `rejected.listed`, `rejected.terms_of_service`, `rejected.other`, `under_review`, or `other`. * * `rejected.unsupported_business` means that the account's business is not supported by the capability. For example, payment methods may restrict the businesses they support in their terms of service: * * - [Afterpay Clearpay's terms of service](https://stripe.com/afterpay-clearpay/legal#restricted-businesses) * * If you believe that the rejection is in error, please contact support@stripe.com for assistance. */ disabled_reason: string | null; /** * Fields that are `currently_due` and need to be collected again because validation or verification failed. */ errors: Array<Requirements.Error>; /** * Fields that need to be collected assuming all volume thresholds are reached. As they become required, they appear in `currently_due` as well, and `current_deadline` becomes set. */ eventually_due: Array<string>; /** * Fields that weren't collected by `current_deadline`. These fields need to be collected to enable the capability on the account. */ past_due: Array<string>; /** * Fields that may become required depending on the results of verification or review. Will be an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due`, `currently_due`, or `past_due`. */ pending_verification: Array<string>; } namespace Requirements { interface Alternative { /** * Fields that can be provided to satisfy all fields in `original_fields_due`. */ alternative_fields_due: Array<string>; /** * Fields that are due and can be satisfied by providing all fields in `alternative_fields_due`. */ original_fields_due: Array<string>; } interface Error { /** * The code for the type of error. */ code: Error.Code; /** * An informative message that indicates the error type and provides additional details about the error. */ reason: string; /** * The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. */ requirement: string; } namespace Error { type Code = | 'invalid_address_city_state_postal_code' | 'invalid_street_address' | 'invalid_value_other' | 'verification_document_address_mismatch' | 'verification_document_address_missing' | 'verification_document_corrupt' | 'verification_document_country_not_supported' | 'verification_document_dob_mismatch' | 'verification_document_duplicate_type' | 'verification_document_expired' | 'verification_document_failed_copy' | 'verification_document_failed_greyscale' | 'verification_document_failed_other' | 'verification_document_failed_test_mode' | 'verification_document_fraudulent' | 'verification_document_id_number_mismatch' | 'verification_document_id_number_missing' | 'verification_document_incomplete' | 'verification_document_invalid' | 'verification_document_issue_or_expiry_date_missing' | 'verification_document_manipulated' | 'verification_document_missing_back' | 'verification_document_missing_front' | 'verification_document_name_mismatch' | 'verification_document_name_missing' | 'verification_document_nationality_mismatch' | 'verification_document_not_readable' | 'verification_document_not_signed' | 'verification_document_not_uploaded' | 'verification_document_photo_mismatch' | 'verification_document_too_large' | 'verification_document_type_not_supported' | 'verification_failed_address_match' | 'verification_failed_business_iec_number' | 'verification_failed_document_match' | 'verification_failed_id_number_match' | 'verification_failed_keyed_identity' | 'verification_failed_keyed_match' | 'verification_failed_name_match' | 'verification_failed_other' | 'verification_failed_tax_id_match' | 'verification_failed_tax_id_not_issued' | 'verification_missing_executives' | 'verification_missing_owners' | 'verification_requires_additional_memorandum_of_associations'; } } type Status = | 'active' | 'disabled' | 'inactive' | 'pending' | 'unrequested'; } interface CapabilityRetrieveParams { /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; } interface CapabilityUpdateParams { /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; /** * Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. */ requested?: boolean; } interface CapabilityListParams { /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; } } }
the_stack
import { Event } from 'vs/base/common/event'; import { withNullAsUndefined } from 'vs/base/common/types'; import { URI, UriComponents } from 'vs/base/common/uri'; import { IChannel } from 'vs/base/parts/ipc/common/ipc'; import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration'; import { ILogService } from 'vs/platform/log/common/log'; import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { serializeEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariableShared'; import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver'; import { SideBySideEditor, EditorResourceAccessor } from 'vs/workbench/common/editor'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { Schemas } from 'vs/base/common/network'; import { ILabelService } from 'vs/platform/label/common/label'; import { IEnvironmentVariableService, ISerializableEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariable'; import { IProcessDataEvent, IRequestResolveVariablesEvent, IShellLaunchConfig, IShellLaunchConfigDto, ITerminalDimensionsOverride, ITerminalEnvironment, ITerminalLaunchError, ITerminalProfile, ITerminalsLayoutInfo, ITerminalsLayoutInfoById, TerminalIcon, IProcessProperty, TerminalShellType, ProcessPropertyType, ProcessCapability, IProcessPropertyMap } from 'vs/platform/terminal/common/terminal'; import { IGetTerminalLayoutInfoArgs, IProcessDetails, IPtyHostProcessReplayEvent, ISetTerminalLayoutInfoArgs } from 'vs/platform/terminal/common/terminalProcess'; import { IProcessEnvironment, OperatingSystem } from 'vs/base/common/platform'; export const REMOTE_TERMINAL_CHANNEL_NAME = 'remoteterminal'; export interface ICompleteTerminalConfiguration { 'terminal.integrated.automationShell.windows': string; 'terminal.integrated.automationShell.osx': string; 'terminal.integrated.automationShell.linux': string; 'terminal.integrated.shell.windows': string; 'terminal.integrated.shell.osx': string; 'terminal.integrated.shell.linux': string; 'terminal.integrated.shellArgs.windows': string | string[]; 'terminal.integrated.shellArgs.osx': string | string[]; 'terminal.integrated.shellArgs.linux': string | string[]; 'terminal.integrated.env.windows': ITerminalEnvironment; 'terminal.integrated.env.osx': ITerminalEnvironment; 'terminal.integrated.env.linux': ITerminalEnvironment; 'terminal.integrated.cwd': string; 'terminal.integrated.detectLocale': 'auto' | 'off' | 'on'; } export type ITerminalEnvironmentVariableCollections = [string, ISerializableEnvironmentVariableCollection][]; export interface IWorkspaceFolderData { uri: UriComponents; name: string; index: number; } export interface ICreateTerminalProcessArguments { configuration: ICompleteTerminalConfiguration; resolvedVariables: { [name: string]: string; }; envVariableCollections: ITerminalEnvironmentVariableCollections; shellLaunchConfig: IShellLaunchConfigDto; workspaceId: string; workspaceName: string; workspaceFolders: IWorkspaceFolderData[]; activeWorkspaceFolder: IWorkspaceFolderData | null; activeFileResource: UriComponents | undefined; shouldPersistTerminal: boolean; cols: number; rows: number; unicodeVersion: '6' | '11'; resolverEnv: { [key: string]: string | null; } | undefined } export interface ICreateTerminalProcessResult { persistentTerminalId: number; resolvedShellLaunchConfig: IShellLaunchConfigDto; } export class RemoteTerminalChannelClient { get onPtyHostExit(): Event<void> { return this._channel.listen<void>('$onPtyHostExitEvent'); } get onPtyHostStart(): Event<void> { return this._channel.listen<void>('$onPtyHostStartEvent'); } get onPtyHostUnresponsive(): Event<void> { return this._channel.listen<void>('$onPtyHostUnresponsiveEvent'); } get onPtyHostResponsive(): Event<void> { return this._channel.listen<void>('$onPtyHostResponsiveEvent'); } get onPtyHostRequestResolveVariables(): Event<IRequestResolveVariablesEvent> { return this._channel.listen<IRequestResolveVariablesEvent>('$onPtyHostRequestResolveVariablesEvent'); } get onProcessData(): Event<{ id: number, event: IProcessDataEvent | string }> { return this._channel.listen<{ id: number, event: IProcessDataEvent | string }>('$onProcessDataEvent'); } get onProcessExit(): Event<{ id: number, event: number | undefined }> { return this._channel.listen<{ id: number, event: number | undefined }>('$onProcessExitEvent'); } get onProcessReady(): Event<{ id: number, event: { pid: number, cwd: string, capabilities: ProcessCapability[], requireWindowsMode?: boolean } }> { return this._channel.listen<{ id: number, event: { pid: number, cwd: string, capabilities: ProcessCapability[], requiresWindowsMode?: boolean } }>('$onProcessReadyEvent'); } get onProcessReplay(): Event<{ id: number, event: IPtyHostProcessReplayEvent }> { return this._channel.listen<{ id: number, event: IPtyHostProcessReplayEvent }>('$onProcessReplayEvent'); } get onProcessTitleChanged(): Event<{ id: number, event: string }> { return this._channel.listen<{ id: number, event: string }>('$onProcessTitleChangedEvent'); } get onProcessShellTypeChanged(): Event<{ id: number, event: TerminalShellType | undefined }> { return this._channel.listen<{ id: number, event: TerminalShellType | undefined }>('$onProcessShellTypeChangedEvent'); } get onProcessOverrideDimensions(): Event<{ id: number, event: ITerminalDimensionsOverride | undefined }> { return this._channel.listen<{ id: number, event: ITerminalDimensionsOverride | undefined }>('$onProcessOverrideDimensionsEvent'); } get onProcessResolvedShellLaunchConfig(): Event<{ id: number, event: IShellLaunchConfig }> { return this._channel.listen<{ id: number, event: IShellLaunchConfig }>('$onProcessResolvedShellLaunchConfigEvent'); } get onProcessOrphanQuestion(): Event<{ id: number }> { return this._channel.listen<{ id: number }>('$onProcessOrphanQuestion'); } get onProcessDidChangeHasChildProcesses(): Event<{ id: number, event: boolean }> { return this._channel.listen<{ id: number, event: boolean }>('$onProcessDidChangeHasChildProcesses'); } get onExecuteCommand(): Event<{ reqId: number, commandId: string, commandArgs: any[] }> { return this._channel.listen<{ reqId: number, commandId: string, commandArgs: any[] }>('$onExecuteCommand'); } get onDidRequestDetach(): Event<{ requestId: number, workspaceId: string, instanceId: number }> { return this._channel.listen<{ requestId: number, workspaceId: string, instanceId: number }>('$onDidRequestDetach'); } get onDidChangeProperty(): Event<{ id: number, property: IProcessProperty<any> }> { return this._channel.listen<{ id: number, property: IProcessProperty<any> }>('$onDidChangeProperty'); } constructor( private readonly _remoteAuthority: string, private readonly _channel: IChannel, @IWorkbenchConfigurationService private readonly _configurationService: IWorkbenchConfigurationService, @IWorkspaceContextService private readonly _workspaceContextService: IWorkspaceContextService, @IConfigurationResolverService private readonly _resolverService: IConfigurationResolverService, @IEnvironmentVariableService private readonly _environmentVariableService: IEnvironmentVariableService, @IRemoteAuthorityResolverService private readonly _remoteAuthorityResolverService: IRemoteAuthorityResolverService, @ILogService private readonly _logService: ILogService, @IEditorService private readonly _editorService: IEditorService, @ILabelService private readonly _labelService: ILabelService, ) { } restartPtyHost(): Promise<void> { return this._channel.call('$restartPtyHost', []); } async createProcess(shellLaunchConfig: IShellLaunchConfigDto, configuration: ICompleteTerminalConfiguration, activeWorkspaceRootUri: URI | undefined, shouldPersistTerminal: boolean, cols: number, rows: number, unicodeVersion: '6' | '11'): Promise<ICreateTerminalProcessResult> { // Be sure to first wait for the remote configuration await this._configurationService.whenRemoteConfigurationLoaded(); // We will use the resolver service to resolve all the variables in the config / launch config // But then we will keep only some variables, since the rest need to be resolved on the remote side const resolvedVariables = Object.create(null); const lastActiveWorkspace = activeWorkspaceRootUri ? withNullAsUndefined(this._workspaceContextService.getWorkspaceFolder(activeWorkspaceRootUri)) : undefined; let allResolvedVariables: Map<string, string> | undefined = undefined; try { allResolvedVariables = (await this._resolverService.resolveAnyMap(lastActiveWorkspace, { shellLaunchConfig, configuration })).resolvedVariables; } catch (err) { this._logService.error(err); } if (allResolvedVariables) { for (const [name, value] of allResolvedVariables.entries()) { if (/^config:/.test(name) || name === 'selectedText' || name === 'lineNumber') { resolvedVariables[name] = value; } } } const envVariableCollections: ITerminalEnvironmentVariableCollections = []; for (const [k, v] of this._environmentVariableService.collections.entries()) { envVariableCollections.push([k, serializeEnvironmentVariableCollection(v.map)]); } const resolverResult = await this._remoteAuthorityResolverService.resolveAuthority(this._remoteAuthority); const resolverEnv = resolverResult.options && resolverResult.options.extensionHostEnv; const workspace = this._workspaceContextService.getWorkspace(); const workspaceFolders = workspace.folders; const activeWorkspaceFolder = activeWorkspaceRootUri ? this._workspaceContextService.getWorkspaceFolder(activeWorkspaceRootUri) : null; const activeFileResource = EditorResourceAccessor.getOriginalUri(this._editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: [Schemas.file, Schemas.userData, Schemas.vscodeRemote] }); const args: ICreateTerminalProcessArguments = { configuration, resolvedVariables, envVariableCollections, shellLaunchConfig, workspaceId: workspace.id, workspaceName: this._labelService.getWorkspaceLabel(workspace), workspaceFolders, activeWorkspaceFolder, activeFileResource, shouldPersistTerminal, cols, rows, unicodeVersion, resolverEnv }; return await this._channel.call<ICreateTerminalProcessResult>('$createProcess', args); } requestDetachInstance(workspaceId: string, instanceId: number): Promise<IProcessDetails | undefined> { return this._channel.call('$requestDetachInstance', [workspaceId, instanceId]); } acceptDetachInstanceReply(requestId: number, persistentProcessId: number): Promise<void> { return this._channel.call('$acceptDetachInstanceReply', [requestId, persistentProcessId]); } attachToProcess(id: number): Promise<void> { return this._channel.call('$attachToProcess', [id]); } detachFromProcess(id: number): Promise<void> { return this._channel.call('$detachFromProcess', [id]); } listProcesses(): Promise<IProcessDetails[]> { return this._channel.call('$listProcesses'); } reduceConnectionGraceTime(): Promise<void> { return this._channel.call('$reduceConnectionGraceTime'); } processBinary(id: number, data: string): Promise<void> { return this._channel.call('$processBinary', [id, data]); } start(id: number): Promise<ITerminalLaunchError | void> { return this._channel.call('$start', [id]); } input(id: number, data: string): Promise<void> { return this._channel.call('$input', [id, data]); } acknowledgeDataEvent(id: number, charCount: number): Promise<void> { return this._channel.call('$acknowledgeDataEvent', [id, charCount]); } setUnicodeVersion(id: number, version: '6' | '11'): Promise<void> { return this._channel.call('$setUnicodeVersion', [id, version]); } shutdown(id: number, immediate: boolean): Promise<void> { return this._channel.call('$shutdown', [id, immediate]); } resize(id: number, cols: number, rows: number): Promise<void> { return this._channel.call('$resize', [id, cols, rows]); } getInitialCwd(id: number): Promise<string> { return this._channel.call('$getInitialCwd', [id]); } getCwd(id: number): Promise<string> { return this._channel.call('$getCwd', [id]); } orphanQuestionReply(id: number): Promise<void> { return this._channel.call('$orphanQuestionReply', [id]); } sendCommandResult(reqId: number, isError: boolean, payload: any): Promise<void> { return this._channel.call('$sendCommandResult', [reqId, isError, payload]); } getDefaultSystemShell(osOverride?: OperatingSystem): Promise<string> { return this._channel.call('$getDefaultSystemShell', [osOverride]); } getProfiles(profiles: unknown, defaultProfile: unknown, includeDetectedProfiles?: boolean): Promise<ITerminalProfile[]> { return this._channel.call('$getProfiles', [this._workspaceContextService.getWorkspace().id, profiles, defaultProfile, includeDetectedProfiles]); } acceptPtyHostResolvedVariables(requestId: number, resolved: string[]) { return this._channel.call('$acceptPtyHostResolvedVariables', [requestId, resolved]); } getEnvironment(): Promise<IProcessEnvironment> { return this._channel.call('$getEnvironment'); } getWslPath(original: string): Promise<string> { return this._channel.call('$getWslPath', [original]); } setTerminalLayoutInfo(layout: ITerminalsLayoutInfoById): Promise<void> { const workspace = this._workspaceContextService.getWorkspace(); const args: ISetTerminalLayoutInfoArgs = { workspaceId: workspace.id, tabs: layout.tabs }; return this._channel.call<void>('$setTerminalLayoutInfo', args); } updateTitle(id: number, title: string): Promise<string> { return this._channel.call('$updateTitle', [id, title]); } updateIcon(id: number, icon: TerminalIcon, color?: string): Promise<string> { return this._channel.call('$updateIcon', [id, icon, color]); } refreshProperty<T extends ProcessPropertyType>(id: number, property: ProcessPropertyType): Promise<IProcessPropertyMap[T]> { return this._channel.call('$refreshProperty', [id, property]); } updateProperty<T extends ProcessPropertyType>(id: number, property: ProcessPropertyType, value: IProcessPropertyMap[T]): Promise<void> { return this._channel.call('$updateProperty', [id, property, value]); } getTerminalLayoutInfo(): Promise<ITerminalsLayoutInfo | undefined> { const workspace = this._workspaceContextService.getWorkspace(); const args: IGetTerminalLayoutInfoArgs = { workspaceId: workspace.id, }; return this._channel.call<ITerminalsLayoutInfo>('$getTerminalLayoutInfo', args); } reviveTerminalProcesses(state: string): Promise<void> { return this._channel.call('$reviveTerminalProcesses', [state]); } serializeTerminalState(ids: number[]): Promise<string> { return this._channel.call('$serializeTerminalState', [ids]); } }
the_stack
import { LoginConfig, OriginData, WhiteLabelData } from "@toruslabs/openlogin-jrpc"; import { ExtraLoginOptions } from "@toruslabs/openlogin-utils"; export declare const iframeDOMElementID = "openlogin-iframe"; export declare const modalDOMElementID = "openlogin-modal"; export declare const storeKey = "openlogin_store"; export declare type PopupResponse<T> = { pid: string; data: T; }; export declare type Maybe<T> = Partial<T> | null | undefined; export declare const UX_MODE: { readonly POPUP: "popup"; readonly REDIRECT: "redirect"; }; export declare type UX_MODE_TYPE = typeof UX_MODE[keyof typeof UX_MODE]; export declare const OPENLOGIN_METHOD: { readonly LOGIN: "openlogin_login"; readonly LOGOUT: "openlogin_logout"; readonly CHECK_3PC_SUPPORT: "openlogin_check_3PC_support"; readonly SET_PID_DATA: "openlogin_set_pid_data"; readonly GET_DATA: "openlogin_get_data"; }; export declare type CUSTOM_OPENLOGIN_METHOD_TYPE = string & { toString?: (radix?: number) => string; }; export declare type OPENLOGIN_METHOD_TYPE = typeof OPENLOGIN_METHOD[keyof typeof OPENLOGIN_METHOD]; export declare const ALLOWED_INTERACTIONS: { readonly POPUP: "popup"; readonly REDIRECT: "redirect"; readonly JRPC: "jrpc"; }; export declare type ALLOWED_INTERACTIONS_TYPE = typeof ALLOWED_INTERACTIONS[keyof typeof ALLOWED_INTERACTIONS]; export declare type RequestParams = { startUrl?: string; popupUrl?: string; method: OPENLOGIN_METHOD_TYPE | CUSTOM_OPENLOGIN_METHOD_TYPE; params: Record<string, unknown>[]; allowedInteractions: ALLOWED_INTERACTIONS_TYPE[]; }; export declare type BaseLogoutParams = { /** * You can get your clientId/projectId by registering your * dapp on {@link "https://developer.tor.us"| developer dashbaord} */ clientId: string; /** * Setting fastLogin to `true` will disable fast login for the user on this dapp. * * Defaults to false * @defaultValue false * @experimental * * @remarks * Use this option with caution only when you are sure that you wish to disable fast login for the user on this dapp. * In general you may not need to use this option. */ fastLogin: boolean; }; export declare type BaseRedirectParams = { /** * redirectUrl is the dapp's url where user will be redirected after login. * * @remarks * Register this url at {@link "https://developer.tor.us"| developer dashbaord} * else initialization will give error. */ redirectUrl?: string; /** * Any custom state you wish to pass along. This will be returned to you post redirect. * Use this to store data that you want to be available to the dapp after login. */ appState?: string; }; export declare const OPENLOGIN_NETWORK: { readonly MAINNET: "mainnet"; readonly TESTNET: "testnet"; readonly DEVELOPMENT: "development"; }; export declare type OPENLOGIN_NETWORK_TYPE = typeof OPENLOGIN_NETWORK[keyof typeof OPENLOGIN_NETWORK]; export declare type OpenLoginOptions = { /** * You can get your clientId/projectId by registering your * dapp on {@link "https://developer.tor.us"| developer dashbaord} */ clientId: string; /** * network specifies the openlogin iframe url url to be used. * * - `'mainnet'`: https://app.openlogin.com will be used which is the production version. * - `'testnet'`: https://beta.openlogin.com will be used which is the beta version. * - `'development'`: http://localhost:3000 will be used for development purpose. */ network: OPENLOGIN_NETWORK_TYPE; /** * Setting no3PC forces openlogin to assume that third party cookies are blocked * in the browser. * * @defaultValue false * @remarks * Only pass no3PC to `true` when you are sure that third party cookies are not * supported. By default openlogin will self check third party cookies and proceed * accordingly. */ no3PC?: boolean; /** * redirectUrl is the dapp's url where user will be redirected after login. * * @remarks * Register this url at {@link "https://developer.tor.us"| developer dashbaord} * else initialization will give error. */ redirectUrl?: string; /** * two uxModes are supported:- * - `'POPUP'`: In this uxMode, a popup will be shown to user for login. * - `'REDIRECT'`: In this uxMode, user will be redirected to a new window tab for login. * * @defaultValue `'POPUP'` * @remarks * * Use of `'REDIRECT'` mode is recommended in browsers where popups might get blocked. */ uxMode?: UX_MODE_TYPE; /** * replaceUrlOnRedirect removes the params from the redirected url after login * * @defaultValue true */ replaceUrlOnRedirect?: boolean; /** * originData is used to verify the origin of dapp by iframe. * * @internal * @remarks * You don't have to pass originData explicitly if you have registered your dapp at * {@link "https://developer.tor.us"| developer dashbaord}. * * originData contains a signature of dapp's origin url which is generated using * project's secret. */ originData?: OriginData; /** * loginConfig enables you to pass your own login verifiers configuration for various * loginProviders. * * loginConfig is key value map where each key should be a valid loginProvider and value * should be custom configuration for that loginProvider * * @remarks * You can deploy your own verifiers from {@link "https://developer.tor.us"| developer dashbaord} * to use here. * */ loginConfig?: LoginConfig; /** * _iframeUrl is for internal development use only and is used to override the * `network` parameter. * @internal */ _iframeUrl?: string; /** * _startUrl is for internal development use only and is used specify authentication * start url of iframe. * @internal */ _startUrl?: string; /** * _popupUrl is for internal development use only and is used specify url of popup window * for popup uxMode. * @internal */ _popupUrl?: string; /** * options for whitelabling default openlogin modal. */ whiteLabel?: WhiteLabelData; }; export declare const LOGIN_PROVIDER: { readonly GOOGLE: "google"; readonly FACEBOOK: "facebook"; readonly REDDIT: "reddit"; readonly DISCORD: "discord"; readonly TWITCH: "twitch"; readonly APPLE: "apple"; readonly LINE: "line"; readonly GITHUB: "github"; readonly KAKAO: "kakao"; readonly LINKEDIN: "linkedin"; readonly TWITTER: "twitter"; readonly WEIBO: "weibo"; readonly WECHAT: "wechat"; readonly EMAIL_PASSWORDLESS: "email_passwordless"; readonly WEBAUTHN: "webauthn"; readonly CUSTOM_JWT: "custom_jwt"; }; export declare type CUSTOM_JWT_PARAMS = { verifierIdField: string; /** * verifierId is the `value` of the jwt verifier id field which you will define * while deploying your verifier. More details about custom verifier are given * {@link "https://docs.tor.us/customauth/setting-up-verifiers/custom-verifier" | here} * * It should be unique identifier field for a user, this field must also be * encoded in your jwt token. * */ verifierId: string; /** * id token associated with verifierId. */ idToken: string; /** * access token associated with verifierId. */ accessToken?: string; userInfoRoute?: string; }; /** * {@label loginProviderType} */ export declare type LOGIN_PROVIDER_TYPE = typeof LOGIN_PROVIDER[keyof typeof LOGIN_PROVIDER]; export declare type CUSTOM_LOGIN_PROVIDER_TYPE = string & { toString?: (radix?: number) => string; }; export declare type LoginParams = BaseRedirectParams & { /** * loginProvider sets the oauth login method to be used. * You can use any of the valid loginProvider from the supported list. * * If this param is not passed then it will show all the available * login methods to user in a modal. * */ loginProvider?: LOGIN_PROVIDER_TYPE | CUSTOM_LOGIN_PROVIDER_TYPE; /** * customJwtParams are required if you are using `custom_jwt` as your * login provider. You can obtain your verifier by deploying your verifier * from {@link "https://developer.tor.us"| developer dashbaord}. Please * contact torus support if you face any difficulty in deploying verifiers */ customJwtParams?: CUSTOM_JWT_PARAMS; /** * Setting fastLogin to `true` will force user to login with webauthn if * webauthn is available on device. * * Defaults to false * @defaultValue false * @experimental * * @remarks * Use this option with caution only when you are sure about that user has * enabled webauthn while registration, else don't use this option. * Openlogin will itself take care of detecting and handling webauthn. * In general you may not need to use this option. */ fastLogin?: boolean; /** * Setting relogin to `true` will force user to relogin when login * method is called even if user is already logged in. By default login * method call skips login process if user is already logged in. * * * Defaults to false * @defaultValue false */ relogin?: boolean; /** * setting skipTKey to `true` will skip TKey onboarding for new users, * whereas old users will be presented with an option to skip tKey in UI * if this option is enabled. * * Defaults to false * @defaultValue false */ skipTKey?: boolean; /** * This option is for internal use only in torus wallet and has not effect * on user's login on other dapps. * * Defaults to false * @defaultValue false * @internal */ getWalletKey?: boolean; /** * extraLoginOptions can be used to pass standard oauth login options to * loginProvider. * * For ex: you will have to pass `login_hint` as user's email and `domain` * as your app domain in `extraLoginOptions` while using `email_passwordless` * loginProvider */ extraLoginOptions?: ExtraLoginOptions; }; export declare type OpenloginUserInfo = { email: string; name: string; profileImage: string; aggregateVerifier: string; verifier: string; verifierId: string; typeOfLogin: LOGIN_PROVIDER_TYPE | CUSTOM_LOGIN_PROVIDER_TYPE; };
the_stack
import dirTree from 'directory-tree'; import Path from 'path'; import fs from 'fs'; import web3 from 'web3'; import * as bunyan from 'bunyan'; import { FileObject, Match, Status, Tag, MatchLevel, FilesInfo, MatchQuality, ContractData } from '../utils/types'; import { checkChainId } from '../utils/utils'; import { Logger } from '../utils/logger'; import rimraf from 'rimraf'; type PathConfig = { matchQuality: MatchQuality chain: string address: string fileName?: string source?: boolean }; export interface IFileService { getTreeByChainAndAddress(chainId: any, address: string): Promise<Array<string>>; getByChainAndAddress(chainId: any, address: string): Promise<Array<FileObject>>; fetchAllFileUrls(chain: string, address: string): Array<string>; fetchAllFilePaths(chain: string, address: string): Array<FileObject>; fetchAllFileContents(chain: string, address: string): Array<FileObject>; findByAddress(address: string, chain: string): Match[]; findAllByAddress(address: string, chain: string): Match[]; save(path: string | PathConfig, file: string): void; deletePartial(chain: string, address: string): void; repositoryPath: string; getTree(chainId: any, address: string, match: string): Promise<FilesInfo<string>>; getContent(chainId: any, address: string, match: string): Promise<FilesInfo<FileObject>>; getContracts(chainId: any): Promise<ContractData>; generateAbsoluteFilePath(pathConfig: PathConfig): string; generateRelativeFilePath(pathConfig: PathConfig): string; generateRelativeContractDir(pathConfig: PathConfig): string; } export class FileService implements IFileService { logger: bunyan; repositoryPath: string; constructor(repositoryPath: string, logger?: bunyan) { this.repositoryPath = repositoryPath; this.logger = logger || Logger("FileService"); } async getTreeByChainAndAddress(chainId: any, address: string): Promise<string[]> { chainId = checkChainId(chainId); return this.fetchAllFileUrls(chainId, address); } async getByChainAndAddress(chainId: any, address: string): Promise<FileObject[]> { chainId = checkChainId(chainId); return this.fetchAllFileContents(chainId, address); } fetchAllFileUrls(chain: string, address: string, match = "full_match"): Array<string> { const files: Array<FileObject> = this.fetchAllFilePaths(chain, address, match); const urls: Array<string> = []; files.forEach((file) => { const relativePath = file.path.split('/repository')[1].substr(1); urls.push(`${process.env.REPOSITORY_URL}/${relativePath}`); }); return urls; } fetchAllFilePaths(chain: string, address: string, match = "full_match"): Array<FileObject> { const fullPath: string = this.repositoryPath + `/contracts/${match}/${chain}/${web3.utils.toChecksumAddress(address)}/`; const files: Array<FileObject> = []; dirTree(fullPath, {}, (item) => { files.push({ "name": item.name, "path": item.path }); }); return files; } fetchAllFileContents(chain: string, address: string, match = "full_match"): Array<FileObject> { const files = this.fetchAllFilePaths(chain, address, match); for (const file in files) { const loadedFile = fs.readFileSync(files[file].path) files[file].content = loadedFile.toString(); } return files; } fetchAllContracts = async(chain: String): Promise<ContractData> => { const fullPath = this.repositoryPath + `/contracts/full_match/${chain}/`; const partialPath = this.repositoryPath + `/contracts/partial_match/${chain}/`; return { full: (fs.existsSync(fullPath)) ? fs.readdirSync(fullPath) : [], partial: (fs.existsSync(partialPath)) ? fs.readdirSync(partialPath) : [] }; } getTree = async (chainId: any, address: string, match: MatchLevel): Promise<FilesInfo<string>> => { chainId = checkChainId(chainId); const fullMatchesTree = this.fetchAllFileUrls(chainId, address, "full_match"); if (fullMatchesTree.length || match === "full_match") { return { status: "full", files: fullMatchesTree }; } const files = this.fetchAllFileUrls(chainId, address, "partial_match"); return { status: "partial", files }; } getContent = async (chainId: any, address: string, match: MatchLevel): Promise<FilesInfo<FileObject>> => { chainId = checkChainId(chainId); const fullMatchesFiles = this.fetchAllFileContents(chainId, address, "full_match"); if (fullMatchesFiles.length || match === "full_match") { return { status: "full", files: fullMatchesFiles }; } const files = this.fetchAllFileContents(chainId, address, "partial_match"); return { status: "partial", files }; } getContracts = async(chainId: any): Promise<ContractData> => { const contracts = await this.fetchAllContracts(chainId); return contracts } // /home/user/sourcify/data/repository/contracts/full_match/5/0x00878Ac0D6B8d981ae72BA7cDC967eA0Fae69df4/sources/filename public generateAbsoluteFilePath(pathConfig: PathConfig) { return Path.join( this.repositoryPath, this.generateRelativeFilePath(pathConfig) ); } // contracts/full_match/5/0x00878Ac0D6B8d981ae72BA7cDC967eA0Fae69df4/sources/filename public generateRelativeFilePath(pathConfig: PathConfig) { return Path.join( this.generateRelativeContractDir(pathConfig), pathConfig.source ? "sources" : "", pathConfig.fileName || "" ); } // contracts/full_match/5/0x00878Ac0D6B8d981ae72BA7cDC967eA0Fae69df4 public generateRelativeContractDir(pathConfig: PathConfig) { return Path.join( "contracts", `${pathConfig.matchQuality}_match`, pathConfig.chain, web3.utils.toChecksumAddress(pathConfig.address) ); } /** * Checks if path exists and for a particular chain returns the perfect or partial match * * @param fullContractPath * @param partialContractPath */ fetchFromStorage(fullContractPath: string, partialContractPath: string): { time: Date, status: Status } { if (fs.existsSync(fullContractPath)) { return { time: fs.statSync(fullContractPath).birthtime, status: 'perfect' } } if (fs.existsSync(partialContractPath)) { return { time: fs.statSync(partialContractPath).birthtime, status: 'partial' } } throw new Error('path not found') } /** * Checks contract existence in repository. * * @param address * @param chain * @param repository */ findByAddress(address: string, chain: string): Match[] { const contractPath = this.generateAbsoluteFilePath({ matchQuality: "full", chain, address, fileName: "metadata.json" }); try { const storageTimestamp = fs.statSync(contractPath).birthtime; return [{ address, status: "perfect", storageTimestamp }]; } catch (e) { throw new Error("Address not found in repository"); } } /** * Checks contract existence in repository for full and partial matches. * * @param address * @param chain * @param repository */ findAllByAddress(address: string, chain: string): Match[] { const fullContractPath = this.generateAbsoluteFilePath({ matchQuality: "full", chain, address, fileName: "metadata.json" }); const partialContractPath = this.generateAbsoluteFilePath({ matchQuality: "partial", chain, address, fileName: "metadata.json" }) try { const storage = this.fetchFromStorage(fullContractPath, partialContractPath) return [ { address, status: storage?.status, storageTimestamp: storage?.time, }, ]; } catch (e) { throw new Error("Address not found in repository"); } } /** * Save file to repository and update the repository tag. The path may include non-existent parent directories. * * @param path the path within the repository where the file will be stored * @param file the content to be stored */ save(path: string | PathConfig, file: string) { const abolsutePath = (typeof path === "string") ? Path.join(this.repositoryPath, path) : this.generateAbsoluteFilePath(path); fs.mkdirSync(Path.dirname(abolsutePath), { recursive: true }); fs.writeFileSync(abolsutePath, file); this.updateRepositoryTag(); } deletePartial(chain: string, address: string) { const pathConfig: PathConfig = { matchQuality: "partial", chain, address, fileName: "" }; const absolutePath = this.generateAbsoluteFilePath(pathConfig); rimraf(absolutePath, err => { if (err) { this.logger.error({ loc: "[FILE_SERVICE:DELETE_PARTIAL]", err: err.message, chain, address }, "Failed deleting a partial match"); } }); } /** * Update repository tag */ updateRepositoryTag() { const filePath: string = Path.join(this.repositoryPath, 'manifest.json') const timestamp = new Date().getTime(); const repositoryVersion = process.env.REPOSITORY_VERSION || '0.1'; const tag: Tag = { timestamp: timestamp, repositoryVersion: repositoryVersion } fs.writeFileSync(filePath, JSON.stringify(tag)); } }
the_stack
import { IBlueprintExternalMessageQueueObj } from './message' import { PackageInfo } from './packageInfo' import { IBlueprintPart, IBlueprintPartInstance, IBlueprintPiece, IBlueprintPieceInstance, IBlueprintResolvedPieceInstance, IBlueprintRundownDB, IBlueprintMutatablePart, IBlueprintSegmentDB, IBlueprintPieceDB, } from './rundown' import { BlueprintMappings } from './studio' import { OnGenerateTimelineObj } from './timeline' /** Common */ export interface ICommonContext { /** * Hash a string. Will return a unique string, to be used for all _id:s that are to be inserted in database * @param originString A representation of the origin of the hash (for logging) * @param originIsNotUnique If the originString is not guaranteed to be unique, set this to true */ getHashId: (originString: string, originIsNotUnique?: boolean) => string /** Un-hash, is return the string that created the hash */ unhashId: (hash: string) => string /** Log a message to the sofie log with level 'debug' */ logDebug: (message: string) => void /** Log a message to the sofie log with level 'info' */ logInfo: (message: string) => void /** Log a message to the sofie log with level 'warn' */ logWarning: (message: string) => void /** Log a message to the sofie log with level 'error' */ logError: (message: string) => void } export function isCommonContext(obj: unknown): obj is ICommonContext { if (!obj || typeof obj !== 'object') { return false } const { getHashId, unhashId, logDebug, logInfo, logWarning, logError } = obj as any return ( typeof getHashId === 'function' && typeof unhashId === 'function' && typeof logDebug === 'function' && typeof logInfo === 'function' && typeof logWarning === 'function' && typeof logError === 'function' ) } export interface IUserNotesContext extends ICommonContext { /** Display a notification to the user of an error */ notifyUserError(message: string, params?: { [key: string]: any }): void /** Display a notification to the user of an warning */ notifyUserWarning(message: string, params?: { [key: string]: any }): void } export function isUserNotesContext(obj: unknown): obj is IUserNotesContext { if (!isCommonContext(obj)) { return false } const { notifyUserError, notifyUserWarning } = obj as any return typeof notifyUserError === 'function' && typeof notifyUserWarning === 'function' } /** Studio */ export interface IStudioContext extends ICommonContext { /** The id of the studio */ readonly studioId: string /** Returns the Studio blueprint config. If StudioBlueprintManifest.preprocessConfig is provided, a config preprocessed by that function is returned, otherwise it is returned unprocessed */ getStudioConfig: () => unknown /** Returns a reference to a studio config value, that can later be resolved in Core */ getStudioConfigRef(configKey: string): string /** Get the mappings for the studio */ getStudioMappings: () => Readonly<BlueprintMappings> getPackageInfo: (packageId: string) => Readonly<PackageInfo.Any[]> } export interface IStudioUserContext extends IUserNotesContext, IStudioContext {} /** Show Style Variant */ export interface IShowStyleContext extends ICommonContext, IStudioContext { /** Returns a ShowStyle blueprint config. If ShowStyleBlueprintManifest.preprocessConfig is provided, a config preprocessed by that function is returned, otherwise it is returned unprocessed */ getShowStyleConfig: () => unknown /** Returns a reference to a showStyle config value, that can later be resolved in Core */ getShowStyleConfigRef(configKey: string): string } export interface IShowStyleUserContext extends IUserNotesContext, IShowStyleContext {} /** Rundown */ export interface IRundownContext extends IShowStyleContext { readonly rundownId: string readonly rundown: Readonly<IBlueprintRundownDB> } export interface IRundownUserContext extends IUserNotesContext, IRundownContext {} export interface ISegmentUserContext extends IUserNotesContext, IRundownContext { /** Display a notification to the user of an error */ notifyUserError: (message: string, params?: { [key: string]: any }, partExternalId?: string) => void /** Display a notification to the user of an warning */ notifyUserWarning: (message: string, params?: { [key: string]: any }, partExternalId?: string) => void } /** Actions */ export interface IActionExecutionContext extends IShowStyleUserContext, IEventContext { /** Data fetching */ // getIngestRundown(): IngestRundown // TODO - for which part? /** Get a PartInstance which can be modified */ getPartInstance(part: 'current' | 'next'): IBlueprintPartInstance | undefined /** Get the PieceInstances for a modifiable PartInstance */ getPieceInstances(part: 'current' | 'next'): IBlueprintPieceInstance[] /** Get the resolved PieceInstances for a modifiable PartInstance */ getResolvedPieceInstances(part: 'current' | 'next'): IBlueprintResolvedPieceInstance[] /** Get the last active piece on given layer */ findLastPieceOnLayer( sourceLayerId: string | string[], options?: { excludeCurrentPart?: boolean originalOnly?: boolean pieceMetaDataFilter?: any // Mongo query against properties inside of piece.metaData } ): IBlueprintPieceInstance | undefined /** Get the previous scripted piece on a given layer, looking backwards from the current part. */ findLastScriptedPieceOnLayer( sourceLayerId: string | string[], options?: { excludeCurrentPart?: boolean pieceMetaDataFilter?: any } ): IBlueprintPiece | undefined /** Gets the PartInstance for a PieceInstance retrieved from findLastPieceOnLayer. This primarily allows for accessing metadata of the PartInstance */ getPartInstanceForPreviousPiece(piece: IBlueprintPieceInstance): IBlueprintPartInstance /** Gets the Part for a Piece retrieved from findLastScriptedPieceOnLayer. This primarily allows for accessing metadata of the Part */ getPartForPreviousPiece(piece: IBlueprintPieceDB): IBlueprintPart | undefined /** Fetch the showstyle config for the specified part */ // getNextShowStyleConfig(): Readonly<{ [key: string]: ConfigItemValue }> /** Creative actions */ /** Insert a pieceInstance. Returns id of new PieceInstance. Any timelineObjects will have their ids changed, so are not safe to reference from another piece */ insertPiece(part: 'current' | 'next', piece: IBlueprintPiece): IBlueprintPieceInstance /** Update a piecesInstance */ updatePieceInstance(pieceInstanceId: string, piece: Partial<IBlueprintPiece>): IBlueprintPieceInstance /** Insert a queued part to follow the current part */ queuePart(part: IBlueprintPart, pieces: IBlueprintPiece[]): IBlueprintPartInstance /** Update a partInstance */ updatePartInstance(part: 'current' | 'next', props: Partial<IBlueprintMutatablePart>): IBlueprintPartInstance /** Destructive actions */ /** Stop any piecesInstances on the specified sourceLayers. Returns ids of piecesInstances that were affected */ stopPiecesOnLayers(sourceLayerIds: string[], timeOffset?: number): string[] /** Stop piecesInstances by id. Returns ids of piecesInstances that were removed */ stopPieceInstances(pieceInstanceIds: string[], timeOffset?: number): string[] /** Remove piecesInstances by id. Returns ids of piecesInstances that were removed. Note: For now we only allow removing from the next, but this might change to include current if there is justification */ removePieceInstances(part: 'next', pieceInstanceIds: string[]): string[] /** Move the next part through the rundown. Can move by either a number of parts, or segments in either direction. */ moveNextPart(partDelta: number, segmentDelta: number): void /** Set flag to perform take after executing the current action. Returns state of the flag after each call. */ takeAfterExecuteAction(take: boolean): boolean /** Misc actions */ // updateAction(newManifest: Pick<IBlueprintAdLibActionManifest, 'description' | 'payload'>): void // only updates itself. to allow for the next one to do something different // executePeripheralDeviceAction(deviceId: string, functionName: string, args: any[]): Promise<any> // openUIDialogue(message: string) // ????? } /** Actions */ export interface ISyncIngestUpdateToPartInstanceContext extends IRundownUserContext { /** Sync a pieceInstance. Inserts the pieceInstance if new, updates if existing. Optionally pass in a mutated Piece, to change the content of the instance */ syncPieceInstance( pieceInstanceId: string, mutatedPiece?: Omit<IBlueprintPiece, 'lifespan'> ): IBlueprintPieceInstance /** Insert a pieceInstance. Returns id of new PieceInstance. Any timelineObjects will have their ids changed, so are not safe to reference from another piece */ insertPieceInstance(piece: IBlueprintPiece): IBlueprintPieceInstance /** Update a piecesInstance */ updatePieceInstance(pieceInstanceId: string, piece: Partial<IBlueprintPiece>): IBlueprintPieceInstance /** Remove a pieceInstance */ removePieceInstances(...pieceInstanceIds: string[]): string[] // Upcoming interface: // /** Insert a AdlibInstance. Returns id of new AdlibInstance. Any timelineObjects will have their ids changed, so are not safe to reference from another piece */ // insertAdlibInstance(adlibPiece: IBlueprintAdLibPiece): IBlueprintAdlibPieceInstance // /** Update a AdlibInstance */ // updateAdlibInstance(adlibInstanceId: string, adlibPiece: Partial<OmitId<IBlueprintAdLibPiece>>): IBlueprintAdlibPieceInstance // /** Remove a AdlibInstance */ // removeAdlibInstances(...adlibInstanceId: string[]): string[] // Upcoming interface: // /** Insert a ActionInstance. Returns id of new ActionInstance. Any timelineObjects will have their ids changed, so are not safe to reference from another piece */ // insertActionInstance(action: IBlueprintAdlibAction): IBlueprintAdlibActionInstance // /** Update a ActionInstance */ // updateActionInstance(actionInstanceId: string, action: Partial<OmitId<IBlueprintAdlibAction>>): IBlueprintAdlibActionInstance // /** Remove a ActionInstance */ // removeActionInstances(...actionInstanceIds: string[]): string[] /** Update a partInstance */ updatePartInstance(props: Partial<IBlueprintMutatablePart>): IBlueprintPartInstance } /** Events */ export interface IEventContext { getCurrentTime(): number } export interface ITimelineEventContext extends IEventContext, IRundownContext { readonly currentPartInstance: Readonly<IBlueprintPartInstance> | undefined readonly nextPartInstance: Readonly<IBlueprintPartInstance> | undefined /** * Get the full session id for an ab playback session. * Note: sessionName should be unique within the segment unless pieces want to share a session */ getPieceABSessionId(piece: IBlueprintPieceInstance, sessionName: string): string /** * Get the full session id for a timelineobject that belongs to an ab playback session * sessionName should also be used in calls to getPieceABSessionId for the owning piece */ getTimelineObjectAbSessionId(obj: OnGenerateTimelineObj, sessionName: string): string | undefined } export interface IPartEventContext extends IEventContext, IRundownContext { readonly part: Readonly<IBlueprintPartInstance> } export interface IRundownDataChangedEventContext extends IEventContext, IRundownContext { formatDateAsTimecode(time: number): string formatDurationAsTimecode(time: number): string /** Get all unsent and queued messages in the rundown */ getAllUnsentQueuedMessages(): Readonly<IBlueprintExternalMessageQueueObj[]> } export interface IRundownTimingEventContext extends IRundownDataChangedEventContext { readonly previousPart: Readonly<IBlueprintPartInstance> | undefined readonly currentPart: Readonly<IBlueprintPartInstance> readonly nextPart: Readonly<IBlueprintPartInstance> | undefined /** * Returns the first PartInstance in the Rundown within the current playlist activation. * This allows for a start time for the Rundown to be determined */ getFirstPartInstanceInRundown(): Readonly<IBlueprintPartInstance> /** * Returns the partInstances in the Segment, limited to the playthrough of the segment that refPartInstance is part of * @param refPartInstance PartInstance to use as the basis of the search */ getPartInstancesInSegmentPlayoutId( refPartInstance: Readonly<IBlueprintPartInstance> ): Readonly<IBlueprintPartInstance[]> /** * Returns pieces in a partInstance * @param id Id of partInstance to fetch items in */ getPieceInstances(...partInstanceIds: string[]): Readonly<IBlueprintPieceInstance[]> /** * Returns a segment * @param id Id of segment to fetch */ getSegment(id: string): Readonly<IBlueprintSegmentDB> | undefined }
the_stack
import type { Error } from '../types' import type { ProtocolData } from '../protocol/types' import type { Mount, Slot, Axis, Direction, SessionUpdate } from './types' export interface LegacyConnectAction { type: 'robot:LEGACY_CONNECT' payload: { name: string } meta: { robotCommand: true } } export interface ConnectAction { type: 'robot:CONNECT' payload: { name: string } meta: { robotCommand: true } } export interface ConnectResponseAction { type: 'robot:CONNECT_RESPONSE' payload: { error: Error | null | undefined sessionCapabilities: string[] } } export interface ReturnTipAction { type: 'robot:RETURN_TIP' payload: { mount: Mount } meta: { robotCommand: true } } export interface ReturnTipResponseAction { type: 'robot:RETURN_TIP_RESPONSE' error: boolean payload?: Error } export interface ClearConnectResponseAction { type: 'robot:CLEAR_CONNECT_RESPONSE' } export interface DisconnectAction { type: 'robot:DISCONNECT' meta: { robotCommand: true } } export interface DisconnectResponseAction { type: 'robot:DISCONNECT_RESPONSE' payload: {} } export interface UnexpectedDisconnectAction { type: 'robot:UNEXPECTED_DISCONNECT' } export interface ConfirmProbedAction { type: 'robot:CONFIRM_PROBED' payload: Mount meta: { robotCommand: true } } export interface PipetteCalibrationAction { type: 'robot:JOG' payload: { mount: Mount axis?: Axis direction?: Direction step?: number } meta: { robotCommand: true } } export interface SetJogDistanceAction { type: 'robot:SET_JOG_DISTANCE' payload: number } export interface LabwareCalibrationAction { type: | 'robot:MOVE_TO' | 'robot:PICKUP_AND_HOME' | 'robot:DROP_TIP_AND_HOME' | 'robot:CONFIRM_TIPRACK' | 'robot:UPDATE_OFFSET' | 'robot:SET_JOG_DISTANCE' payload: { mount: Mount slot: Slot } meta: { robotCommand: true } } export interface CalibrationSuccessAction { type: | 'robot:MOVE_TO_SUCCESS' | 'robot:JOG_SUCCESS' | 'robot:PICKUP_AND_HOME_SUCCESS' | 'robot:DROP_TIP_AND_HOME_SUCCESS' | 'robot:CONFIRM_TIPRACK_SUCCESS' | 'robot:UPDATE_OFFSET_SUCCESS' | 'robot:RETURN_TIP_SUCCESS' payload: { isTiprack?: boolean tipOn?: boolean } } export interface CalibrationFailureAction { type: | 'robot:MOVE_TO_FAILURE' | 'robot:JOG_FAILURE' | 'robot:PICKUP_AND_HOME_FAILURE' | 'robot:DROP_TIP_AND_HOME_FAILURE' | 'robot:CONFIRM_TIPRACK_FAILURE' | 'robot:UPDATE_OFFSET_FAILURE' | 'robot:RETURN_TIP_FAILURE' error: true payload: Error } export interface SessionResponseAction { type: 'robot:SESSION_RESPONSE' // TODO(mc, 2018-09-06): this payload is incomplete payload: { name: string protocolText: string metadata?: ProtocolData['metadata'] | null | undefined apiLevel: [number, number] [key: string]: unknown } meta: { freshUpload: boolean } } export interface SessionErrorAction { type: 'robot:SESSION_ERROR' payload: { error: Error } meta: { freshUpload: boolean } } export interface SessionUpdateAction { type: 'robot:SESSION_UPDATE' payload: SessionUpdate meta: { now: number } } export interface RefreshSessionAction { type: 'robot:REFRESH_SESSION' meta: { robotCommand: true } } export type CalibrationResponseAction = | CalibrationSuccessAction | CalibrationFailureAction export interface SetModulesReviewedAction { type: 'robot:SET_MODULES_REVIEWED' payload: boolean } export interface ClearCalibrationRequestAction { type: 'robot:CLEAR_CALIBRATION_REQUEST' } export interface SetDeckPopulatedAction { type: 'robot:SET_DECK_POPULATED' payload: boolean } export interface MoveToFrontAction { type: 'robot:MOVE_TO_FRONT' payload: { mount: Mount } meta: { robotCommand: true } } export interface MoveToFrontResponseAction { type: 'robot:MOVE_TO_FRONT_RESPONSE' error: boolean payload?: Error } export interface ProbeTipAction { type: 'robot:PROBE_TIP' payload: { mount: Mount } meta: { robotCommand: true } } export interface ProbeTipResponseAction { type: 'robot:PROBE_TIP_RESPONSE' error: boolean payload?: Error } export interface ConfirmLabwareAction { type: 'robot:CONFIRM_LABWARE' payload: { labware: Slot } } export interface RunAction { type: 'robot:RUN' meta: { robotCommand: true } } export interface RunResponseAction { type: 'robot:RUN_RESPONSE' error: boolean payload?: Error } export interface PauseAction { type: 'robot:PAUSE' meta: { robotCommand: true } } export interface PauseResponseAction { type: 'robot:PAUSE_RESPONSE' error: boolean payload?: Error } export interface ResumeAction { type: 'robot:RESUME' meta: { robotCommand: true } } export interface ResumeResponseAction { type: 'robot:RESUME_RESPONSE' error: boolean payload?: Error } export interface CancelAction { type: 'robot:CANCEL' meta: { robotCommand: true } } export interface CancelResponseAction { type: 'robot:CANCEL_RESPONSE' error: boolean payload?: Error } // TODO(mc, 2018-01-23): refactor to use type above // DO NOT ADD NEW ACTIONS HERE export const actionTypes = { // calibration SET_DECK_POPULATED: 'robot:SET_DECK_POPULATED', // TODO(mc, 2018-01-10): rename MOVE_TO_FRONT to PREPARE_TO_PROBE? MOVE_TO_FRONT: 'robot:MOVE_TO_FRONT', MOVE_TO_FRONT_RESPONSE: 'robot:MOVE_TO_FRONT_RESPONSE', PROBE_TIP: 'robot:PROBE_TIP', PROBE_TIP_RESPONSE: 'robot:PROBE_TIP_RESPONSE', RETURN_TIP: 'robot:RETURN_TIP', RETURN_TIP_RESPONSE: 'robot:RETURN_TIP_RESPONSE', CONFIRM_LABWARE: 'robot:CONFIRM_LABWARE', // protocol run controls RUN: 'robot:RUN', RUN_RESPONSE: 'robot:RUN_RESPONSE', PAUSE: 'robot:PAUSE', PAUSE_RESPONSE: 'robot:PAUSE_RESPONSE', RESUME: 'robot:RESUME', RESUME_RESPONSE: 'robot:RESUME_RESPONSE', CANCEL: 'robot:CANCEL', CANCEL_RESPONSE: 'robot:CANCEL_RESPONSE', } as const export type Action = | LegacyConnectAction | ConnectAction | ConnectResponseAction | DisconnectAction | DisconnectResponseAction | ClearConnectResponseAction | UnexpectedDisconnectAction | ConfirmProbedAction | PipetteCalibrationAction | LabwareCalibrationAction | CalibrationResponseAction | CalibrationFailureAction | ReturnTipAction | ReturnTipResponseAction | SetJogDistanceAction | SessionResponseAction | SessionErrorAction | SessionUpdateAction | RefreshSessionAction | SetModulesReviewedAction | ClearCalibrationRequestAction | SetDeckPopulatedAction | MoveToFrontAction | MoveToFrontResponseAction | ProbeTipAction | ProbeTipResponseAction | ConfirmLabwareAction | RunAction | RunResponseAction | PauseAction | PauseResponseAction | ResumeAction | ResumeResponseAction | CancelAction | CancelResponseAction export const actions = { // legacyConnect will construct an RPC client and update state legacyConnect(name: string): LegacyConnectAction { return { type: 'robot:LEGACY_CONNECT', payload: { name }, meta: { robotCommand: true }, } }, // connect will NOT construct an RPC client connect(name: string): ConnectAction { return { type: 'robot:CONNECT', payload: { name }, meta: { robotCommand: true }, } }, connectResponse( error: Error | null, sessionCapabilities: string[] = [] ): ConnectResponseAction { return { type: 'robot:CONNECT_RESPONSE', payload: { error, sessionCapabilities }, } }, clearConnectResponse(): ClearConnectResponseAction { return { type: 'robot:CLEAR_CONNECT_RESPONSE' } }, disconnect(): DisconnectAction { return { type: 'robot:DISCONNECT', meta: { robotCommand: true } } }, disconnectResponse(): DisconnectResponseAction { return { type: 'robot:DISCONNECT_RESPONSE', payload: {}, } }, unexpectedDisconnect(): UnexpectedDisconnectAction { return { type: 'robot:UNEXPECTED_DISCONNECT' } }, sessionResponse( error: Error | null | undefined, // TODO(mc, 2018-01-23): type Session (see reducers/session.js) session: any, freshUpload: boolean ): SessionResponseAction | SessionErrorAction { const meta = { freshUpload } if (error) { return { type: 'robot:SESSION_ERROR', payload: { error }, meta } } return { type: 'robot:SESSION_RESPONSE', payload: session, meta } }, sessionUpdate(update: SessionUpdate, now: number): SessionUpdateAction { return { type: 'robot:SESSION_UPDATE', payload: update, meta: { now }, } }, setModulesReviewed(payload: boolean): SetModulesReviewedAction { return { type: 'robot:SET_MODULES_REVIEWED', payload } }, setDeckPopulated(payload: boolean): SetDeckPopulatedAction { return { type: actionTypes.SET_DECK_POPULATED, payload } }, // pick up a tip with instrument on `mount` from tiprack in `slot` pickupAndHome(mount: Mount, slot: Slot): LabwareCalibrationAction { return { type: 'robot:PICKUP_AND_HOME', payload: { mount, slot }, meta: { robotCommand: true }, } }, // response for pickup and home pickupAndHomeResponse( error: Error | null | undefined = null ): CalibrationResponseAction { if (error) { return { type: 'robot:PICKUP_AND_HOME_FAILURE', error: true, payload: error, } } return { type: 'robot:PICKUP_AND_HOME_SUCCESS', payload: {}, } }, // drop the tip on pipette on `mount` into the tiprack in `slot` dropTipAndHome(mount: Mount, slot: Slot): LabwareCalibrationAction { return { type: 'robot:DROP_TIP_AND_HOME', payload: { mount, slot }, meta: { robotCommand: true }, } }, // response for drop tip and home dropTipAndHomeResponse( error: Error | null | undefined = null ): CalibrationResponseAction { if (error) { return { type: 'robot:DROP_TIP_AND_HOME_FAILURE', error: true, payload: error, } } return { type: 'robot:DROP_TIP_AND_HOME_SUCCESS', payload: {}, } }, // set tiprack to calibrated and conditionally drop the tip confirmTiprack(mount: Mount, slot: Slot): LabwareCalibrationAction { return { type: 'robot:CONFIRM_TIPRACK', payload: { mount, slot }, meta: { robotCommand: true }, } }, // response for pickup and home // payload.tipOn is a flag for whether a tip remains on the pipette confirmTiprackResponse( error: Error | null | undefined = null, tipOn: boolean = false ): CalibrationResponseAction { if (error) { return { type: 'robot:CONFIRM_TIPRACK_FAILURE', error: true, payload: error, } } return { type: 'robot:CONFIRM_TIPRACK_SUCCESS', payload: { tipOn }, } }, moveToFront(mount: Mount): MoveToFrontAction { return { type: actionTypes.MOVE_TO_FRONT, payload: { mount }, meta: { robotCommand: true }, } }, moveToFrontResponse( error: Error | null | undefined = null ): MoveToFrontResponseAction { const action: MoveToFrontResponseAction = { type: actionTypes.MOVE_TO_FRONT_RESPONSE, error: error != null, } if (error) action.payload = error return action }, probeTip(mount: Mount): ProbeTipAction { return { type: actionTypes.PROBE_TIP, payload: { mount }, meta: { robotCommand: true }, } }, probeTipResponse( error: Error | null | undefined = null ): ProbeTipResponseAction { const action: ProbeTipResponseAction = { type: actionTypes.PROBE_TIP_RESPONSE, error: error != null, } if (error) action.payload = error return action }, // confirm tip removed + tip probed then home pipette on `mount` confirmProbed(mount: Mount): ConfirmProbedAction { return { type: 'robot:CONFIRM_PROBED', payload: mount, meta: { robotCommand: true }, } }, returnTip(mount: Mount): ReturnTipAction { return { type: actionTypes.RETURN_TIP, payload: { mount }, meta: { robotCommand: true }, } }, returnTipResponse( error: Error | null | undefined = null ): ReturnTipResponseAction { const action: ReturnTipResponseAction = { type: actionTypes.RETURN_TIP_RESPONSE, error: error != null, } if (error) action.payload = error return action }, moveTo(mount: Mount, slot: Slot): LabwareCalibrationAction { return { type: 'robot:MOVE_TO', payload: { mount, slot }, meta: { robotCommand: true }, } }, moveToResponse( error: Error | null | undefined = null ): CalibrationResponseAction { if (error) { return { type: 'robot:MOVE_TO_FAILURE', error: true, payload: error, } } return { type: 'robot:MOVE_TO_SUCCESS', payload: {} } }, setJogDistance(step: number): SetJogDistanceAction { return { type: 'robot:SET_JOG_DISTANCE', payload: step } }, jog( mount: Mount, axis: Axis, direction: Direction, step: number ): PipetteCalibrationAction { return { type: 'robot:JOG', payload: { mount, axis, direction, step }, meta: { robotCommand: true }, } }, jogResponse( error: Error | null | undefined = null ): CalibrationResponseAction { if (error) { return { type: 'robot:JOG_FAILURE', error: true, payload: error, } } return { type: 'robot:JOG_SUCCESS', payload: {} } }, // update the offset of labware in slot using position of pipette on mount updateOffset(mount: Mount, slot: Slot): LabwareCalibrationAction { return { type: 'robot:UPDATE_OFFSET', payload: { mount, slot }, meta: { robotCommand: true }, } }, // response for updateOffset updateOffsetResponse( error: Error | null | undefined = null ): CalibrationResponseAction { if (error) { return { type: 'robot:UPDATE_OFFSET_FAILURE', error: true, payload: error, } } return { type: 'robot:UPDATE_OFFSET_SUCCESS', payload: {}, } }, confirmLabware(labware: Slot): ConfirmLabwareAction { return { type: actionTypes.CONFIRM_LABWARE, payload: { labware } } }, run(): RunAction { return { type: actionTypes.RUN, meta: { robotCommand: true } } }, runResponse(error: Error | null | undefined = null): RunResponseAction { const action: RunResponseAction = { type: actionTypes.RUN_RESPONSE, error: error != null, } if (error) action.payload = error return action }, pause(): PauseAction { return { type: actionTypes.PAUSE, meta: { robotCommand: true } } }, pauseResponse(error: Error | null | undefined = null): PauseResponseAction { const action: PauseResponseAction = { type: actionTypes.PAUSE_RESPONSE, error: error != null, } if (error) action.payload = error return action }, resume(): ResumeAction { return { type: actionTypes.RESUME, meta: { robotCommand: true } } }, resumeResponse(error: Error | null | undefined = null): ResumeResponseAction { const action: ResumeResponseAction = { type: actionTypes.RESUME_RESPONSE, error: error != null, } if (error) action.payload = error return action }, cancel(): CancelAction { return { type: actionTypes.CANCEL, meta: { robotCommand: true } } }, cancelResponse(error: Error | null | undefined = null): CancelResponseAction { const action: CancelResponseAction = { type: actionTypes.CANCEL_RESPONSE, error: error != null, } if (error) action.payload = error return action }, refreshSession(): RefreshSessionAction { return { type: 'robot:REFRESH_SESSION', meta: { robotCommand: true } } }, clearCalibrationRequest(): ClearCalibrationRequestAction { return { type: 'robot:CLEAR_CALIBRATION_REQUEST' } }, }
the_stack
import React from 'react' import MultiPicker from '../../picker/MultiPicker' import Picker from '../../picker/Picker' import DatePickerProps from './DatePickerProps' import defaultLocale from './locale/en_US' function getDaysInMonth(date: any) { return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate() } function pad(n: any) { return n < 10 ? `0${n}` : n + '' } function cloneDate(date: any) { return new Date(+date) } function setMonth(date: Date, month: number) { date.setDate( Math.min( date.getDate(), getDaysInMonth(new Date(date.getFullYear(), month)), ), ) date.setMonth(month) } const DATETIME = 'datetime' const DATE = 'date' const TIME = 'time' const MONTH = 'month' const YEAR = 'year' const ONE_DAY = 24 * 60 * 60 * 1000 class DatePicker extends React.Component<DatePickerProps, any> { static defaultProps = { prefixCls: 'rmc-date-picker', pickerPrefixCls: 'rmc-picker', locale: defaultLocale, mode: DATE, disabled: false, minuteStep: 1, onDateChange() {}, use12Hours: false, } state = { date: this.props.date || this.props.defaultDate, } defaultMinDate: any defaultMaxDate: any UNSAFE_componentWillReceiveProps(nextProps: { date: any; defaultDate: any }) { if ('date' in nextProps) { this.setState({ date: nextProps.date || nextProps.defaultDate, }) } } getNewDate = (values: any, index: any) => { const value = parseInt(values[index], 10) const props = this.props const { mode } = props const newValue = cloneDate(this.getDate()) if (mode === DATETIME || mode === DATE || mode === YEAR || mode === MONTH) { switch (index) { case 0: newValue.setFullYear(value) break case 1: // Note: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth // e.g. from 2017-03-31 to 2017-02-28 setMonth(newValue, value) break case 2: newValue.setDate(value) break case 3: this.setHours(newValue, value) break case 4: newValue.setMinutes(value) break case 5: this.setAmPm(newValue, value) break default: break } } else if (mode === TIME) { switch (index) { case 0: this.setHours(newValue, value) break case 1: newValue.setMinutes(value) break case 2: this.setAmPm(newValue, value) break default: break } } return this.clipDate(newValue) } onValueChange = (values: any, index: any) => { const props = this.props const newValue = this.getNewDate(values, index) if (!('date' in props)) { this.setState({ date: newValue, }) } if (props.onDateChange) { props.onDateChange(newValue) } if (props.onValueChange) { props.onValueChange(values, index) } } onScrollChange = (values: any, index: any) => { const props = this.props if (props.onScrollChange) { const newValue = this.getNewDate(values, index) props.onScrollChange(newValue, values, index) } } setHours(date: Date, hour: number) { if (this.props.use12Hours) { const dh = date.getHours() let nhour = hour nhour = dh >= 12 ? hour + 12 : hour nhour = nhour >= 24 ? 0 : nhour // Make sure no more than one day date.setHours(nhour) } else { date.setHours(hour) } } setAmPm(date: any, index: any) { if (index === 0) { date.setTime(+date - ONE_DAY / 2) } else { date.setTime(+date + ONE_DAY / 2) } } getDefaultMinDate() { if (!this.defaultMinDate) { this.defaultMinDate = new Date(2000, 0, 1, 0, 0, 0) } return this.defaultMinDate } getDefaultMaxDate() { if (!this.defaultMaxDate) { this.defaultMaxDate = new Date(2030, 0, 1, 23, 59, 59) } return this.defaultMaxDate } getDate() { return this.clipDate( this.state.date || this.props.defaultDate || this.getDefaultMinDate(), ) } // used by rmc-picker/lib/PopupMixin.js getValue() { return this.getDate() } getMinYear() { return this.getMinDate().getFullYear() } getMaxYear() { return this.getMaxDate().getFullYear() } getMinMonth() { return this.getMinDate().getMonth() } getMaxMonth() { return this.getMaxDate().getMonth() } getMinDay() { return this.getMinDate().getDate() } getMaxDay() { return this.getMaxDate().getDate() } getMinHour() { return this.getMinDate().getHours() } getMaxHour() { return this.getMaxDate().getHours() } getMinMinute() { return this.getMinDate().getMinutes() } getMaxMinute() { return this.getMaxDate().getMinutes() } getMinDate() { return this.props.minDate || this.getDefaultMinDate() } getMaxDate() { return this.props.maxDate || this.getDefaultMaxDate() } getDateData() { const { locale, formatMonth, formatDay, mode } = this.props const date = this.getDate() const selYear = date.getFullYear() const selMonth = date.getMonth() const minDateYear = this.getMinYear() const maxDateYear = this.getMaxYear() const minDateMonth = this.getMinMonth() const maxDateMonth = this.getMaxMonth() const minDateDay = this.getMinDay() const maxDateDay = this.getMaxDay() const years: any[] = [] for (let i = minDateYear; i <= maxDateYear; i++) { years.push({ value: i + '', label: i + locale.year + '', }) } const yearCol = { key: 'year', props: { children: years } } if (mode === YEAR) { return [yearCol] } const months: any[] = [] let minMonth = 0 let maxMonth = 11 if (minDateYear === selYear) { minMonth = minDateMonth } if (maxDateYear === selYear) { maxMonth = maxDateMonth } for (let i = minMonth; i <= maxMonth; i++) { const label = formatMonth ? formatMonth(i, date) : i + 1 + locale.month + '' months.push({ value: i + '', label, }) } const monthCol = { key: 'month', props: { children: months } } if (mode === MONTH) { return [yearCol, monthCol] } const days: any[] = [] let minDay = 1 let maxDay = getDaysInMonth(date) if (minDateYear === selYear && minDateMonth === selMonth) { minDay = minDateDay } if (maxDateYear === selYear && maxDateMonth === selMonth) { maxDay = maxDateDay } for (let i = minDay; i <= maxDay; i++) { const label = formatDay ? formatDay(i, date) : i + locale.day + '' days.push({ value: i + '', label, }) } return [yearCol, monthCol, { key: 'day', props: { children: days } }] } getDisplayHour(rawHour: number) { // 12 hour am (midnight 00:00) -> 12 hour pm (noon 12:00) -> 12 hour am (midnight 00:00) if (this.props.use12Hours) { if (rawHour === 0) { rawHour = 12 } if (rawHour > 12) { rawHour -= 12 } return rawHour } return rawHour } getTimeData(date: any) { let minHour = 0 let maxHour = 23 let minMinute = 0 let maxMinute = 59 const { mode, locale, minuteStep, use12Hours } = this.props const minDateMinute = this.getMinMinute() const maxDateMinute = this.getMaxMinute() const minDateHour = this.getMinHour() const maxDateHour = this.getMaxHour() const hour = date.getHours() if (mode === DATETIME) { const year = date.getFullYear() const month = date.getMonth() const day = date.getDate() const minDateYear = this.getMinYear() const maxDateYear = this.getMaxYear() const minDateMonth = this.getMinMonth() const maxDateMonth = this.getMaxMonth() const minDateDay = this.getMinDay() const maxDateDay = this.getMaxDay() if ( minDateYear === year && minDateMonth === month && minDateDay === day ) { minHour = minDateHour if (minDateHour === hour) { minMinute = minDateMinute } } if ( maxDateYear === year && maxDateMonth === month && maxDateDay === day ) { maxHour = maxDateHour if (maxDateHour === hour) { maxMinute = maxDateMinute } } } else { minHour = minDateHour if (minDateHour === hour) { minMinute = minDateMinute } maxHour = maxDateHour if (maxDateHour === hour) { maxMinute = maxDateMinute } } const hours: any[] = [] if ((minHour === 0 && maxHour === 0) || (minHour !== 0 && maxHour !== 0)) { minHour = this.getDisplayHour(minHour) } else if (minHour === 0 && use12Hours) { minHour = 1 hours.push({ value: '0', label: locale.hour ? '12' + locale.hour : '12', }) } maxHour = this.getDisplayHour(maxHour) for (let i = minHour; i <= maxHour; i++) { hours.push({ value: i + '', label: locale.hour ? i + locale.hour + '' : pad(i), }) } const minutes: any[] = [] const selMinute = date.getMinutes() for (let i = minMinute; i <= maxMinute; i += minuteStep!) { minutes.push({ value: i + '', label: locale.minute ? i + locale.minute + '' : pad(i), }) if (selMinute > i && selMinute < i + minuteStep!) { minutes.push({ value: selMinute + '', label: locale.minute ? selMinute + locale.minute + '' : pad(selMinute), }) } } const cols = [ { key: 'hours', props: { children: hours } }, { key: 'minutes', props: { children: minutes } }, ].concat( use12Hours ? [ { key: 'ampm', props: { children: [ { value: '0', label: locale.am }, { value: '1', label: locale.pm }, ], }, }, ] : [], ) return { cols, selMinute } } clipDate(date: any) { const { mode } = this.props const minDate = this.getMinDate() const maxDate = this.getMaxDate() if (mode === DATETIME) { if (date < minDate) { return cloneDate(minDate) } if (date > maxDate) { return cloneDate(maxDate) } } else if (mode === DATE || mode === YEAR || mode === MONTH) { // compare-two-dates: https://stackoverflow.com/a/14629978/2190503 if (+date + ONE_DAY <= minDate) { return cloneDate(minDate) } if (date >= +maxDate + ONE_DAY) { return cloneDate(maxDate) } } else if (mode === TIME) { const maxHour = maxDate.getHours() const maxMinutes = maxDate.getMinutes() const minHour = minDate.getHours() const minMinutes = minDate.getMinutes() const hour = date.getHours() const minutes = date.getMinutes() if (hour < minHour || (hour === minHour && minutes < minMinutes)) { return cloneDate(minDate) } if (hour > maxHour || (hour === maxHour && minutes > maxMinutes)) { return cloneDate(maxDate) } } return date } getValueCols() { const { mode, use12Hours } = this.props const date = this.getDate() let cols: any[] = [] let value: any[] = [] if (mode === YEAR) { return { cols: this.getDateData(), value: [date.getFullYear() + ''], } } if (mode === MONTH) { return { cols: this.getDateData(), value: [date.getFullYear() + '', date.getMonth() + ''], } } if (mode === DATETIME || mode === DATE) { cols = this.getDateData() value = [ date.getFullYear() + '', date.getMonth() + '', date.getDate() + '', ] } if (mode === DATETIME || mode === TIME) { const time = this.getTimeData(date) cols = cols.concat(time.cols) const hour = date.getHours() let dtValue = [hour + '', time.selMinute + ''] let nhour = hour if (use12Hours) { nhour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour dtValue = [nhour + '', time.selMinute + '', (hour >= 12 ? 1 : 0) + ''] } value = value.concat(dtValue) } return { value, cols, } } render() { const { value, cols } = this.getValueCols() const { disabled, rootNativeProps, style, itemStyle } = this.props return ( <MultiPicker style={[{ flexDirection: 'row', alignItems: 'center' }, style]} rootNativeProps={rootNativeProps} selectedValue={value} onValueChange={this.onValueChange} onScrollChange={this.onScrollChange}> {cols.map((p) => ( <Picker style={{ flex: 1 }} key={p.key} disabled={disabled} itemStyle={itemStyle}> {p.props.children.map((item: any) => { return ( <Picker.Item key={item.value} value={item.value}> {item.label} </Picker.Item> ) })} </Picker> ))} </MultiPicker> ) } } export default DatePicker
the_stack
import { resolve } from 'path' // a import fetch = require('node-fetch') import express = require('express') import multer = require('multer') import path = require('path') import fs = require('fs') import mkdirp = require('mkdirp') import * as BlinkDiff from 'blink-diff' import { Role } from '../packages/shared/comms/v1/proto/broker' import titere = require('titere') import WebSocket = require('ws') import http = require('http') import proto = require('../packages/shared/comms/v1/proto/broker') const url = require('url') // defines if we should run headless tests and exit (true) or keep the server on (false) const singleRun = !(process.env.SINGLE_RUN === 'true') // defines if we should replace the base images const shouldGenerateNewImages = process.env.GENERATE_NEW_IMAGES === 'true' const port = process.env.PORT || 8080 const resultsDir = path.resolve(__dirname, '../test/results') const tmpDir = path.resolve(__dirname, '../test/tmp') const diffDir = path.resolve(__dirname, '../test/diff') const storage = multer.diskStorage({ destination: function(req, file, cb) { const destination = path.resolve(tmpDir, file.fieldname) cb(null, destination) }, filename: function(req, file, cb) { cb(null, file.originalname) } }) const upload = multer({ storage }) const app = express() const server = http.createServer(app) const wss = new WebSocket.Server({ server }) const connections = new Set<WebSocket>() const topicsPerConnection = new WeakMap<WebSocket, Set<string>>() const aliasToUserId = new Map<number, string>() let connectionCounter = 0 function getTopicList(socket: WebSocket): Set<string> { let set = topicsPerConnection.get(socket) if (!set) { set = new Set() topicsPerConnection.set(socket, set) } return set } wss.on('connection', function connection(ws, req) { connections.add(ws) const alias = ++connectionCounter const query = url.parse(req.url, true).query const userId = query['identity'] aliasToUserId.set(alias, userId) ws.on('message', message => { const data = message as Buffer const msgType = proto.CoordinatorMessage.deserializeBinary(data).getType() if (msgType === proto.MessageType.PING) { ws.send(data) } else if (msgType === proto.MessageType.TOPIC) { const topicMessage = proto.TopicMessage.deserializeBinary(data) const topic = topicMessage.getTopic() const topicFwMessage = new proto.TopicFWMessage() topicFwMessage.setType(proto.MessageType.TOPIC_FW) topicFwMessage.setFromAlias(alias) topicFwMessage.setBody(topicMessage.getBody_asU8()) const topicData = topicFwMessage.serializeBinary() // Reliable/unreliable data connections.forEach($ => { if (ws !== $) { if (getTopicList($).has(topic)) { $.send(topicData) } } }) } else if (msgType === proto.MessageType.TOPIC_IDENTITY) { const topicMessage = proto.TopicIdentityMessage.deserializeBinary(data) const topic = topicMessage.getTopic() const topicFwMessage = new proto.TopicIdentityFWMessage() topicFwMessage.setType(proto.MessageType.TOPIC_IDENTITY_FW) topicFwMessage.setFromAlias(alias) topicFwMessage.setIdentity(aliasToUserId.get(alias)) topicFwMessage.setRole(Role.CLIENT) topicFwMessage.setBody(topicMessage.getBody_asU8()) const topicData = topicFwMessage.serializeBinary() // Reliable/unreliable data connections.forEach($ => { if (ws !== $) { if (getTopicList($).has(topic)) { $.send(topicData) } } }) } else if (msgType === proto.MessageType.SUBSCRIPTION) { const topicMessage = proto.SubscriptionMessage.deserializeBinary(data) const rawTopics = topicMessage.getTopics() const topics = Buffer.from(rawTopics).toString('utf8') const set = getTopicList(ws) set.clear() topics.split(/\s+/g).forEach($ => set.add($)) } }) ws.on('close', () => { connections.delete(ws) aliasToUserId.delete(alias) }) setTimeout(() => { const welcome = new proto.WelcomeMessage() welcome.setType(proto.MessageType.WELCOME) welcome.setAlias(alias) const data = welcome.serializeBinary() ws.send(data) }, 100) }) function getFile(files: any): Express.Multer.File { return files[Object.keys(files)[0]] } function checkDiff(imageAPath: string, imageBPath: string, threshold: number, diffOutputPath: string): Promise<number> { return new Promise((resolve, reject) => { mkdirp.sync(diffDir) const diff = new BlinkDiff({ imageAPath, imageBPath, thresholdType: BlinkDiff.THRESHOLD_PERCENT, threshold, imageOutputLimit: BlinkDiff.OUTPUT_DIFFERENT, imageOutputPath: diffOutputPath }) diff.run(function(error, result) { if (error) { reject(error) } else { if (diff.hasPassed(result.code)) { resolve(result.differences) } else { reject(new Error(`Found ${result.differences} differences`)) } } }) }) } /// --- SIDE EFFECTS --- { mkdirp.sync('test/tmp') app.use(require('cors')()) app.get('/test', (req, res) => { res.writeHead(200, 'OK', { 'Content-Type': 'text/html' }) res.write(`<!DOCTYPE html> <html> <head> <title>Mocha Tests</title> <meta charset="utf-8"> <link rel="stylesheet" href="/node_modules/mocha/mocha.css"> </head> <body> <div id="mocha"></div> <script>console.log('test html loaded')</script> <script src="/node_modules/mocha/mocha.js"></script> <script>mocha.setup('bdd');</script> <script src="/test/out/index.js"></script> </body> </html> `) res.end() }) app.use( '/@/artifacts/preview.js', express.static(resolve(__dirname, '../static/dist/preview.js'), { setHeaders: res => { res.setHeader('Content-Type', 'application/javascript') } }) ) app.use('/@', express.static(resolve(__dirname, '../packages/decentraland-ecs'))) app.use( '/preview.html', express.static(resolve(__dirname, '../static/preview.html'), { setHeaders: res => { res.setHeader('Content-Type', 'text/html') } }) ) function getAllParcelIdsBetween(coords: { pointer: string[] }) { return Array.isArray(coords.pointer) ? coords.pointer : [coords.pointer] // if a single value is given, we should wrap it in an array } function readAllJsonFiles(filenames: string[]) { return Promise.all( filenames.map(value => { return new Promise((res, reject) => { return fs.readFile(value, (err, data) => { if (err) { return res(null) } return res(JSON.parse(data.toString())) }) }) }) ) } const sceneEndpoint = async (req, res) => { const coords = getAllParcelIdsBetween(req.query) const fileData = await readAllJsonFiles( coords.map(coord => resolve(__dirname, path.join('..', 'public', 'local-ipfs', 'scene_mapping', coord))) ) const length = coords.length const parcelData = [] for (let i = 0; i < length; i++) { if (!fileData[i]) continue parcelData.push(fileData[i]) } const cids = parcelData.map(p => p.root_cid) const sceneData: any[] = await readAllJsonFiles( cids.map(_ => resolve(__dirname, path.join('..', 'public', 'local-ipfs', 'parcel_info', _))) ) const result = await Promise.all( sceneData.map(async data => { const sceneJsonHash = data.contents.filter($ => $.file === 'scene.json')[0].hash const download: any[] = await readAllJsonFiles([ resolve(__dirname, path.join('..', 'public', 'local-ipfs', 'contents', sceneJsonHash)) ]) const metadata = download[0] return { id: data.root_cid, type: 'scene', timestamp: Date.now(), pointers: metadata.scene.parcels, content: data.contents, metadata } }) ) const response = res.json(result) return response } app.use('/scenes', sceneEndpoint) app.use('/local-ipfs/scenes', sceneEndpoint) app.use('/local-ipfs/content/entities/scene', sceneEndpoint) const parcelInfoEndpoint = async (req, res) => { const cids = req.query.cids.split(',') as string[] const fileData = await readAllJsonFiles( cids.map(_ => resolve(__dirname, path.join('..', 'public', 'local-ipfs', 'parcel_info', _))) ) return res.json({ data: fileData .filter($ => !!$) .map(($: any) => ({ root_cid: $.root_cid, publisher: $.publisher, content: $ })) }) } app.use('/local-ipfs/parcel_info', parcelInfoEndpoint) app.use('/parcel_info', parcelInfoEndpoint) app.use('/test', express.static(resolve(__dirname, '../test'))) app.use('/node_modules', express.static(resolve(__dirname, '../node_modules'))) app.use('/test-scenes', express.static(path.resolve(__dirname, '../public/test-scenes'))) app.use('/ecs-scenes', express.static(path.resolve(__dirname, '../public/ecs-scenes'))) app.use('/local-ipfs', express.static(path.resolve(__dirname, '../public/local-ipfs'))) app.use(express.static(path.resolve(__dirname, '..', 'static'))) app.post('/upload', upload.any(), function(req, res) { const threshold = 0.01 const file = getFile(req.files) const tmpPath = path.resolve(file.destination, file.filename) const resultPath = path.resolve(resultsDir, req.query.path) const outputDiffFile = path.resolve(diffDir, req.query.path) mkdirp.sync(path.dirname(tmpPath)) mkdirp.sync(path.dirname(resultPath)) console.log(` uploading to: ${tmpPath}`) console.log(` target file: ${resultPath}`) console.log(` output diff: ${outputDiffFile}`) // if the file to compare does not exist and we are uploading a new file if ((shouldGenerateNewImages && fs.existsSync(tmpPath)) || !fs.existsSync(resultPath)) { // move it to the final path fs.renameSync(tmpPath, resultPath) res.writeHead(201) res.end() return } // make sure the directory where we store the differences exists mkdirp.sync(path.dirname(outputDiffFile)) const promise = checkDiff(resultPath, tmpPath, threshold, outputDiffFile) promise .then($ => { console.log(` differences: ${$}`) res.writeHead(200) res.end() }) .catch(e => { console.log(` generating img: ${shouldGenerateNewImages} `) console.log(` error: ${e} `) if (shouldGenerateNewImages) { // If the diff fails, it means images are different enough to be // commited as a test result to the repo. if (fs.existsSync(tmpPath)) { fs.renameSync(tmpPath, resultPath) console.log(` mv: ${tmpPath} -> ${resultPath}`) } res.writeHead(201) res.end() } else { res.writeHead(500, e.message) res.end() } }) }) server.listen(port, function() { console.info('==> Listening on port %s. Open up http://localhost:%s/test to run tests', port, port) console.info(' Open up http://localhost:%s/ to test the client.', port) const options: titere.Options = { file: `http://localhost:${port}/test`, visible: true, height: 600, width: 800, timeout: 5 * 60 * 1000, args: ['--no-sandbox', '--disable-setuid-sandbox', '--debug-devtools-frontend', '--js-flags="--expose-gc"'] } if (!singleRun) { titere .run(options) .then(result => { if (result.coverage) { fs.writeFileSync('test/tmp/out.json', JSON.stringify(result.coverage)) } process.exit(result.result.stats.failures) }) .catch((err: Error) => { console.error(err.message || JSON.stringify(err)) console.dir(err) process.exit(1) }) } }) }
the_stack
import { promisify } from 'bluebird'; import * as jscodeshift from 'jscodeshift'; import { ASTNode, ASTPath } from 'jscodeshift'; import { Collection } from 'jscodeshift/src/Collection'; import * as minimist from 'minimist'; import { fs } from 'mz'; import * as protobuf from 'protobufjs'; import { pbjs, pbts } from 'protobufjs/cli'; import * as tmp from 'tmp'; const pbjsMain = promisify(pbjs.main); const pbtsMain = promisify(pbts.main); const createTempDir = promisify((callback: (error: any, result: tmp.SynchrounousResult) => any) => { tmp.dir({ unsafeCleanup: true }, (error, name, removeCallback) => { callback(error, { name, removeCallback, fd: -1 }); }); }); type NamedReference = { reference: string; name: string; }; type Services = NamedReference[]; export function bootstrap() { main(process.argv.slice(2)) .then(code => process.exit(code)) .catch(error => { console.error(error); process.exit(1); }); } export async function main(args: string[]) { const { _: protoFiles, out } = minimist(args, { alias: { out: 'o', }, string: ['out'], }); if (protoFiles.length === 0) { printUsage(); return 1; } const ts = await buildTypeScript(protoFiles); if (out) { await fs.writeFile(out, ts); } else { process.stdout.write(ts); } return 0; } export async function buildTypeScript(protoFiles: string[]) { const tempDir = await createTempDir(); try { // Use pbjs to generate static JS code for the protobuf definitions const jsFile = await call(tempDir.name, pbjsMain, protoFiles, 'js', ['keep-case'], { target: 'static-module', wrap: 'commonjs', }); const jsonDescriptor = await call(tempDir.name, pbjsMain, protoFiles, 'js', ['keep-case'], { target: 'json', }); const root = protobuf.loadSync(jsonDescriptor); const js = transformJavaScriptSource(await fs.readFile(jsFile, 'utf8'), root); await fs.writeFile(jsFile, js); // Create TypeScript file const tsFile = await call(tempDir.name, pbtsMain, [jsFile], 'ts'); return transformTypeScriptSource(await fs.readFile(tsFile, 'utf8')); } finally { tempDir.removeCallback(); } } export async function buildTypeScriptFromSources(protoSources: string[]) { const tempDir = await createTempDir(); try { const protoFiles = []; for (const source of protoSources) { const file = `${tempDir.name}/${Math.random()}.proto`; await fs.writeFile(file, source); protoFiles.push(file); } return await buildTypeScript(protoFiles); } finally { tempDir.removeCallback(); } } function printUsage() { console.log('Usage: rxjs-grpc -o [output] file.proto'); console.log(''); console.log('Options:'); console.log(' -o, --out Saves to a file instead of writing to stdout'); console.log(''); } function transformJavaScriptSource(source: string, root: protobuf.Root) { const ast: Collection<jscodeshift.File> = jscodeshift(source); // Change constructors to interfaces and remove their parameters constructorsToInterfaces(ast); // Clean method signatures cleanMethodSignatures(ast); // Remove message members (we use declared interfaces) removeMembers(ast, root); // Add the ClientFactory and ServerBuilder interfaces getNamespaceDeclarations(ast) .closestScope() .forEach(path => addFactoryAndBuild(jscodeshift(path.node))); // Render AST return ast.toSource(); } function transformTypeScriptSource(source: string) { // Remove imports source = source.replace(/^import.*?$\n?/gm, ''); // Add our imports source = `import { Observable } from 'rxjs';\n${source}`; source = `import * as grpc from 'grpc';\n${source}`; if (source.includes('$protobuf')) { source = `import * as $protobuf from 'protobufjs';\n${source}`; } // Fix generic type syntax source = source.replace(/Observable\.</g, 'Observable<'); // Remove public keyword from the field, because they are not allowed in interface source = source.replace(/^(\s+)public\s+/gm, '$1'); // Export interfaces, enums and namespaces source = source.replace(/^(\s+)(interface|enum|namespace)(\s+)/gm, '$1export $2$3'); return source; } function addFactoryAndBuild(ast: Collection<ASTNode>) { const services = collectServices(ast); const declaration = getNamespaceDeclarations(ast).filter((path, index) => index === 0); const namespace = getNamepaceName(declaration); const ownServices = services .filter(service => service.reference.startsWith(namespace)) .filter(service => { const relative = service.reference.substring(namespace.length + 1); return !relative.includes('.'); }); declaration.insertBefore(sourceToNodes(buildClientFactorySource(namespace, ownServices))); declaration.insertBefore(sourceToNodes(buildServerBuilderSource(namespace, ownServices))); } function collectServices(ast: Collection<ASTNode>) { const services: Services = []; ast .find(jscodeshift.FunctionDeclaration) .filter(path => !!path.node.comments) // only service constructors have more than 1 parameters .filter(path => path.node.params.length > 1) .forEach(path => { const reference = getReference(path); if (reference) { const name = path.node.id.name; services.push({ reference: reference + '.' + name, name }); } }); return services; } function getReference(commentedNodePath: ASTPath<jscodeshift.FunctionDeclaration>) { if (!commentedNodePath.node.comments) { return; } return commentedNodePath.node.comments .map(comment => /@memberof\s+([^\s]+)/.exec(comment.value)) .map(match => (match ? match[1] : undefined)) .filter(match => match)[0]; } function constructorsToInterfaces(ast: Collection<ASTNode>) { ast.find(jscodeshift.FunctionDeclaration).forEach(path => { if (!path.node.comments) { return; } const interfaceComments = path.node.comments.filter(comment => /@interface/.test(comment.value), ); if (interfaceComments.length) { // Message type has an @interface declaration path.node.comments = interfaceComments; path.node.comments.forEach(comment => { comment.value = comment.value.replace(/^([\s\*]+@interface\s+)I/gm, '$1'); comment.value = comment.value.replace(/^([\s\*]+@property\s+\{.*?\.)I([^.]+\})/gm, '$1$2'); }); } else { // Otherwise this is a service path.node.comments.forEach(comment => { comment.value = comment.value.replace(/@constructor/g, '@interface'); comment.value = comment.value.replace(/^[\s\*]+@extends.*$/gm, ''); comment.value = comment.value.replace(/^[\s\*]+@param.*$/gm, ''); comment.value = comment.value.replace(/^[\s\*]+@returns.*$/gm, ''); }); } jscodeshift(path).replaceWith(path.node); }); } function cleanMethodSignatures(ast: Collection<ASTNode>) { ast.find(jscodeshift.ExpressionStatement).forEach(path => { if (!path.node.comments) { return; } if (path.node.expression.type === 'AssignmentExpression') { const left = jscodeshift(path.node.expression.left).toSource(); // do not remove enums if (path.node.comments.some(comment => /@enum/.test(comment.value))) { return; } // Remove static methods and converter methods, we export simple interfaces if (!/\.prototype\./.test(left) || /\.(toObject|toJSON)/.test(left)) { path.node.comments = []; } } path.node.comments.forEach(comment => { // Remove callback typedefs, as we use Observable instead of callbacks if (/@typedef\s+\w+Callback/.test(comment.value)) { comment.value = ''; } if (/@param\s+\{.*?Callback\}\s+callback/.test(comment.value)) { comment.value = ''; } }); // Remove empty comments path.node.comments = path.node.comments.filter(comment => comment.value); jscodeshift(path).replaceWith(path.node); }); // The promise variant of service methods are after the method declerations, // so the last method will have its comment followed by a return statement. ast.find(jscodeshift.ExpressionStatement).forEach(fixPromiseMethodSignature); ast.find(jscodeshift.ReturnStatement).forEach(fixPromiseMethodSignature); function fixPromiseMethodSignature( path: ASTPath<jscodeshift.ExpressionStatement | jscodeshift.ReturnStatement>, ) { if (!path.node.comments) { return; } let changed = false; path.node.comments.forEach(comment => { const returnsPromiseRe = /(@returns\s+\{)Promise(<)/g; if (returnsPromiseRe.test(comment.value)) { changed = true; comment.value = comment.value.replace(returnsPromiseRe, '$1Observable$2'); comment.value = comment.value.replace(/(@param\s+\{.*?\.)I([^.]+\})/g, '$1$2'); // Add optional metadata parameter comment.value = comment.value.replace( /^([\s\*]+@param\s+)(\{.*)$/gm, '$1$2\n$1{grpc.Metadata=} metadata Optional metadata', ); } }); if (changed) { path.node.comments = path.node.comments.filter(comment => comment.value); jscodeshift(path).replaceWith(path.node); } } } function removeMembers(ast: Collection<ASTNode>, root: protobuf.Root) { ast.find(jscodeshift.ExpressionStatement).forEach(path => { if (!path.node.comments) { return; } path.node.comments.forEach(comment => { // Remove members of classes, as we use interfaces. But keep the oneofs, // as they are not part of the interfaces. if (/@member /.test(comment.value)) { let member; comment.value.replace(/@member\s+\{.*?\}\s+([^\s]+)/g, (match, _member_) => { member = _member_; return match; }); let oneofNames: string[] = []; comment.value.replace(/@memberof\s+([^\s]+)/g, (match, memberOf) => { oneofNames = root.lookupType(memberOf).oneofsArray.map(oneof => oneof.name); return match; }); if (!member || oneofNames.indexOf(member) === -1) { comment.value = ''; } } }); // Remove empty comments path.node.comments = path.node.comments.filter(comment => comment.value); jscodeshift(path).replaceWith(path.node); }); } function sourceToNodes(source: string) { return jscodeshift(source).paths()[0].node.program.body; } function buildClientFactorySource(namespace: string, services: Services) { return ` /** * Contains all the RPC service clients. * @exports ${namespace}.ClientFactory * @interface */ function ClientFactory() {} ${services .map( service => ` /** * Returns the ${service.name} service client. * @returns {${service.reference}} */ ClientFactory.prototype.get${service.name} = function() {}; `, ) .join('\n')} `; } function getNamepaceName(declarations: Collection<jscodeshift.VariableDeclaration>) { let namespaceName = ''; const node = declarations.paths()[0].node; if (!node.comments) { return ''; } node.comments.forEach(comment => { comment.value.replace(/@exports\s+([^\s]+)/g, (match, reference) => { namespaceName = reference; return match; }); if (!namespaceName) { comment.value.replace(/@memberof\s+([^\s]+)/g, (match, memberOf) => { const declaration = node.declarations[0]; if (declaration.type === 'VariableDeclarator') { if (declaration.id.type === 'Identifier') { const name = declaration.id.name; namespaceName = memberOf + '.' + name; } } return match; }); } }); return namespaceName; } function buildServerBuilderSource(namespace: string, services: Services) { return ` /** * Builder for an RPC service server. * @exports ${namespace}.ServerBuilder * @interface */ function ServerBuilder() {} ${services .map( service => ` /** * Adds a ${service.name} service implementation. * @param {${service.reference}} impl ${service.name} service implementation * @returns {${namespace}.ServerBuilder} */ ServerBuilder.prototype.add${service.name} = function() {}; `, ) .join('\n')} `; } function getNamespaceDeclarations(ast: Collection<ASTNode>) { return ast .find(jscodeshift.VariableDeclaration) .filter(path => !!path.node.comments) .filter(path => path.node.comments!.some(comment => { return /@namespace/.test(comment.value); }), ); } type PbMain = typeof pbjsMain | typeof pbtsMain; type Options = { [name: string]: string }; async function call( tempDir: string, func: PbMain, files: string[], ext = 'js', flags: string[] = [], opts: Options = {}, ) { const out = `${tempDir}/${Math.random()}.${ext}`; const all = { ...opts, out } as typeof opts; const args = Object.keys(all).map(name => [`--${name}`, all[name]]); await func([...flatten(args), ...flags.map(name => `--${name}`), ...files]); return out; } function flatten<T>(arr: T[][]): T[] { return Array.prototype.concat(...arr); }
the_stack
import {GaxiosOptions} from 'gaxios'; import {describe, it} from 'mocha'; import * as assert from 'assert'; import * as querystring from 'querystring'; import {Headers} from '../src/auth/oauth2client'; import { ClientAuthentication, OAuthClientAuthHandler, getErrorFromOAuthErrorResponse, } from '../src/auth/oauth2common'; /** Test class to test abstract class OAuthClientAuthHandler. */ class TestOAuthClientAuthHandler extends OAuthClientAuthHandler { testApplyClientAuthenticationOptions( opts: GaxiosOptions, bearerToken?: string ) { return this.applyClientAuthenticationOptions(opts, bearerToken); } } /** Custom error object for testing additional fields on an Error. */ class CustomError extends Error { public readonly code?: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(message: string, stack?: any, code?: string) { super(message); this.name = 'CustomError'; this.stack = stack; this.code = code; } } describe('OAuthClientAuthHandler', () => { const basicAuth: ClientAuthentication = { confidentialClientType: 'basic', clientId: 'username', clientSecret: 'password', }; // Base64 encoding of "username:password" const expectedBase64EncodedCred = 'dXNlcm5hbWU6cGFzc3dvcmQ='; const basicAuthNoSecret: ClientAuthentication = { confidentialClientType: 'basic', clientId: 'username', }; // Base64 encoding of "username:" const expectedBase64EncodedCredNoSecret = 'dXNlcm5hbWU6'; const reqBodyAuth: ClientAuthentication = { confidentialClientType: 'request-body', clientId: 'username', clientSecret: 'password', }; const reqBodyAuthNoSecret: ClientAuthentication = { confidentialClientType: 'request-body', clientId: 'username', }; it('should not process request when no client authentication is used', () => { const handler = new TestOAuthClientAuthHandler(); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { key1: 'value1', key2: 'value2', }, }; const actualOptions = Object.assign({}, originalOptions); handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(originalOptions, actualOptions); }); it('should process request with basic client auth', () => { const handler = new TestOAuthClientAuthHandler(basicAuth); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { key1: 'value1', key2: 'value2', }, }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); ( expectedOptions.headers as Headers ).Authorization = `Basic ${expectedBase64EncodedCred}`; handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should process request with secretless basic client auth', () => { const handler = new TestOAuthClientAuthHandler(basicAuthNoSecret); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { key1: 'value1', key2: 'value2', }, }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); ( expectedOptions.headers as Headers ).Authorization = `Basic ${expectedBase64EncodedCredNoSecret}`; handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should process GET (non-request-body) with basic client auth', () => { const handler = new TestOAuthClientAuthHandler(basicAuth); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'GET', headers: { 'Content-Type': 'application/json', }, }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); ( expectedOptions.headers as Headers ).Authorization = `Basic ${expectedBase64EncodedCred}`; handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); describe('with request-body client auth', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const unsupportedMethods: any[] = [ undefined, 'GET', 'DELETE', 'TRACE', 'OPTIONS', 'HEAD', ]; unsupportedMethods.forEach(method => { it(`should throw on requests with unsupported HTTP method ${method}`, () => { const expectedError = new Error( `${method || 'GET'} HTTP method does not support request-body ` + 'client authentication' ); const handler = new TestOAuthClientAuthHandler(reqBodyAuth); const originalOptions: GaxiosOptions = { method, url: 'https://www.example.com/path/to/api', }; assert.throws(() => { handler.testApplyClientAuthenticationOptions(originalOptions); }, expectedError); }); }); it('should throw on unsupported content-types', () => { const expectedError = new Error( 'text/html content-types are not supported with request-body ' + 'client authentication' ); const handler = new TestOAuthClientAuthHandler(reqBodyAuth); const originalOptions: GaxiosOptions = { headers: { 'Content-Type': 'text/html', }, method: 'POST', url: 'https://www.example.com/path/to/api', }; assert.throws(() => { handler.testApplyClientAuthenticationOptions(originalOptions); }, expectedError); }); it('should inject creds in non-empty json content', () => { const handler = new TestOAuthClientAuthHandler(reqBodyAuth); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { key1: 'value1', key2: 'value2', }, }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); expectedOptions.data.client_id = reqBodyAuth.clientId; expectedOptions.data.client_secret = reqBodyAuth.clientSecret; handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should inject secretless creds in json content', () => { const handler = new TestOAuthClientAuthHandler(reqBodyAuthNoSecret); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { key1: 'value1', key2: 'value2', }, }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); expectedOptions.data.client_id = reqBodyAuthNoSecret.clientId; expectedOptions.data.client_secret = ''; handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should inject creds in empty json content', () => { const handler = new TestOAuthClientAuthHandler(reqBodyAuth); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); expectedOptions.data = { client_id: reqBodyAuth.clientId, client_secret: reqBodyAuth.clientSecret, }; handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should inject creds in non-empty x-www-form-urlencoded content', () => { const handler = new TestOAuthClientAuthHandler(reqBodyAuth); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { // Handling of headers should be case insensitive. 'content-Type': 'application/x-www-form-urlencoded', }, data: querystring.stringify({key1: 'value1', key2: 'value2'}), }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); expectedOptions.data = querystring.stringify({ key1: 'value1', key2: 'value2', client_id: reqBodyAuth.clientId, client_secret: reqBodyAuth.clientSecret, }); handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should inject secretless creds in x-www-form-urlencoded content', () => { const handler = new TestOAuthClientAuthHandler(reqBodyAuthNoSecret); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, data: querystring.stringify({key1: 'value1', key2: 'value2'}), }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); expectedOptions.data = querystring.stringify({ key1: 'value1', key2: 'value2', client_id: reqBodyAuth.clientId, client_secret: '', }); handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should inject creds in empty x-www-form-urlencoded content', () => { const handler = new TestOAuthClientAuthHandler(reqBodyAuth); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); expectedOptions.data = querystring.stringify({ client_id: reqBodyAuth.clientId, client_secret: reqBodyAuth.clientSecret, }); handler.testApplyClientAuthenticationOptions(actualOptions); assert.deepStrictEqual(expectedOptions, actualOptions); }); }); it('should process request with bearer token when provided', () => { const bearerToken = 'BEARER_TOKEN'; const handler = new TestOAuthClientAuthHandler(); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { key1: 'value1', key2: 'value2', }, }; const actualOptions = Object.assign({}, originalOptions); const expectedOptions = Object.assign({}, originalOptions); ( expectedOptions.headers as Headers ).Authorization = `Bearer ${bearerToken}`; handler.testApplyClientAuthenticationOptions(actualOptions, bearerToken); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should prioritize bearer token over basic auth', () => { const bearerToken = 'BEARER_TOKEN'; const handler = new TestOAuthClientAuthHandler(basicAuth); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { key1: 'value1', key2: 'value2', }, }; const actualOptions = Object.assign({}, originalOptions); // Expected options should have bearer token in header. const expectedOptions = Object.assign({}, originalOptions); ( expectedOptions.headers as Headers ).Authorization = `Bearer ${bearerToken}`; handler.testApplyClientAuthenticationOptions(actualOptions, bearerToken); assert.deepStrictEqual(expectedOptions, actualOptions); }); it('should prioritize bearer token over request body', () => { const bearerToken = 'BEARER_TOKEN'; const handler = new TestOAuthClientAuthHandler(reqBodyAuth); const originalOptions: GaxiosOptions = { url: 'https://www.example.com/path/to/api', method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { key1: 'value1', key2: 'value2', }, }; const actualOptions = Object.assign({}, originalOptions); // Expected options should have bearer token in header. const expectedOptions = Object.assign({}, originalOptions); ( expectedOptions.headers as Headers ).Authorization = `Bearer ${bearerToken}`; handler.testApplyClientAuthenticationOptions(actualOptions, bearerToken); assert.deepStrictEqual(expectedOptions, actualOptions); }); }); describe('getErrorFromOAuthErrorResponse', () => { it('should create expected error with code, description and uri', () => { const resp = { error: 'unsupported_grant_type', error_description: 'The provided grant_type is unsupported', error_uri: 'https://tools.ietf.org/html/rfc6749', }; const error = getErrorFromOAuthErrorResponse(resp); assert.strictEqual( error.message, `Error code ${resp.error}: ${resp.error_description} ` + `- ${resp.error_uri}` ); }); it('should create expected error with code and description', () => { const resp = { error: 'unsupported_grant_type', error_description: 'The provided grant_type is unsupported', }; const error = getErrorFromOAuthErrorResponse(resp); assert.strictEqual( error.message, `Error code ${resp.error}: ${resp.error_description}` ); }); it('should create expected error with code only', () => { const resp = { error: 'unsupported_grant_type', }; const error = getErrorFromOAuthErrorResponse(resp); assert.strictEqual(error.message, `Error code ${resp.error}`); }); it('should preserve the original error properties', () => { const originalError = new CustomError( 'Original error message', 'Error stack', '123456' ); const resp = { error: 'unsupported_grant_type', error_description: 'The provided grant_type is unsupported', error_uri: 'https://tools.ietf.org/html/rfc6749', }; const expectedError = new CustomError( `Error code ${resp.error}: ${resp.error_description} ` + `- ${resp.error_uri}`, 'Error stack', '123456' ); const actualError = getErrorFromOAuthErrorResponse(resp, originalError); assert.strictEqual(actualError.message, expectedError.message); // eslint-disable-next-line @typescript-eslint/no-explicit-any assert.strictEqual((actualError as any).code, expectedError.code); assert.strictEqual(actualError.name, expectedError.name); assert.strictEqual(actualError.stack, expectedError.stack); }); });
the_stack
import { TestBed, fakeAsync, tick, waitForAsync } from '@angular/core/testing'; import { SortingDirection } from '../../data-operations/sorting-expression.interface'; import { IgxTreeGridComponent } from './tree-grid.component'; import { IgxGridCell, IgxTreeGridModule } from './public_api'; import { IgxTreeGridCellComponent } from './tree-cell.component'; import { IgxTreeGridSimpleComponent, IgxTreeGridCellSelectionComponent, IgxTreeGridSelectionRowEditingComponent, IgxTreeGridSelectionWithTransactionComponent, IgxTreeGridRowEditingTransactionComponent, IgxTreeGridCustomRowSelectorsComponent, IgxTreeGridCascadingSelectionComponent, IgxTreeGridCascadingSelectionTransactionComponent } from '../../test-utils/tree-grid-components.spec'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { TreeGridFunctions, TREE_ROW_SELECTION_CSS_CLASS, ROW_EDITING_BANNER_OVERLAY_CLASS, TREE_ROW_DIV_SELECTION_CHECKBOX_CSS_CLASS } from '../../test-utils/tree-grid-functions.spec'; import { IgxStringFilteringOperand, IgxNumberFilteringOperand } from '../../data-operations/filtering-condition'; import { configureTestSuite } from '../../test-utils/configure-suite'; import { wait, UIInteractions } from '../../test-utils/ui-interactions.spec'; import { IgxGridSelectionModule } from '../selection/selection.module'; import { IgxActionStripModule, IgxActionStripComponent } from '../../action-strip/public_api'; import { GridFunctions } from '../../test-utils/grid-functions.spec'; import { GridSelectionMode } from '../common/enums'; import { By } from '@angular/platform-browser'; import { FilteringExpressionsTree } from '../../data-operations/filtering-expressions-tree'; import { FilteringLogic } from '../../data-operations/filtering-expression.interface'; import { IRowSelectionEventArgs } from '../common/events'; describe('IgxTreeGrid - Selection #tGrid', () => { configureTestSuite(); let fix; let treeGrid: IgxTreeGridComponent; let actionStrip: IgxActionStripComponent; const endTransition = () => { // transition end needs to be simulated const animationElem = fix.nativeElement.querySelector('.igx-grid__tr--inner'); const endEvent = new AnimationEvent('animationend'); animationElem.dispatchEvent(endEvent); }; beforeAll(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ IgxTreeGridSimpleComponent, IgxTreeGridCellSelectionComponent, IgxTreeGridSelectionRowEditingComponent, IgxTreeGridSelectionWithTransactionComponent, IgxTreeGridRowEditingTransactionComponent, IgxTreeGridCustomRowSelectorsComponent, IgxTreeGridCascadingSelectionComponent, IgxTreeGridCascadingSelectionTransactionComponent ], imports: [IgxTreeGridModule, NoopAnimationsModule, IgxGridSelectionModule, IgxActionStripModule] }) .compileComponents(); })); describe('API Row Selection', () => { // configureTestSuite(); beforeEach(async () => { fix = TestBed.createComponent(IgxTreeGridSimpleComponent); fix.detectChanges(); treeGrid = fix.componentInstance.treeGrid; treeGrid.rowSelection = GridSelectionMode.multiple; await wait(); fix.detectChanges(); }); it('should have checkbox on each row if rowSelection is not none', () => { const rows = TreeGridFunctions.getAllRows(fix); expect(rows.length).toBe(10); rows.forEach((row) => { const checkBoxElement = row.nativeElement.querySelector(TREE_ROW_DIV_SELECTION_CHECKBOX_CSS_CLASS); expect(checkBoxElement).not.toBeNull(); }); treeGrid.rowSelection = GridSelectionMode.none; fix.detectChanges(); expect(rows.length).toBe(10); rows.forEach((row) => { const checkBoxElement = row.nativeElement.querySelector(TREE_ROW_DIV_SELECTION_CHECKBOX_CSS_CLASS); expect(checkBoxElement).toBeNull(); }); }); it('should be able to select/deselect all rows', () => { treeGrid.selectAllRows(); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], true); expect(treeGrid.selectedRows.length).toEqual(10); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); treeGrid.deselectAllRows(); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([]); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it('when all items are selected and then some of the selected rows are deleted, still all the items should be selected', () => { treeGrid.selectAllRows(); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); treeGrid.deleteRowById(treeGrid.selectedRows[0]); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); treeGrid.deleteRowById(treeGrid.selectedRows[0]); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); treeGrid.deleteRowById(treeGrid.selectedRows[0]); fix.detectChanges(); // When deleting the last selected row, header checkbox will be unchecked. TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it('should be able to select row of any level', () => { treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(0).rowID], true); fix.detectChanges(); // Verify selection. TreeGridFunctions.verifyDataRowsSelection(fix, [0], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(2).rowID], false); fix.detectChanges(); // Verify new selection by keeping the old one. TreeGridFunctions.verifyDataRowsSelection(fix, [0, 2], true); treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(1).rowID, treeGrid.gridAPI.get_row_by_index(3).rowID, treeGrid.gridAPI.get_row_by_index(6).rowID, treeGrid.gridAPI.get_row_by_index(8).rowID], true); fix.detectChanges(); // Verify new selection by NOT keeping the old one. TreeGridFunctions.verifyDataRowsSelection(fix, [0, 2], false); TreeGridFunctions.verifyDataRowsSelection(fix, [1, 3, 6, 8], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('should be able to deselect row of any level', () => { treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(1).rowID, treeGrid.gridAPI.get_row_by_index(3).rowID, treeGrid.gridAPI.get_row_by_index(6).rowID, treeGrid.gridAPI.get_row_by_index(8).rowID, treeGrid.gridAPI.get_row_by_index(9).rowID], true); fix.detectChanges(); treeGrid.deselectRows([treeGrid.gridAPI.get_row_by_index(1).rowID, treeGrid.gridAPI.get_row_by_index(3).rowID]); fix.detectChanges(); // Verify modified selection TreeGridFunctions.verifyDataRowsSelection(fix, [1, 3], false); TreeGridFunctions.verifyDataRowsSelection(fix, [6, 8, 9], true); }); it('should persist the selection after sorting', () => { treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(0).rowID, treeGrid.gridAPI.get_row_by_index(4).rowID], true); fix.detectChanges(); treeGrid.sort({ fieldName: 'Age', dir: SortingDirection.Asc, ignoreCase: false }); fix.detectChanges(); // Verification indices are different since the sorting changes rows' positions. TreeGridFunctions.verifyDataRowsSelection(fix, [2, 7], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.clearSort(); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 4], true); }); it('should persist the selection after filtering', fakeAsync(() => { treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(0).rowID, treeGrid.gridAPI.get_row_by_index(5).rowID, treeGrid.gridAPI.get_row_by_index(8).rowID], true); fix.detectChanges(); treeGrid.filter('Age', 40, IgxNumberFilteringOperand.instance().condition('greaterThan')); fix.detectChanges(); tick(); // Verification indices are different since the sorting changes rows' positions. TreeGridFunctions.verifyDataRowsSelection(fix, [0, 2, 4], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.clearFilter(); fix.detectChanges(); tick(); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 5, 8], true); })); it('should be able to select and select only filtered data', () => { treeGrid.selectRows([299, 147]); fix.detectChanges(); treeGrid.filter('Age', 40, IgxNumberFilteringOperand.instance().condition('greaterThan')); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([299, 147]); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.selectAllRows(true); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([299, 147, 317, 998, 19, 847]); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); treeGrid.deselectAllRows(true); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([299]); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); treeGrid.clearFilter(); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([299]); TreeGridFunctions.verifyDataRowsSelection(fix, [6], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('should persist the selection after expand/collapse', () => { treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(0).rowID, treeGrid.gridAPI.get_row_by_index(3).rowID, treeGrid.gridAPI.get_row_by_index(5).rowID], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); // Collapse row and verify visible selected rows treeGrid.toggleRow(treeGrid.gridAPI.get_row_by_index(0).rowID); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); // Expand same row and verify visible selected rows treeGrid.toggleRow(treeGrid.gridAPI.get_row_by_index(0).rowID); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 3, 5], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('should persist selection after paging', fakeAsync(() => { treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(0).rowID, treeGrid.gridAPI.get_row_by_index(3).rowID, treeGrid.gridAPI.get_row_by_index(5).rowID], true); fix.detectChanges(); tick(16); fix.componentInstance.paging = true; fix.detectChanges(); treeGrid.perPage = 4; fix.detectChanges(); tick(16); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, true); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 1, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 2, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, true); treeGrid.page = 1; fix.detectChanges(); tick(16); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 1, true); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 2, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, false); treeGrid.page = 2; fix.detectChanges(); tick(16); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 1, false); })); it('Should bind selectedRows properly', () => { fix.componentInstance.selectedRows = [147, 19, 957]; fix.detectChanges(); expect(treeGrid.gridAPI.get_row_by_index(0).selected).toBeTrue(); expect(treeGrid.gridAPI.get_row_by_index(7).selected).toBeTrue(); expect(treeGrid.gridAPI.get_row_by_index(4).selected).toBeFalse(); fix.componentInstance.selectedRows = [847, 711]; fix.detectChanges(); expect(treeGrid.gridAPI.get_row_by_index(0).selected).toBeFalse(); expect(treeGrid.gridAPI.get_row_by_index(4).selected).toBeTrue(); expect(treeGrid.gridAPI.get_row_by_index(8).selected).toBeTrue(); }); }); describe('UI Row Selection', () => { // configureTestSuite(); beforeEach(async () => { fix = TestBed.createComponent(IgxTreeGridSimpleComponent); fix.detectChanges(); treeGrid = fix.componentInstance.treeGrid; treeGrid.rowSelection = GridSelectionMode.multiple; await wait(); fix.detectChanges(); }); it('should be able to select/deselect all rows', () => { TreeGridFunctions.clickHeaderRowSelectionCheckbox(fix); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); TreeGridFunctions.clickHeaderRowSelectionCheckbox(fix); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [], true); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it('Header checkbox should NOT select/deselect all rows when selectionMode is single', () => { spyOn(treeGrid.rowSelected, 'emit').and.callThrough(); treeGrid.rowSelection = GridSelectionMode.single; fix.detectChanges(); TreeGridFunctions.clickHeaderRowSelectionCheckbox(fix); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); TreeGridFunctions.verifyDataRowsSelection(fix, [], false); expect(treeGrid.selectedRows).toEqual([]); expect(treeGrid.rowSelected.emit).toHaveBeenCalledTimes(0); TreeGridFunctions.clickHeaderRowSelectionCheckbox(fix); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); TreeGridFunctions.verifyDataRowsSelection(fix, [], false); expect(treeGrid.selectedRows).toEqual([]); expect(treeGrid.rowSelected.emit).toHaveBeenCalledTimes(0); }); it('should be able to select row of any level', () => { TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [0], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); TreeGridFunctions.clickRowSelectionCheckbox(fix, 2); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 2], true); // Deselect rows TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); TreeGridFunctions.clickRowSelectionCheckbox(fix, 2); fix.detectChanges(); // Select new rows TreeGridFunctions.clickRowSelectionCheckbox(fix, 1); TreeGridFunctions.clickRowSelectionCheckbox(fix, 3); TreeGridFunctions.clickRowSelectionCheckbox(fix, 6); TreeGridFunctions.clickRowSelectionCheckbox(fix, 8); fix.detectChanges(); // Verify new selection TreeGridFunctions.verifyDataRowsSelection(fix, [0, 2], false); TreeGridFunctions.verifyDataRowsSelection(fix, [1, 3, 6, 8], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('should be able to deselect row of any level', () => { // Select rows TreeGridFunctions.clickRowSelectionCheckbox(fix, 1); TreeGridFunctions.clickRowSelectionCheckbox(fix, 3); TreeGridFunctions.clickRowSelectionCheckbox(fix, 6); TreeGridFunctions.clickRowSelectionCheckbox(fix, 8); TreeGridFunctions.clickRowSelectionCheckbox(fix, 9); fix.detectChanges(); // Deselect rows TreeGridFunctions.clickRowSelectionCheckbox(fix, 1); TreeGridFunctions.clickRowSelectionCheckbox(fix, 3); fix.detectChanges(); // Verify modified selection TreeGridFunctions.verifyDataRowsSelection(fix, [1, 3], false); TreeGridFunctions.verifyDataRowsSelection(fix, [6, 8, 9], true); }); it('Rows would be selected only from checkboxes if selectRowOnClick is disabled', () => { expect(treeGrid.selectRowOnClick).toBe(true); const firstRow = treeGrid.gridAPI.get_row_by_index(1); const secondRow = treeGrid.gridAPI.get_row_by_index(4); expect(treeGrid.selectedRows).toEqual([]); // selectRowOnClick = true; UIInteractions.simulateClickEvent(firstRow.nativeElement); fix.detectChanges(); UIInteractions.simulateClickEvent(secondRow.nativeElement, false, true); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [1, 4], true); TreeGridFunctions.clickRowSelectionCheckbox(fix, 1); fix.detectChanges(); TreeGridFunctions.clickRowSelectionCheckbox(fix, 4); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([]); // selectRowOnClick = false treeGrid.selectRowOnClick = false; UIInteractions.simulateClickEvent(firstRow.nativeElement); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [1], false); TreeGridFunctions.clickRowSelectionCheckbox(fix, 1); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [1], true); TreeGridFunctions.clickRowSelectionCheckbox(fix, 4); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [1, 4], true); }); it('should persist the selection after sorting', () => { TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); TreeGridFunctions.clickRowSelectionCheckbox(fix, 4); treeGrid.columnList.filter(c => c.field === 'Age')[0].sortable = true; fix.detectChanges(); treeGrid.sort({ fieldName: 'Age', dir: SortingDirection.Asc, ignoreCase: false }); fix.detectChanges(); // Verification indices are different since the sorting changes rows' positions. TreeGridFunctions.verifyDataRowsSelection(fix, [2, 7], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.clearSort(); fix.detectChanges(); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 4], true); }); it('should persist the selection after filtering', fakeAsync(() => { TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); TreeGridFunctions.clickRowSelectionCheckbox(fix, 5); TreeGridFunctions.clickRowSelectionCheckbox(fix, 8); treeGrid.filter('Age', 40, IgxNumberFilteringOperand.instance().condition('greaterThan')); fix.detectChanges(); tick(100); // Verification indices are different since the sorting changes rows' positions. TreeGridFunctions.verifyDataRowsSelection(fix, [0, 2, 4], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.clearFilter(); fix.detectChanges(); tick(100); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 5, 8], true); })); it('should update header checkbox when reselecting all filtered-in rows', fakeAsync(() => { treeGrid.filter('Age', 30, IgxNumberFilteringOperand.instance().condition('lessThan')); tick(100); TreeGridFunctions.clickHeaderRowSelectionCheckbox(fix); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); // Verify header checkbox is selected TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); // Unselect row fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // Verify header checkbox is indeterminate TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); // Reselect same row fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); // Verify header checkbox is selected })); it('should persist the selection after expand/collapse', () => { TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); TreeGridFunctions.clickRowSelectionCheckbox(fix, 3); TreeGridFunctions.clickRowSelectionCheckbox(fix, 5); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); // Collapse row and verify visible selected rows TreeGridFunctions.clickRowIndicator(fix, 0); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); // Expand same row and verify visible selected rows TreeGridFunctions.clickRowIndicator(fix, 0); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 3, 5], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('should persist selection after paging', fakeAsync(() => { TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); TreeGridFunctions.clickRowSelectionCheckbox(fix, 3); TreeGridFunctions.clickRowSelectionCheckbox(fix, 5); fix.detectChanges(); fix.componentInstance.paging = true; fix.detectChanges(); treeGrid.perPage = 4; fix.detectChanges(); tick(16); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, true); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 1, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 2, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, true); treeGrid.page = 1; fix.detectChanges(); tick(16); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 1, true); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 2, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, false); treeGrid.page = 2; fix.detectChanges(); tick(16); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 1, false); })); it('Should update selectedRows when selecting rows from UI', fakeAsync(() => { TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); TreeGridFunctions.clickRowSelectionCheckbox(fix, 3); TreeGridFunctions.clickRowSelectionCheckbox(fix, 5); fix.detectChanges(); expect(treeGrid.selectedRows.length).toBe(3); })); }); describe('Row Selection with transactions - Hierarchical DS', () => { // configureTestSuite(); beforeEach(fakeAsync(() => { fix = TestBed.createComponent(IgxTreeGridSelectionWithTransactionComponent); fix.detectChanges(); treeGrid = fix.componentInstance.treeGrid; treeGrid.rowSelection = GridSelectionMode.multiple; fix.detectChanges(); })); it('should deselect row when delete its parent', () => { treeGrid.selectRows([treeGrid.gridAPI.get_row_by_index(3).rowID, treeGrid.gridAPI.get_row_by_index(5).rowID], true); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, true); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 5, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.deleteRow(147); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 5, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); expect(treeGrid.selectedRows).toEqual([]); // try to select deleted row UIInteractions.simulateClickEvent(treeGrid.gridAPI.get_row_by_index(0).nativeElement); TreeGridFunctions.clickRowSelectionCheckbox(fix, 3); TreeGridFunctions.clickRowSelectionCheckbox(fix, 5); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 5, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); expect(treeGrid.selectedRows).toEqual([]); // undo transaction treeGrid.transactions.undo(); fix.detectChanges(); // select rows UIInteractions.simulateClickEvent(treeGrid.gridAPI.get_row_by_index(0).nativeElement); TreeGridFunctions.clickRowSelectionCheckbox(fix, 3); TreeGridFunctions.clickRowSelectionCheckbox(fix, 5); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, true); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, true); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 5, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); expect(treeGrid.selectedRows).toEqual([147, 317, 998]); // redo transaction treeGrid.transactions.redo(); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 0, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 5, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); expect(treeGrid.selectedRows).toEqual([]); }); it('should have correct header checkbox when delete a row', () => { treeGrid.selectAllRows(); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); treeGrid.deleteRow(317); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); expect(treeGrid.selectedRows.includes(317)).toEqual(false); expect(treeGrid.selectedRows.includes(711)).toEqual(false); expect(treeGrid.selectedRows.includes(998)).toEqual(false); // undo transaction treeGrid.transactions.undo(); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 4, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 5, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // redo transaction treeGrid.transactions.redo(); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 3, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 4, false); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 5, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); }); it('should have correct header checkbox when add a row', () => { treeGrid.selectAllRows(); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); treeGrid.addRow({ ID: 13, Name: 'Michael Cooper', Age: 33, OnPTO: false }, 317); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 6, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); expect(treeGrid.selectedRows.includes(13)).toEqual(false); // undo transaction treeGrid.transactions.undo(); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); }); it('should have correct header checkbox when add a row and then selectAll rows', () => { treeGrid.addRow({ ID: 13, Name: 'Michael Cooper', Age: 33, OnPTO: false }, 317); fix.detectChanges(); TreeGridFunctions.clickHeaderRowSelectionCheckbox(fix); fix.detectChanges(); expect(treeGrid.selectedRows.length).toBeGreaterThan(treeGrid.flatData.length); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); }); it('should have correct header checkbox when add a row and undo transaction', fakeAsync(() => { treeGrid.addRow({ ID: 13, Name: 'Michael Cooper', Age: 33, OnPTO: false }, 317); tick(); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); TreeGridFunctions.clickRowSelectionCheckbox(fix, 6); fix.detectChanges(); TreeGridFunctions.verifyTreeRowSelectionByIndex(fix, 6, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // undo transaction treeGrid.transactions.undo(); tick(); fix.detectChanges(); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); expect(treeGrid.selectedRows.includes(13)).toEqual(false); })); it('Should be able to select deleted rows through API - Hierarchical DS', () => { treeGrid.deleteRowById(663); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([]); treeGrid.selectRows([663]); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([663]); /** Select row with deleted parent */ treeGrid.deleteRowById(147); fix.detectChanges(); // 147 -> 475 treeGrid.selectRows([475]); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([663, 475]); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it('Should not be able to select deleted rows through API with selectAllRows - Hierarchical DS', () => { treeGrid.deleteRowById(663); treeGrid.deleteRowById(147); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([]); treeGrid.selectAllRows(); fix.detectChanges(); expect(treeGrid.selectedRows.includes(663)).toBe(false); expect(treeGrid.selectedRows.includes(147)).toBe(false); expect(treeGrid.selectedRows.includes(475)).toBe(false); expect(treeGrid.selectedRows.includes(19)).toBe(true); expect(treeGrid.selectedRows.includes(847)).toBe(true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); }); }); describe('Row Selection with transactions - flat DS', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(IgxTreeGridRowEditingTransactionComponent); fix.detectChanges(); treeGrid = fix.componentInstance.treeGrid; treeGrid.rowSelection = GridSelectionMode.multiple; fix.detectChanges(); })); it('Should select deleted rows through API', () => { treeGrid.deleteRowById(6); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([]); treeGrid.selectRows([6]); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([6]); /** Select row with deleted parent */ treeGrid.deleteRowById(10); fix.detectChanges(); // 10 -> 9 treeGrid.selectRows([9]); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([6, 9]); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it('Should not be able to select deleted rows through API with selectAllRows', () => { treeGrid.deleteRowById(6); treeGrid.deleteRowById(10); fix.detectChanges(); expect(treeGrid.selectedRows).toEqual([]); treeGrid.selectAllRows(); fix.detectChanges(); expect(treeGrid.selectedRows.includes(6)).toBe(false); expect(treeGrid.selectedRows.includes(10)).toBe(false); expect(treeGrid.selectedRows.includes(9)).toBe(false); expect(treeGrid.selectedRows.includes(1)).toBe(true); expect(treeGrid.selectedRows.includes(2)).toBe(true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, true); }); }); describe('Cell Selection', () => { // configureTestSuite(); beforeEach(fakeAsync(/** height/width setter rAF */() => { fix = TestBed.createComponent(IgxTreeGridCellSelectionComponent); fix.detectChanges(); tick(16); treeGrid = fix.componentInstance.treeGrid; })); it('should return the correct type of cell when clicking on a cells', () => { const rows = TreeGridFunctions.getAllRows(fix); const normalCells = TreeGridFunctions.getNormalCells(rows[0]); UIInteractions.simulateClickAndSelectEvent(normalCells[0]); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); let treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); // perform 2 clicks and check selection again treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); }); it('should return the correct type of cell when clicking on child cells', () => { const rows = TreeGridFunctions.getAllRows(fix); // level 1 let treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(147); // level 2 treeGridCell = TreeGridFunctions.getTreeCell(rows[1]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(475); // level 3 treeGridCell = TreeGridFunctions.getTreeCell(rows[2]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(957); }); it('should not persist selection after paging', () => { let rows = TreeGridFunctions.getAllRows(fix); let treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(TreeGridFunctions.verifyGridCellHasSelectedClass(treeGridCell)).toBe(true); // Clicking on the pager buttons triggers a blur event. GridFunctions.navigateToNextPage(treeGrid.nativeElement); treeGridCell.nativeElement.dispatchEvent(new Event('blur')); fix.detectChanges(); GridFunctions.navigateToFirstPage(treeGrid.nativeElement); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(0); rows = TreeGridFunctions.getAllRows(fix); treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(TreeGridFunctions.verifyGridCellHasSelectedClass(treeGridCell)).toBe(true); GridFunctions.navigateToLastPage(treeGrid.nativeElement); treeGridCell.nativeElement.dispatchEvent(new Event('blur')); fix.detectChanges(); GridFunctions.navigateToFirstPage(treeGrid.nativeElement); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(0); }); it('should persist selection after filtering', fakeAsync(() => { const rows = TreeGridFunctions.getAllRows(fix); const treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); treeGrid.filter('ID', '14', IgxStringFilteringOperand.instance().condition('startsWith'), true); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(TreeGridFunctions.verifyGridCellHasSelectedClass(treeGridCell)).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(147); // set new filtering treeGrid.clearFilter('ProductName'); treeGrid.filter('ID', '8', IgxStringFilteringOperand.instance().condition('startsWith'), true); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(TreeGridFunctions.verifyGridCellHasSelectedClass(treeGridCell)).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(847); })); it('should persist selection after scrolling', async () => { treeGrid.paging = false; fix.detectChanges(); const rows = TreeGridFunctions.getAllRows(fix); const treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); // scroll down 150 pixels treeGrid.verticalScrollContainer.getScroll().scrollTop = 150; treeGrid.headerContainer.getScroll().dispatchEvent(new Event('scroll')); await wait(100); fix.detectChanges(); // then scroll back to top treeGrid.verticalScrollContainer.getScroll().scrollTop = 0; treeGrid.headerContainer.getScroll().dispatchEvent(new Event('scroll')); await wait(100); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(147); }); it('should persist selection after sorting', () => { const rows = TreeGridFunctions.getAllRows(fix); const treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(147); treeGrid.sort({ fieldName: 'ID', dir: SortingDirection.Desc, ignoreCase: false }); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(847); }); it('should persist selection after row delete', () => { const rows = TreeGridFunctions.getAllRows(fix); const treeGridCell = TreeGridFunctions.getTreeCell(rows[0]); UIInteractions.simulateClickAndSelectEvent(treeGridCell); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(147); treeGrid.deleteRow(847); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(147); treeGrid.deleteRow(147); fix.detectChanges(); expect(treeGrid.selectedCells.length).toBe(1); expect(treeGrid.selectedCells[0] instanceof IgxGridCell).toBe(true); expect(treeGrid.selectedCells[0].value).toBe(19); }); }); describe('Cell/Row Selection With Row Editing', () => { // configureTestSuite(); beforeEach(async () => { fix = TestBed.createComponent(IgxTreeGridSelectionRowEditingComponent); fix.detectChanges(); treeGrid = fix.componentInstance.treeGrid; await wait(); fix.detectChanges(); }); it('should display the banner correctly on row selection', fakeAsync(() => { const targetCell = treeGrid.getCellByColumn(1, 'Name'); treeGrid.rowSelection = GridSelectionMode.multiple; treeGrid.rowEditable = true; // select the second row treeGrid.selectRows([targetCell.id.rowID], true); tick(16); fix.detectChanges(); // check if any rows were selected expect(treeGrid.selectedRows.length).toBeGreaterThan(0); // enter edit mode targetCell.editMode = true; tick(16); fix.detectChanges(); // the banner should appear const banner = document.getElementsByClassName(ROW_EDITING_BANNER_OVERLAY_CLASS); expect(banner).toBeTruthy(); expect(banner[0]).toBeTruthy(); })); it('should display the banner correctly on cell selection', fakeAsync(() => { treeGrid.rowEditable = true; const allRows = TreeGridFunctions.getAllRows(fix); const treeGridCells = TreeGridFunctions.getNormalCells(allRows[0]); // select a cell const targetCell = treeGridCells[0]; UIInteractions.simulateClickAndSelectEvent(targetCell); fix.detectChanges(); // there should be at least one selected cell expect(treeGrid.selectedCells.length).toBeGreaterThan(0); // enter edit mode targetCell.triggerEventHandler('dblclick', new Event('dblclick')); tick(16); fix.detectChanges(); // the banner should appear const banner = document.getElementsByClassName(ROW_EDITING_BANNER_OVERLAY_CLASS); expect(banner).toBeTruthy(); expect(banner[0]).toBeTruthy(); })); }); describe('Cascading Row Selection', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(IgxTreeGridCascadingSelectionComponent); fix.detectChanges(); treeGrid = fix.componentInstance.treeGrid; actionStrip = fix.componentInstance.actionStrip; })); it('Should select/deselect all leaf nodes and set the correct state to their checkboxes on parent rows checkbox click', () => { TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(7); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // Deselect rows TreeGridFunctions.clickRowSelectionCheckbox(fix, 0); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6], false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it('Should select/deselect parent row by selecting/deselecting all its children', () => { treeGrid.selectRows([475, 957, 711, 998, 299], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(7); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // Deselect rows treeGrid.deselectRows([475, 957, 711, 998, 299]); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6], false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it('Should select/deselect parent row by selecting/deselecting the last deselected/selected child', () => { treeGrid.selectRows([475, 957, 711, 998], true); fix.detectChanges(); TreeGridFunctions.clickRowSelectionCheckbox(fix, 6); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(7); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // Deselect rows treeGrid.deselectRows([475, 957, 711, 998]); fix.detectChanges(); TreeGridFunctions.clickRowSelectionCheckbox(fix, 6); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6], false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it(`Should set parent row checkbox to indeterminate by selecting/deselecting a child row when all child rows are deselected/selected`, () => { TreeGridFunctions.clickRowSelectionCheckbox(fix, 6); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // Deselect one row treeGrid.selectRows([475, 957, 711, 998, 299], true); fix.detectChanges(); TreeGridFunctions.clickRowSelectionCheckbox(fix, 6); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('Should select all children of record on Shift + click even if they are not in the selected range. ', () => { const firstRow = treeGrid.gridAPI.get_row_by_index(1); const secondRow = treeGrid.gridAPI.get_row_by_index(4); const mockEvent = new MouseEvent('click', { shiftKey: true }); UIInteractions.simulateClickEvent(firstRow.nativeElement); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toEqual(1); TreeGridFunctions.verifyDataRowsSelection(fix, [1], true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // Click on other row holding Shift key secondRow.nativeElement.dispatchEvent(mockEvent); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(7); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('Should select only the newly clicked parent row and its children and deselect the previous selection.', () => { treeGrid.selectRows([19, 847], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); const firstRow = treeGrid.gridAPI.get_row_by_index(0); UIInteractions.simulateClickEvent(firstRow.nativeElement); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(7); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('Should add a row and its children to the selected rows collection using Ctrl + click.', () => { treeGrid.selectRows([847], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(2); // select a child of the first parent and all of its children const firstRow = treeGrid.gridAPI.get_row_by_index(3); UIInteractions.simulateClickEvent(firstRow.nativeElement, false, true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(6); TreeGridFunctions.verifyDataRowsSelection(fix, [3, 4, 5, 6, 8, 9], true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); // select the first parent and all of its children const secondRow = treeGrid.gridAPI.get_row_by_index(0); UIInteractions.simulateClickEvent(secondRow.nativeElement, false, true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(9); TreeGridFunctions.verifyDataRowsSelection(fix, [0, 1, 2, 3, 4, 5, 6, 8, 9], true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('After adding a new child row to a selected parent its checkbox state SHOULD be indeterminate.', async () => { treeGrid.selectRows([847], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 8, true, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); const row = treeGrid.gridAPI.get_row_by_index(8); actionStrip.show(row); fix.detectChanges(); // add new child through the UI const editActions = fix.debugElement.queryAll(By.css(`igx-grid-action-button`)); const addChildBtn = editActions[2].componentInstance; addChildBtn.actionClick.emit(); fix.detectChanges(); endTransition(); const addRow = treeGrid.gridAPI.get_row_by_index(9); expect(addRow.addRowUI).toBeTrue(); treeGrid.gridAPI.crudService.endEdit(true); await wait(100); fix.detectChanges(); const addedRow = treeGrid.gridAPI.get_row_by_index(10); expect(addedRow.rowData.Name).toBe(undefined); TreeGridFunctions.verifyDataRowsSelection(fix, [9], true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 8, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('After adding child to a selected parent with no children, parent checkbox state SHOULD NOT be selected.', async () => { treeGrid.selectRows([957], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.addRow({ ID: -1, Name: undefined, HireDate: undefined, Age: undefined }, 957); fix.detectChanges(); await wait(100); fix.detectChanges(); const addedRow = treeGrid.gridAPI.get_row_by_index(3); expect(addedRow.rowData.Name).toBe(undefined); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 2, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it('If parent and its children are selected and we delete a child, parent SHOULD be still selected.', async () => { treeGrid.selectRows([147], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(7); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, true, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); expect(treeGrid.dataRowList.length).toBe(10); const childRow = treeGrid.gridAPI.get_row_by_index(5); actionStrip.show(childRow); fix.detectChanges(); // delete the child through the UI const editActions = fix.debugElement.queryAll(By.css(`igx-grid-action-button`)); const deleteBtn = editActions[2].componentInstance; deleteBtn.actionClick.emit(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(treeGrid.dataRowList.length).toBe(9); expect(getVisibleSelectedRows(fix).length).toBe(6); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, true, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('If parent has one non-selected child and we delete it, the parent checkbox state SHOULD be selected.', async () => { treeGrid.selectRows([711, 299], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); expect(treeGrid.dataRowList.length).toBe(10); const childRow = treeGrid.gridAPI.get_row_by_index(5); actionStrip.show(childRow); fix.detectChanges(); // delete the child through the UI const editActions = fix.debugElement.queryAll(By.css(`igx-grid-action-button`)); const deleteBtn = editActions[2].componentInstance; deleteBtn.actionClick.emit(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(treeGrid.dataRowList.length).toBe(9); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('If we delete the only selected child of a parent row, the parent checkbox state SHOULD be deselected', async () => { treeGrid.selectRows([711], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); expect(treeGrid.dataRowList.length).toBe(10); // delete the child through the API const childRow = treeGrid.gridAPI.get_row_by_index(4); childRow.delete(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(treeGrid.dataRowList.length).toBe(9); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); it(`If there is only one selected leaf row for a particular parent and we filter it out parent's checkbox state -> non-selected. All non-direct parents’ checkbox states should be set correctly as well`, async () => { treeGrid.selectRows([711], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); treeGrid.filter('ID', 711, IgxNumberFilteringOperand.instance().condition('doesNotEqual')); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); }); it(`If there is only one non-selected row for a particular parent and we filter it out parent's checkbox state -> selected. All non-direct parents’ checkbox states should be set correctly as well`, async () => { treeGrid.selectRows([711, 998], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 5, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 6, false, false); treeGrid.filter('ID', 299, IgxNumberFilteringOperand.instance().condition('doesNotEqual')); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 5, true, true); }); it(`No rows are selected. Filter out all children for certain parent. Select this parent. It should be the only one within the selectedRows collection. Remove filtering. The selectedRows collection should be empty. All non-direct parents’ checkbox states should be set correctly as well`, async () => { const expressionTree = new FilteringExpressionsTree(FilteringLogic.And, 'ID'); expressionTree.filteringOperands = [ { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 711 }, { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 998 }, { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 299 } ]; treeGrid.filter('ID', null, expressionTree); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); treeGrid.selectRows([317], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); treeGrid.clearFilter(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); }); it(`Filter out all selected children for a certain parent and explicitly deselect it. Remove filtering. Parent row should be selected again. All non-direct parents’ checkbox states should be set correctly as well`, async () => { treeGrid.selectRows([317], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); const expressionTree = new FilteringExpressionsTree(FilteringLogic.And, 'ID'); expressionTree.filteringOperands = [ { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 711 }, { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 998 }, { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 299 } ]; treeGrid.filter('ID', null, expressionTree); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); treeGrid.deselectRows([317]); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); treeGrid.clearFilter(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); }); it(`Parent in indeterminate state. Filter out its children -> parent not selected. Select parent and add new child. Parent -> not selected. Revert filtering so that previous records are back in the view and parent should become in indeterminate state because one of it children is selected`, fakeAsync(() => { treeGrid.selectRows([998], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); const expressionTree = new FilteringExpressionsTree(FilteringLogic.And, 'ID'); expressionTree.filteringOperands = [ { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 711 }, { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 998 }, { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 299 } ]; treeGrid.filter('ID', null, expressionTree); fix.detectChanges(); tick(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); treeGrid.selectRows([317]); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); treeGrid.addRow({ ID: -1, Name: undefined, HireDate: undefined, Age: undefined }, 317); fix.detectChanges(); tick(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); treeGrid.clearFilter(); fix.detectChanges(); tick(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); })); it(`Selected parent. Filter out some of the children and delete otheres. Parent should be not selected`, fakeAsync(() => { treeGrid.selectRows([317], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); const expressionTree = new FilteringExpressionsTree(FilteringLogic.And, 'ID'); expressionTree.filteringOperands = [ { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 711 }, { condition: IgxNumberFilteringOperand.instance().condition('doesNotEqual'), fieldName: 'ID', searchVal: 998 } ]; treeGrid.filter('ID', null, expressionTree); fix.detectChanges(); tick(100); fix.detectChanges(); treeGrid.deleteRow(299); fix.detectChanges(); tick(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); })); it(`Set nested child row, that has its own children, as initially selected and verify that both direct and indirect parent's checkboxes are set in the correct state.`, fakeAsync(() => { treeGrid.selectedRows = [317]; fix.detectChanges(); tick(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 5, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 6, true, true); })); it(`Setting true to the cancel property of the rowSelected event should not modify the selected rows collection`, () => { treeGrid.rowSelected.subscribe((e: IRowSelectionEventArgs) => { e.cancel = true; }); spyOn(treeGrid.rowSelected, 'emit').and.callThrough(); treeGrid.selectionService.selectRowsWithNoEvent([317]); fix.detectChanges(); treeGrid.selectionService.deselectRow(299); fix.detectChanges(); const args: IRowSelectionEventArgs = { oldSelection: [317, 711, 998, 299], newSelection: [711, 998], added: [], removed: [317, 299], event: undefined, cancel: true }; expect(treeGrid.rowSelected.emit).toHaveBeenCalledWith(args); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 5, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 6, true, true); }); it(`selectionService clearRowSelection method should work correctly`, () => { treeGrid.selectionService.selectRowsWithNoEvent([711]); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); expect(treeGrid.selectionService.indeterminateRows.size).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 1, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 2, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, true, true); treeGrid.selectionService.clearRowSelection(); treeGrid.cdr.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); expect(treeGrid.selectionService.indeterminateRows.size).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 1, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 2, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, false, false); }); it(`selectionService selectAllRows method should work correctly`, () => { treeGrid.selectionService.selectRowsWithNoEvent([711]); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); expect(treeGrid.selectionService.indeterminateRows.size).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 1, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 2, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, true, true); treeGrid.selectionService.selectAllRows(); treeGrid.cdr.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(10); expect(treeGrid.selectionService.indeterminateRows.size).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 1, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 2, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, true, true); }); it('selectRowById event SHOULD be emitted correctly with valid arguments.', () => { spyOn(treeGrid.rowSelected, 'emit').and.callThrough(); treeGrid.selectionService.selectRowsWithNoEvent([317]); fix.detectChanges(); expect(treeGrid.rowSelected.emit).toHaveBeenCalledTimes(0); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 5, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 6, true, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.selectionService.selectRowById(847, true); const args: IRowSelectionEventArgs = { oldSelection: [317, 711, 998, 299], newSelection: [847, 663], added: [847, 663], removed: [317, 711, 998, 299], event: undefined, cancel: false }; expect(treeGrid.rowSelected.emit).toHaveBeenCalledWith(args); treeGrid.cdr.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 4, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 5, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 6, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 8, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 9, true, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('After changing the newSelection arguments of onSelectedRowChange, the arguments SHOULD be correct.', () => { treeGrid.rowSelected.subscribe((e: IRowSelectionEventArgs) => { e.newSelection = [847, 663]; }); spyOn(treeGrid.rowSelected, 'emit').and.callThrough(); treeGrid.selectionService.selectRowsWithNoEvent([317], true); fix.detectChanges(); treeGrid.selectionService.selectRowById(19, true); const selectionArgs: IRowSelectionEventArgs = { oldSelection: [317, 711, 998, 299], newSelection: [847, 663], added: [19], removed: [317, 711, 998, 299], event: undefined, cancel: false }; expect(treeGrid.rowSelected.emit).toHaveBeenCalledWith(selectionArgs); treeGrid.cdr.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 8, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 9, true, true); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); }); describe('Cascading Row Selection with Transaction', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(IgxTreeGridCascadingSelectionTransactionComponent); fix.detectChanges(); treeGrid = fix.componentInstance.treeGrid; actionStrip = fix.componentInstance.actionStrip; })); it('Add a new leaf row to a selected parent and revert the transaction. The parent SHOULD be selected.', async () => { const trans = treeGrid.transactions; treeGrid.selectRows([317], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.addRow({ ID: -1, Name: undefined, HireDate: undefined, Age: undefined }, 317); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); trans.undo(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('Add a new row to a selected parent and commit the transaction.The parent checkbox state SHOULD be indeterminate', async () => { const trans = treeGrid.transactions; treeGrid.selectRows([317], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); treeGrid.addRow({ ID: -1, Name: undefined, HireDate: undefined, Age: undefined }, 317); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); trans.commit(treeGrid.data); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('Delete one of the children of selected parent. Parent checkbox state SHOULD be selected.', async () => { const trans = treeGrid.transactions; treeGrid.selectRows([317], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(4); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); const childRow = treeGrid.gridAPI.get_row_by_index(4); childRow.delete(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); trans.undo(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); trans.redo(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('After delete the only non-selected child, the parent checkbox state SHOULD be selected.', async () => { treeGrid.selectRows([711, 299], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(2); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); const childRow = treeGrid.gridAPI.get_row_by_index(5); actionStrip.show(childRow); fix.detectChanges(); // delete the child through the UI const editActions = fix.debugElement.queryAll(By.css(`igx-grid-action-button`)); const deleteBtn = editActions[2].componentInstance; deleteBtn.actionClick.emit(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(3); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, true, true); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); }); it('Delete the only selected child of a parent row. Parent checkbox state SHOULD NOT be selected.', async () => { treeGrid.selectRows([998], true); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(1); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, null); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, null); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, null); const row = treeGrid.gridAPI.get_row_by_index(5); row.delete(); fix.detectChanges(); await wait(100); fix.detectChanges(); expect(getVisibleSelectedRows(fix).length).toBe(0); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 3, false, false); TreeGridFunctions.verifyRowByIndexSelectionAndCheckboxState(fix, 0, false, false); TreeGridFunctions.verifyHeaderCheckboxSelection(fix, false); }); }); describe('Custom row selectors', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(IgxTreeGridCustomRowSelectorsComponent); fix.detectChanges(); treeGrid = fix.componentInstance.treeGrid; })); it('Should have the correct properties in the custom row selector template', () => { const firstRow = treeGrid.gridAPI.get_row_by_index(0); const firstCheckbox = firstRow.nativeElement.querySelector('.igx-checkbox__composite'); const context = { index: 0, rowID: 1, selected: false }; const contextUnselect = { index: 0, rowID: 1, selected: true }; spyOn(fix.componentInstance, 'onRowCheckboxClick').and.callThrough(); (firstCheckbox as HTMLElement).click(); fix.detectChanges(); expect(fix.componentInstance.onRowCheckboxClick).toHaveBeenCalledTimes(1); expect(fix.componentInstance.onRowCheckboxClick).toHaveBeenCalledWith(fix.componentInstance.rowCheckboxClick, context); // Verify correct properties when unselecting a row (firstCheckbox as HTMLElement).click(); fix.detectChanges(); expect(fix.componentInstance.onRowCheckboxClick).toHaveBeenCalledTimes(2); expect(fix.componentInstance.onRowCheckboxClick).toHaveBeenCalledWith(fix.componentInstance.rowCheckboxClick, contextUnselect); }); it('Should have the correct properties in the custom row selector header template', () => { const context = { selectedCount: 0, totalCount: 8 }; const contextUnselect = { selectedCount: 8, totalCount: 8 }; const headerCheckbox = treeGrid.theadRow.nativeElement.querySelector('.igx-checkbox__composite') as HTMLElement; spyOn(fix.componentInstance, 'onHeaderCheckboxClick').and.callThrough(); headerCheckbox.click(); fix.detectChanges(); expect(fix.componentInstance.onHeaderCheckboxClick).toHaveBeenCalledTimes(1); expect(fix.componentInstance.onHeaderCheckboxClick).toHaveBeenCalledWith(fix.componentInstance.headerCheckboxClick, context); headerCheckbox.click(); fix.detectChanges(); expect(fix.componentInstance.onHeaderCheckboxClick).toHaveBeenCalledTimes(2); expect(fix.componentInstance.onHeaderCheckboxClick). toHaveBeenCalledWith(fix.componentInstance.headerCheckboxClick, contextUnselect); }); it('Should have correct indices on all pages', () => { treeGrid.nextPage(); fix.detectChanges(); const firstRootRow = treeGrid.gridAPI.get_row_by_index(0); expect(firstRootRow.nativeElement.querySelector('.rowNumber').textContent).toEqual('5'); }); }); }); const getVisibleSelectedRows = (fix) => TreeGridFunctions.getAllRows(fix).filter( (row) => row.nativeElement.classList.contains(TREE_ROW_SELECTION_CSS_CLASS));
the_stack
import { Stack, Duration } from '@aws-cdk/core'; import { LambdaToSagemakerEndpoint, LambdaToSagemakerEndpointProps } from '../lib'; import * as defaults from '@aws-solutions-constructs/core'; import * as lambda from '@aws-cdk/aws-lambda'; import * as iam from '@aws-cdk/aws-iam'; import '@aws-cdk/assert/jest'; // ----------------------------------------------------------------------------------------- // Pattern deployment with new Lambda function, new Sagemaker endpoint and deployVpc = true // ----------------------------------------------------------------------------------------- test('Pattern deployment with new Lambda function, new Sagemaker endpoint, deployVpc = true', () => { // Initial Setup const stack = new Stack(); const constructProps: LambdaToSagemakerEndpointProps = { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, lambdaFunctionProps: { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, }, deployVpc: true, }; new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); expect(stack).toHaveResourceLike('AWS::Lambda::Function', { Environment: { Variables: { SAGEMAKER_ENDPOINT_NAME: { 'Fn::GetAtt': ['testlambdasagemakerSagemakerEndpoint12803730', 'EndpointName'], }, }, }, VpcConfig: { SecurityGroupIds: [ { 'Fn::GetAtt': ['testlambdasagemakerReplaceDefaultSecurityGroupsecuritygroupB2FD7810', 'GroupId'], }, ], SubnetIds: [ { Ref: 'VpcisolatedSubnet1SubnetE62B1B9B', }, { Ref: 'VpcisolatedSubnet2Subnet39217055', }, ], }, }); // Assertion 3 expect(stack).toHaveResourceLike('AWS::SageMaker::Model', { ExecutionRoleArn: { 'Fn::GetAtt': ['testlambdasagemakerSagemakerRoleD84546B8', 'Arn'], }, PrimaryContainer: { Image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', ModelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, VpcConfig: { SecurityGroupIds: [ { 'Fn::GetAtt': ['testlambdasagemakerReplaceModelDefaultSecurityGroup7284AA24', 'GroupId'], }, ], Subnets: [ { Ref: 'VpcisolatedSubnet1SubnetE62B1B9B', }, { Ref: 'VpcisolatedSubnet2Subnet39217055', }, ], }, }); // Assertion 4 expect(stack).toHaveResourceLike('AWS::SageMaker::EndpointConfig', { ProductionVariants: [ { InitialInstanceCount: 1, InitialVariantWeight: 1, InstanceType: 'ml.m4.xlarge', ModelName: { 'Fn::GetAtt': ['testlambdasagemakerSagemakerModelEC3E4E39', 'ModelName'], }, VariantName: 'AllTraffic', }, ], KmsKeyId: { Ref: 'testlambdasagemakerEncryptionKey2AACF9E0', }, }); // Assertion 5 expect(stack).toHaveResourceLike('AWS::SageMaker::Endpoint', { EndpointConfigName: { 'Fn::GetAtt': ['testlambdasagemakerSagemakerEndpointConfig6BABA334', 'EndpointConfigName'], }, }); }); // ---------------------------------------------------------------------------------------------- // Pattern deployment with existing Lambda function, new Sagemaker endpoint and deployVpc = false // ---------------------------------------------------------------------------------------------- test('Pattern deployment with existing Lambda function, new Sagemaker endpoint, deployVpc = false', () => { // Initial Setup const stack = new Stack(); // deploy lambda function const fn = defaults.deployLambdaFunction(stack, { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, }); const constructProps: LambdaToSagemakerEndpointProps = { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, existingLambdaObj: fn, }; new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); expect(stack).toHaveResourceLike('AWS::SageMaker::Model', { ExecutionRoleArn: { 'Fn::GetAtt': ['testlambdasagemakerSagemakerRoleD84546B8', 'Arn'], }, PrimaryContainer: { Image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', ModelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }); // Assertion 3 expect(stack).toHaveResourceLike('AWS::Lambda::Function', { Environment: { Variables: { SAGEMAKER_ENDPOINT_NAME: { 'Fn::GetAtt': ['testlambdasagemakerSagemakerEndpoint12803730', 'EndpointName'], }, }, }, }); }); // ------------------------------------------------------------------------------------------------------------------ // Pattern deployment with new Lambda function, new Sagemaker endpoint, deployVpc = true, and custom role // ------------------------------------------------------------------------------------------------------------------ test('Pattern deployment with new Lambda function, new Sagemaker endpoint, deployVpc = true, and custom role', () => { // Initial Setup const stack = new Stack(); // Create IAM Role to be assumed by SageMaker const sagemakerRole = new iam.Role(stack, 'SagemakerRole', { assumedBy: new iam.ServicePrincipal('sagemaker.amazonaws.com'), }); sagemakerRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonSageMakerFullAccess')); const constructProps: LambdaToSagemakerEndpointProps = { modelProps: { executionRoleArn: sagemakerRole.roleArn, primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, deployVpc: true, lambdaFunctionProps: { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, }, }; new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); // Assertion 1 expect(stack).toHaveResourceLike('AWS::IAM::Role', { AssumeRolePolicyDocument: { Statement: [ { Action: 'sts:AssumeRole', Effect: 'Allow', Principal: { Service: 'sagemaker.amazonaws.com', }, }, ], Version: '2012-10-17', }, }); // Assertion 2: ReplaceDefaultSecurityGroup, ReplaceEndpointDefaultSecurityGroup, and ReplaceModelDefaultSecurityGroup expect(stack).toCountResources('AWS::EC2::SecurityGroup', 3); // Assertion 3 expect(stack).toCountResources('AWS::EC2::Subnet', 2); // Assertion 4 expect(stack).toCountResources('AWS::EC2::InternetGateway', 0); // Assertion 5: SAGEMAKER_RUNTIME VPC Interface expect(stack).toHaveResource('AWS::EC2::VPCEndpoint', { VpcEndpointType: 'Interface', }); // Assertion 6: S3 VPC Endpoint expect(stack).toHaveResource('AWS::EC2::VPCEndpoint', { VpcEndpointType: 'Gateway', }); // Assertion 7 expect(stack).toHaveResource('AWS::EC2::VPC', { EnableDnsHostnames: true, EnableDnsSupport: true, }); }); // --------------------------------------------------------------------------------- // Test for error when existing Lambda function does not have vpc and deployVpc = true // --------------------------------------------------------------------------------- test('Test for errot when existing Lambda function does not have vpc and deployVpc = true ', () => { // Initial Setup const stack = new Stack(); // deploy lambda function const fn = defaults.deployLambdaFunction(stack, { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, }); const constructProps: LambdaToSagemakerEndpointProps = { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, deployVpc: true, existingLambdaObj: fn, }; const app = () => { new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); }; // Assertion 1 expect(app).toThrowError(); }); // ------------------------------------------------------------------------------------------------------- // Pattern deployment with existing Lambda function (with VPC), new Sagemaker endpoint, and existingVpc // ------------------------------------------------------------------------------------------------------- test('Pattern deployment with existing Lambda function (with VPC), new Sagemaker endpoint, and existingVpc', () => { // Initial Setup const stack = new Stack(); const vpc = defaults.buildVpc(stack, { defaultVpcProps: defaults.DefaultIsolatedVpcProps(), constructVpcProps: { enableDnsHostnames: true, enableDnsSupport: true, }, }); // Add S3 VPC Gateway Endpint, required by Sagemaker to access Models artifacts via AWS private network defaults.AddAwsServiceEndpoint(stack, vpc, defaults.ServiceEndpointTypes.S3); // Add SAGEMAKER_RUNTIME VPC Interface Endpint, required by the lambda function to invoke the SageMaker endpoint defaults.AddAwsServiceEndpoint(stack, vpc, defaults.ServiceEndpointTypes.SAGEMAKER_RUNTIME); // deploy lambda function const fn = defaults.deployLambdaFunction(stack, { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, vpc, }); const constructProps: LambdaToSagemakerEndpointProps = { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, existingVpc: vpc, existingLambdaObj: fn, }; new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); // Assertion 2: ReplaceDefaultSecurityGroup, ReplaceEndpointDefaultSecurityGroup, and ReplaceModelDefaultSecurityGroup expect(stack).toCountResources('AWS::EC2::SecurityGroup', 3); // Assertion 3 expect(stack).toCountResources('AWS::EC2::Subnet', 2); // Assertion 4 expect(stack).toCountResources('AWS::EC2::InternetGateway', 0); // Assertion 5: SAGEMAKER_RUNTIME VPC Interface expect(stack).toHaveResource('AWS::EC2::VPCEndpoint', { VpcEndpointType: 'Interface', }); // Assertion 6: S3 VPC Endpoint expect(stack).toHaveResource('AWS::EC2::VPCEndpoint', { VpcEndpointType: 'Gateway', }); // Assertion 7 expect(stack).toHaveResource('AWS::EC2::VPC', { EnableDnsHostnames: true, EnableDnsSupport: true, }); }); // ----------------------------------------------------------------------------------------- // Test for error with existingLambdaObj/lambdaFunctionProps=undefined (not supplied by user) // ----------------------------------------------------------------------------------------- test('Test for error with existingLambdaObj/lambdaFunctionProps=undefined (not supplied by user)', () => { // Initial Setup const stack = new Stack(); const props: LambdaToSagemakerEndpointProps = { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, }; const app = () => { new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', props); }; // Assertion 1 expect(app).toThrowError(); }); // -------------------------------------------------------------------- // Test for error with (props.deployVpc && props.existingVpc) is true // -------------------------------------------------------------------- test('Test for error with (props.deployVpc && props.existingVpc) is true', () => { // Initial Setup const stack = new Stack(); const vpc = defaults.buildVpc(stack, { defaultVpcProps: defaults.DefaultIsolatedVpcProps(), constructVpcProps: { enableDnsHostnames: true, enableDnsSupport: true, }, }); // Add S3 VPC Gateway Endpint, required by Sagemaker to access Models artifacts via AWS private network defaults.AddAwsServiceEndpoint(stack, vpc, defaults.ServiceEndpointTypes.S3); // Add SAGEMAKER_RUNTIME VPC Interface Endpint, required by the lambda function to invoke the SageMaker endpoint defaults.AddAwsServiceEndpoint(stack, vpc, defaults.ServiceEndpointTypes.SAGEMAKER_RUNTIME); const constructProps: LambdaToSagemakerEndpointProps = { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, deployVpc: true, existingVpc: vpc, }; const app = () => { new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); }; // Assertion 1 expect(app).toThrowError(); }); // ---------------------------------------------------------------------------------------------------------- // Test for error with primaryContainer=undefined (not supplied by user), and no existingSageMakerEndpointObj // ---------------------------------------------------------------------------------------------------------- test('Test for error with primaryContainer=undefined (not supplied by user)', () => { // Initial Setup const stack = new Stack(); // deploy lambda function const fn = defaults.deployLambdaFunction(stack, { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, }); const constructProps: LambdaToSagemakerEndpointProps = { modelProps: {}, deployVpc: true, existingLambdaObj: fn, }; const app = () => { new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); }; // Assertion 1 expect(app).toThrowError(); }); // ------------------------------------------------------------------------------------------------- // Test getter methods: existing Lambda function (with VPC), new Sagemaker endpoint, and existingVpc // ------------------------------------------------------------------------------------------------- test('Test getter methods: existing Lambda function (with VPC), new Sagemaker endpoint, and existingVpc', () => { // Initial Setup const stack = new Stack(); const vpc = defaults.buildVpc(stack, { defaultVpcProps: defaults.DefaultIsolatedVpcProps(), constructVpcProps: { enableDnsHostnames: true, enableDnsSupport: true, }, }); // Add S3 VPC Gateway Endpint, required by Sagemaker to access Models artifacts via AWS private network defaults.AddAwsServiceEndpoint(stack, vpc, defaults.ServiceEndpointTypes.S3); // Add SAGEMAKER_RUNTIME VPC Interface Endpint, required by the lambda function to invoke the SageMaker endpoint defaults.AddAwsServiceEndpoint(stack, vpc, defaults.ServiceEndpointTypes.SAGEMAKER_RUNTIME); // deploy lambda function const fn = defaults.deployLambdaFunction(stack, { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, vpc, }); const constructProps: LambdaToSagemakerEndpointProps = { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, existingVpc: vpc, existingLambdaObj: fn, }; const app = new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); // Assertions expect(app.lambdaFunction).toBeDefined(); expect(app.sagemakerEndpoint).toBeDefined(); expect(app.sagemakerEndpointConfig).toBeDefined(); expect(app.sagemakerModel).toBeDefined(); expect(app.vpc).toBeDefined(); }); // -------------------------------------------------------------------------------------------- // Test getter methods: new Lambda function, existingSagemakerendpointObj (no vpc) // -------------------------------------------------------------------------------------------- test('Test getter methods: new Lambda function, existingSagemakerendpointObj (no vpc)', () => { // Initial Setup const stack = new Stack(); const [sagemakerEndpoint] = defaults.deploySagemakerEndpoint(stack, { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, }); const constructProps: LambdaToSagemakerEndpointProps = { existingSagemakerEndpointObj: sagemakerEndpoint, lambdaFunctionProps: { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, }, }; const app = new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); // Assertions expect(app.lambdaFunction).toBeDefined(); expect(app.sagemakerEndpoint).toBeDefined(); expect(app.sagemakerEndpointConfig).toBeUndefined(); expect(app.sagemakerModel).toBeUndefined(); expect(app.vpc).toBeUndefined(); }); // -------------------------------------------------------------------------------------------- // Test getter methods: new Lambda function, existingSagemakerendpointObj and deployVpc = true // -------------------------------------------------------------------------------------------- test('Test getter methods: new Lambda function, existingSagemakerendpointObj and deployVpc = true', () => { // Initial Setup const stack = new Stack(); const [sagemakerEndpoint] = defaults.deploySagemakerEndpoint(stack, { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, }); const constructProps: LambdaToSagemakerEndpointProps = { existingSagemakerEndpointObj: sagemakerEndpoint, lambdaFunctionProps: { runtime: lambda.Runtime.PYTHON_3_8, code: lambda.Code.fromAsset(`${__dirname}/lambda`), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, }, deployVpc: true, }; const app = new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', constructProps); // Assertions expect(app.lambdaFunction).toBeDefined(); expect(app.sagemakerEndpoint).toBeDefined(); expect(app.sagemakerEndpointConfig).toBeUndefined(); expect(app.sagemakerModel).toBeUndefined(); expect(app.vpc).toBeDefined(); }); // -------------------------------------------------------------- // Test lambda function custom environment variable // -------------------------------------------------------------- test('Test lambda function custom environment variable', () => { // Stack const stack = new Stack(); // Helper declaration const [sagemakerEndpoint] = defaults.deploySagemakerEndpoint(stack, { modelProps: { primaryContainer: { image: '<AccountId>.dkr.ecr.<region>.amazonaws.com/linear-learner:latest', modelDataUrl: 's3://<bucket-name>/<prefix>/model.tar.gz', }, }, }); new LambdaToSagemakerEndpoint(stack, 'test-lambda-sagemaker', { existingSagemakerEndpointObj: sagemakerEndpoint, lambdaFunctionProps: { runtime: lambda.Runtime.PYTHON_3_8, handler: 'index.handler', code: lambda.Code.fromAsset(`${__dirname}/lambda`), }, sagemakerEnvironmentVariableName: 'CUSTOM_SAGEMAKER_ENDPOINT' }); // Assertion expect(stack).toHaveResource('AWS::Lambda::Function', { Handler: 'index.handler', Runtime: 'python3.8', Environment: { Variables: { CUSTOM_SAGEMAKER_ENDPOINT: { 'Fn::GetAtt': [ 'SagemakerEndpoint', 'EndpointName' ] } } } }); });
the_stack
import { BlocksoftBlockchainTypes } from '../../BlocksoftBlockchainTypes' import DogeUnspentsProvider from '../../doge/providers/DogeUnspentsProvider' import Database from '@app/appstores/DataSource/Database'; import BlocksoftCryptoLog from '../../../common/BlocksoftCryptoLog' import BlocksoftDict from '@crypto/common/BlocksoftDict' import main from '@app/appstores/DataSource/Database' const CACHE_FOR_CHANGE = {} export default class BtcUnspentsProvider extends DogeUnspentsProvider implements BlocksoftBlockchainTypes.UnspentsProvider { static async getCache(walletHash : string, currencyCode = 'BTC') { if (typeof CACHE_FOR_CHANGE[walletHash] !== 'undefined') { return CACHE_FOR_CHANGE[walletHash] } const mainCurrencyCode = currencyCode === 'LTC' ? 'LTC' : 'BTC' const segwitPrefix = BlocksoftDict.CurrenciesForTests[mainCurrencyCode + '_SEGWIT'].addressPrefix BlocksoftCryptoLog.log(currencyCode + ' ' + mainCurrencyCode + ' BtcUnspentsProvider.getCache ' + walletHash + ' started as ' + JSON.stringify(CACHE_FOR_CHANGE[walletHash])) const sqlPub = `SELECT wallet_pub_value as walletPub FROM wallet_pub WHERE wallet_hash = '${walletHash} AND currency_code='${mainCurrencyCode}' ` const resPub = await Database.query(sqlPub) if (resPub && resPub.array && resPub.array.length > 0) { const sql = `SELECT account.address FROM account WHERE account.wallet_hash = '${walletHash} AND currency_code='${mainCurrencyCode}' AND (already_shown IS NULL OR already_shown=0) AND derivation_type!='main' ORDER BY derivation_index ASC ` const res = await Database.query(sql) for (const row of res.array) { const prefix = row.address.indexOf(segwitPrefix) === 0 ? segwitPrefix : row.address.substr(0, 1) await BlocksoftCryptoLog.log(currencyCode + ' ' + mainCurrencyCode + ' BtcUnspentsProvider.getCache started HD CACHE_FOR_CHANGE ' + walletHash) // @ts-ignore if (typeof CACHE_FOR_CHANGE[walletHash] === 'undefined') { // @ts-ignore CACHE_FOR_CHANGE[walletHash] = {} } // @ts-ignore if (typeof CACHE_FOR_CHANGE[walletHash][prefix] === 'undefined' || CACHE_FOR_CHANGE[walletHash][prefix] === '') { // @ts-ignore CACHE_FOR_CHANGE[walletHash][prefix] = row.address // @ts-ignore await BlocksoftCryptoLog.log(currencyCode + ' ' + mainCurrencyCode + ' BtcUnspentsProvider.getCache started HD CACHE_FOR_CHANGE ' + walletHash + ' ' + prefix + ' changed ' + JSON.stringify(CACHE_FOR_CHANGE[walletHash])) } } } else { const sql = `SELECT account.address FROM account WHERE account.wallet_hash = '${walletHash}' AND currency_code='${mainCurrencyCode}' ` const res = await Database.query(sql) for (const row of res.array) { // @ts-ignore await BlocksoftCryptoLog.log(currencyCode + '/' + mainCurrencyCode + ' BtcUnspentsProvider.getUnspents started CACHE_FOR_CHANGE ' + walletHash) if (typeof CACHE_FOR_CHANGE[walletHash] === 'undefined') { // @ts-ignore CACHE_FOR_CHANGE[walletHash] = {} } const prefix = row.address.indexOf(segwitPrefix) === 0 ? segwitPrefix : row.address.substr(0, 1) // @ts-ignore CACHE_FOR_CHANGE[walletHash][prefix] = row.address } } if (typeof CACHE_FOR_CHANGE[walletHash] === 'undefined') { throw new Error(currencyCode + '/' + mainCurrencyCode + ' BtcUnspentsProvider no CACHE_FOR_CHANGE retry for ' + walletHash) } return CACHE_FOR_CHANGE[walletHash] } _isMyAddress(voutAddress: string, address: string, walletHash: string): string { // @ts-ignore if (typeof CACHE_FOR_CHANGE[walletHash] === 'undefined' || !CACHE_FOR_CHANGE[walletHash]) { return '' } // @ts-ignore let found = '' for (const key in CACHE_FOR_CHANGE[walletHash]) { BlocksoftCryptoLog.log('CACHE_FOR_CHANGE[walletHash][key]', key + '_' + CACHE_FOR_CHANGE[walletHash][key]) if (voutAddress === CACHE_FOR_CHANGE[walletHash][key]) { found = voutAddress } } return found } async getUnspents(address: string): Promise<BlocksoftBlockchainTypes.UnspentTx[]> { const mainCurrencyCode = this._settings.currencyCode === 'LTC' ? 'LTC' : 'BTC' const segwitPrefix = BlocksoftDict.CurrenciesForTests[mainCurrencyCode + '_SEGWIT'].addressPrefix const sqlPub = `SELECT wallet_pub_value as walletPub FROM wallet_pub WHERE wallet_hash = (SELECT wallet_hash FROM account WHERE address='${address}') AND currency_code='${mainCurrencyCode}' ` const totalUnspents = [] const resPub = await Database.query(sqlPub) if (resPub && resPub.array && resPub.array.length > 0) { for (const row of resPub.array) { const unspents = await super.getUnspents(row.walletPub) if (unspents) { for (const unspent of unspents) { totalUnspents.push(unspent) } } } const sqlAdditional = `SELECT account.address, account.derivation_path as derivationPath, wallet_hash AS walletHash FROM account WHERE account.wallet_hash = (SELECT wallet_hash FROM account WHERE address='${address}') AND account.derivation_path = 'm/49quote/0quote/0/1/0' AND currency_code='${mainCurrencyCode}' ` const resAdditional = await Database.query(sqlAdditional) if (resAdditional && resAdditional.array && resAdditional.array.length > 0) { for (const row of resAdditional.array) { const unspents = await super.getUnspents(row.address) if (unspents) { for (const unspent of unspents) { unspent.address = row.address unspent.derivationPath = Database.unEscapeString(row.derivationPath) totalUnspents.push(unspent) } } } } const sql = `SELECT account.address, account.derivation_path as derivationPath, wallet_hash AS walletHash FROM account WHERE account.wallet_hash = (SELECT wallet_hash FROM account WHERE address='${address}') AND currency_code='${mainCurrencyCode}' AND (already_shown IS NULL OR already_shown=0) AND derivation_type!='main' ORDER BY derivation_index ASC ` const res = await Database.query(sql) for (const row of res.array) { const walletHash = row.walletHash const prefix = row.address.indexOf(segwitPrefix) === 0 ? segwitPrefix : row.address.substr(0, 1) await BlocksoftCryptoLog.log(this._settings.currencyCode + ' ' + mainCurrencyCode + ' BtcUnspentsProvider.getUnspents started HD CACHE_FOR_CHANGE ' + address + ' walletHash ' + walletHash) // @ts-ignore if (typeof CACHE_FOR_CHANGE[walletHash] === 'undefined') { // @ts-ignore CACHE_FOR_CHANGE[walletHash] = {} } // @ts-ignore if (typeof CACHE_FOR_CHANGE[walletHash][prefix] === 'undefined' || CACHE_FOR_CHANGE[walletHash][prefix] === '') { // @ts-ignore CACHE_FOR_CHANGE[walletHash][prefix] = row.address // @ts-ignore await BlocksoftCryptoLog.log(this._settings.currencyCode + ' ' + mainCurrencyCode + ' BtcUnspentsProvider.getUnspents started HD CACHE_FOR_CHANGE ' + address + ' walletHash ' + walletHash + ' ' + prefix + ' changed ' + JSON.stringify(CACHE_FOR_CHANGE[walletHash])) } } } else { const sql = `SELECT account.address, account.derivation_path as derivationPath, wallet_hash AS walletHash FROM account WHERE account.wallet_hash = (SELECT wallet_hash FROM account WHERE address='${address}') AND currency_code='${mainCurrencyCode}' ` const res = await Database.query(sql) for (const row of res.array) { const walletHash = row.walletHash const unspents = await super.getUnspents(row.address) // @ts-ignore await BlocksoftCryptoLog.log(this._settings.currencyCode + '/' + mainCurrencyCode + ' BtcUnspentsProvider.getUnspents started CACHE_FOR_CHANGE ' + address + ' ' + row.address + ' walletHash ' + walletHash) if (typeof CACHE_FOR_CHANGE[walletHash] === 'undefined') { // @ts-ignore CACHE_FOR_CHANGE[walletHash] = {} } const prefix = row.address.indexOf(segwitPrefix) === 0 ? segwitPrefix : row.address.substr(0, 1) // @ts-ignore CACHE_FOR_CHANGE[walletHash][prefix] = row.address if (unspents) { for (const unspent of unspents) { unspent.address = row.address unspent.derivationPath = Database.unEscapeString(row.derivationPath) totalUnspents.push(unspent) } } } } // @ts-ignore await BlocksoftCryptoLog.log(this._settings.currencyCode + ' ' + mainCurrencyCode + ' BtcUnspentsProvider.getUnspents finished ' + address, totalUnspents) return totalUnspents } }
the_stack
import { ViewBasedJSONModel } from './viewbasedjsonmodel'; import { toArray, filter } from '@lumino/algorithm'; import { Transform } from './transform'; import * as moment from 'moment'; /** * An object that defines a data transformation executor. */ export abstract class TransformExecutor { /** * Apply a transformation to the provided data, then return a new copy. */ abstract apply(input: TransformExecutor.IData): TransformExecutor.IData; } /** * The namespace for the `Transform` class statics. */ export namespace TransformExecutor { /** * A read only type for the input/output of .apply(). */ export type IData = Readonly<ViewBasedJSONModel.IData>; } /** * A transformation that filters a single field by the provided operator and * value. * * Note: This is a WIP */ export class FilterExecutor extends TransformExecutor { /** * Create a new transformation. * * @param options - The options for initializing the transformation. */ constructor(options: FilterExecutor.IOptions) { super(); this._options = options; } /** * Apply a transformation to the provided data. * * @param input - The data to be operated on. */ public apply(input: TransformExecutor.IData): TransformExecutor.IData { let filterFunc: any; switch (this._options.operator) { case '>': filterFunc = (item: any) => { if (['date', 'datetime', 'time'].includes(this._options.dType)) { const target = moment.default.utc(item[this._options.field]); const value = moment.default.utc(this._options.value); return target.isAfter(value, 'day'); } return item[this._options.field] > this._options.value; }; break; case '<': filterFunc = (item: any) => { if (['date', 'datetime', 'time'].includes(this._options.dType)) { const target = moment.default.utc(item[this._options.field]); const value = moment.default.utc(this._options.value); return target.isBefore(value, 'day'); } return item[this._options.field] < this._options.value; }; break; case '<=': filterFunc = (item: any) => { if (['date', 'datetime', 'time'].includes(this._options.dType)) { const target = moment.default.utc(item[this._options.field]); const value = moment.default.utc(this._options.value); return target.isSameOrBefore(value, 'day'); } return item[this._options.field] <= this._options.value; }; break; case '>=': filterFunc = (item: any) => { if (['date', 'datetime', 'time'].includes(this._options.dType)) { const target = moment.default.utc(item[this._options.field]); const value = moment.default.utc(this._options.value); return target.isSameOrAfter(value, 'day'); } return item[this._options.field] >= this._options.value; }; break; case '=': filterFunc = (item: any) => { if (['date', 'datetime', 'time'].includes(this._options.dType)) { const target = moment.default.utc(item[this._options.field]); const value = moment.default.utc(this._options.value); return target.isSame(value); } return item[this._options.field] == this._options.value; }; break; case '!=': filterFunc = (item: any) => { if (['date', 'datetime', 'time'].includes(this._options.dType)) { const target = moment.default.utc(item[this._options.field]); const value = moment.default.utc(this._options.value); return !target.isSame(value); } return item[this._options.field] !== this._options.value; }; break; case 'empty': filterFunc = (item: any) => { return item[this._options.field] === null; }; break; case 'notempty': filterFunc = (item: any) => { return item[this._options.field] !== null; }; break; case 'in': filterFunc = (item: any) => { const values = <any[]>this._options.value; return values.includes(item[this._options.field]); }; break; case 'between': filterFunc = (item: any) => { const values = <any[]>this._options.value; if (['date', 'datetime', 'time'].includes(this._options.dType)) { const target = moment.default.utc(item[this._options.field]); const lowValue = moment.default.utc(values[0]); const highValue = moment.default.utc(values[1]); return target.isBetween(lowValue, highValue, 'day'); } return ( item[this._options.field] > values[0] && item[this._options.field] < values[1] ); }; break; case 'startswith': filterFunc = (item: any) => { return item[this._options.field].startsWith(this._options.value); }; break; case 'endswith': filterFunc = (item: any) => { return item[this._options.field].endsWith(this._options.value); }; break; case 'stringContains': filterFunc = (item: any) => { return String(item[this._options.field]) .toLowerCase() .includes(String(this._options.value).toLowerCase()); }; break; case 'contains': filterFunc = (item: any) => { return item[this._options.field].includes(this._options.value); }; break; case '!contains': filterFunc = (item: any) => { return !item[this._options.field].includes(this._options.value); }; break; case 'isOnSameDay': filterFunc = (item: any) => { const target = moment.default.utc(item[this._options.field]); const value = moment.default.utc(this._options.value); return target.isSame(value, 'day'); }; break; default: throw 'unreachable'; } return { schema: input.schema, data: toArray(filter(input.data, filterFunc)), }; } protected _options: FilterExecutor.IOptions; } /** * The namespace for the `FilterExecutor` class statics. */ export namespace FilterExecutor { /** * An options object for initializing a Filter. */ export interface IOptions { /** * The name of the field in the data source. */ field: string; /** * The data type of the column associated with this transform. */ dType: string; /** * The operator to use for the comparison. */ operator: Transform.FilterOperator; /** * The value(s) to filter by. */ value: string | string[] | number | number[]; } } /** * A transformation that sorts the provided data by the provided field. * * Note: This is a WIP */ export class SortExecutor extends TransformExecutor { /** * Creates a new sort transformation * * @param options - The options for initializing the transformation. */ constructor(options: SortExecutor.IOptions) { super(); this._options = options; } /** * Apply a transformation to the provided data. * * Note: Currently ignores the `desc` parameter. * * @param input - The data to be operated on. */ public apply(input: TransformExecutor.IData): TransformExecutor.IData { let sortFunc: (a: any, b: any) => number; const field = this._options.field; const columnDataType = this._options.dType; // Adding string checks within the sort function so we do // not have to mutate in-place the original types of the // values of the column into strings. This allows the // displayed values to maintain their original types but // be sorted as if they were all strings. const stringifyIfNeeded = (value: any) => { if (typeof value != 'string') { return String(value); } return value; }; if (columnDataType == 'string') { if (this._options.desc) { sortFunc = (a: any, b: any): number => { return stringifyIfNeeded(a[field]) < stringifyIfNeeded(b[field]) ? 1 : -1; }; } else { sortFunc = (a: any, b: any): number => { return stringifyIfNeeded(a[field]) > stringifyIfNeeded(b[field]) ? 1 : -1; }; } } else { if (this._options.desc) { sortFunc = (a: any, b: any): number => { return a[field] < b[field] ? 1 : -1; }; } else { sortFunc = (a: any, b: any): number => { return a[field] > b[field] ? 1 : -1; }; } } const data = input.data.slice(0); const sortables: any[] = [], notSortables: any[] = []; data.forEach((value: any) => { const cellValue = value[field]; const notSortable = cellValue === null || (typeof cellValue === 'number' && Number.isNaN(cellValue)) || (cellValue instanceof Date && Number.isNaN(cellValue.getTime())); if (notSortable) { notSortables.push(value); } else { sortables.push(value); } }); return { schema: input.schema, data: sortables.sort(sortFunc).concat(notSortables), }; } protected _options: SortExecutor.IOptions; } /** * The namespace for the `SortExecutor` class statics. */ export namespace SortExecutor { /** * An options object for initializing a Sort. */ export interface IOptions { /** * The name of the field in the data source. */ field: string; /** * The data type of the column associated with this transform. */ dType: string; /** * Indicates ascending or descending order for the sort. */ desc: boolean; } } export namespace Private { export type JSONDate = 'date' | 'time' | 'datetime'; }
the_stack
import * as vscode from 'vscode'; import {BaseView} from '../../views/baseview'; import {ZSimRemote} from './zsimremote'; import {Settings} from '../../settings'; import {Utility} from '../../misc/utility'; import {LogCustomCode} from '../../log'; import {GlobalStorage} from '../../globalstorage'; import {readFileSync} from 'fs'; import {DiagnosticsHandler} from '../../diagnosticshandler'; /** * A Webview that shows the simulated peripherals. * E.g. in case of the Spectrum the ULA screen or the keyboard. */ export class ZSimulationView extends BaseView { // The max. number of message in the queue. If reached the ZSimulationView will ask // for processing time. static MESSAGE_HIGH_WATERMARK = 100; static MESSAGE_LOW_WATERMARK = 10; // A map to hold the values of the simulated ports. protected simulatedPorts: Map<number, number>; // Port <-> value // A pointer to the simulator. protected simulator: ZSimRemote; // Taken from Settings. Path to the extra javascript code. protected customUiPath: string; // Counts the number of outstanding (not processed) webview messages. // Is used to insert "pauses" so that the webview can catch up. protected countOfOutstandingMessages: number; // The time interval to update the simulation view. protected displayTime: number; // The timer used for updating the display. protected displayTimer: NodeJS.Timeout; // The timeout (with no CPU activity) before a 'cpuStopped' is sent to the webview. protected stopTime: number; // The timer used for the stop time. protected stopTimer: NodeJS.Timeout; // Set by the display timer: the next time an update will happen. protected nextUpdateTime: number; // Set by the vertSync event: The last sync time. protected lastVertSyncTime: number; // Stores the last T-states value. // Used to check for changes. protected previousTstates: number; /** * Creates the basic view. * @param memory The memory of the CPU. */ constructor(simulator: ZSimRemote) { super(false); // Init this.simulator = simulator; this.countOfOutstandingMessages = 0; this.displayTime = 1000 / Settings.launch.zsim.updateFrequency; this.displayTimer = undefined as any; this.displayTime = 1000 / Settings.launch.zsim.updateFrequency; this.displayTimer = undefined as any; this.stopTime = 2 * this.displayTime; if (this.stopTime < 500) this.stopTime = 500; // At least 500 ms this.stopTimer = undefined as any; this.previousTstates = -1; // ZX Keyboard? this.simulatedPorts = new Map<number, number>(); if (Settings.launch.zsim.zxKeyboard) { // Prepare all used ports this.simulatedPorts.set(0xFEFE, 0xFF); this.simulatedPorts.set(0xFDFE, 0xFF); this.simulatedPorts.set(0xFBFE, 0xFF); this.simulatedPorts.set(0xF7FE, 0xFF); this.simulatedPorts.set(0xEFFE, 0xFF); this.simulatedPorts.set(0xDFFE, 0xFF); this.simulatedPorts.set(0xBFFE, 0xFF); this.simulatedPorts.set(0x7FFE, 0xFF); } else { // If keyboard id not defined, check for ZX Interface 2 if (Settings.launch.zsim.zxInterface2Joy) { // Prepare all used ports this.simulatedPorts.set(0xF7FE, 0xFF); // Joystick 2 (left): Bits: xxxLRDUF, low active, keys 1-5 this.simulatedPorts.set(0xEFFE, 0xFF); // Joystick 1 (right): Bits: xxxFUDRL, low active, keys 6-0 // Set call backs for (const [simPort,] of this.simulatedPorts) { this.simulator.ports.registerSpecificInPortFunction(simPort, (port: number) => { const value = this.simulatedPorts.get(port)!; return value; }); } } } // Check for Kempston Joystick if (Settings.launch.zsim.kempstonJoy) { // Prepare port: Port 0x001f, 000FUDLR, Active = 1 this.simulatedPorts.set(0x001F, 0x00); } // Set callbacks for all simulated ports. for (const [simPort,] of this.simulatedPorts) { this.simulator.ports.registerSpecificInPortFunction(simPort, (port: number) => { const value = this.simulatedPorts.get(port)!; return value; }); } // Add title Utility.assert(this.vscodePanel); this.vscodePanel.title = 'Z80 Simulator - ' + Settings.launch.zsim.memoryModel; // Read path for additional javascript code this.customUiPath = Settings.launch.zsim.customCode.uiPath; // Initial html page. this.setHtml(); // Inform custom code that UI is ready. this.simulator.customCode?.uiReady(); // Check if simulator restored this.simulator.on('restored', () => { // Change previous t-states to force an update. this.previousTstates = -1; }); // Close this.simulator.once('closed', () => { this.close(); }); // Handle vertical sync this.simulator.on('vertSync', async (reason) => { this.vertSync(); }); // Handle custom code messages this.simulator.customCode?.on('sendToCustomUi', (message: any) => { LogCustomCode.log('UI: UIAPI.receivedFromCustomLogic: ' + JSON.stringify(message)); // Wrap message from custom code const outerMsg = { command: 'receivedFromCustomLogic', value: message }; this.sendMessageToWebView(outerMsg); }); // Update regularly this.startDisplayTimer(); // Update once initially //this.updateDisplay(); } /** * Starts the stop timer. * Some time after the last CPU activity has been found a 'cpuStopped' * is sent to the webview to e.g. shutdown audio. */ protected restartStopTimer() { // Update on timer clearInterval(this.stopTimer); // Start timer this.stopTimer = setTimeout(() => { // Send stop to audio in webview this.sendMessageToWebView({command: 'cpuStopped'}); this.stopTimer = undefined as any; }, this.stopTime); // in ms } /** * Starts the display timer. */ protected startDisplayTimer() { // Update on timer clearInterval(this.displayTimer); // Get current time const nowTime = Date.now(); this.lastVertSyncTime = nowTime; this.nextUpdateTime = nowTime + this.displayTime; // Start timer this.displayTimer = setInterval(() => { //Log.log("timer: do update"); // Update this.updateDisplay(); // Get current time const currentTime = Date.now(); this.lastVertSyncTime = currentTime; this.nextUpdateTime = currentTime + this.displayTime; }, this.displayTime); // in ms } /** * A vertical sync was received from the Z80 simulation. * Is used to sync the display as best as possible: * On update the next time is stored (nextUpdateTime). * The lastVertSyncTime is stored with the current time. * On next vert sync the diff to lastVertSyncTime is calculated and extrapolated. * If the next time would be later as the next regular update, then the update is * done earlier and the timer restarted. * I.e. the last vert sync before the regular update is used for synched display. */ protected vertSync() { //Log.log("vertSync"); // Get current time const currentTime = Date.now(); // Diff to last vertical sync const diff = currentTime - this.lastVertSyncTime; this.lastVertSyncTime = currentTime; // Extrapolate if (currentTime + diff > this.nextUpdateTime) { //Log.log("vertSync: do update"); // Do the update earlier, now at the vert sync this.updateDisplay(); // Restart timer this.startDisplayTimer(); } } /** * Closes the view. */ public close() { this.vscodePanel.dispose(); } /** * Dispose the view (called e.g. on close). * Use this to clean up additional stuff. * Normally not required. */ public disposeView() { clearInterval(this.displayTimer); this.displayTimer = undefined as any; } /** * The web view posted a message to this view. * @param message The message. message.command contains the command as a string. E.g. 'keyChanged' */ protected async webViewMessageReceived(message: any) { switch (message.command) { case 'warning': // A warning has been received, e.g. sample rate was not possible. const warningText = message.text; vscode.window.showWarningMessage(warningText); break; case 'keyChanged': this.keyChanged(message.key, message.value); break; case 'volumeChanged': GlobalStorage.Set('audio.volume', message.value); break; case 'portBit': this.setPortBit(message.value.port, message.value.on, message.value.bitByte); break; case 'sendToCustomLogic': // Unwrap message const innerMsg = message.value; LogCustomCode.log("UI: UIAPI.sendToCustomLogic: " + JSON.stringify(innerMsg)); this.sendToCustomLogic(innerMsg); break; case 'reloadCustomLogicAndUi': // Clear any diagnostics DiagnosticsHandler.clear(); // Reload the custom code const jsPath = Settings.launch.zsim.customCode?.jsPath; if (jsPath) { // Can throw an error this.simulator.customCode.load(jsPath); this.simulator.customCode.execute(); } // Reload the custom UI code this.setHtml(); // Inform custom code that UI is ready. this.simulator.customCode?.uiReady(); break; case 'log': // Log a message const text = message.args.map(elem => elem.toString()).join(', '); LogCustomCode.log("UI: " + text); break; case 'countOfProcessedMessages': // For balancing the number of processed messages (since last time) is provided.; this.countOfOutstandingMessages -= message.value; Utility.assert(this.countOfOutstandingMessages >= 0); // For balancing: Remove request for procesing time if (this.countOfOutstandingMessages <= ZSimulationView.MESSAGE_LOW_WATERMARK) { this.simulator.setTimeoutRequest(false); } break; default: await super.webViewMessageReceived(message); break; } } /** * A message is posted to the web view. * Overwritten to count the number of messages for balancing. * @param message The message. message.command should contain the command as a string. * This needs to be evaluated inside the web view. * @param baseView The webview to post to. Can be omitted, default is 'this'. */ protected sendMessageToWebView(message: any, baseView: BaseView = this) { this.countOfOutstandingMessages++; super.sendMessageToWebView(message, baseView); // For balancing: Ask for processing time if messages cannot be processed in time. if (this.countOfOutstandingMessages >= ZSimulationView.MESSAGE_HIGH_WATERMARK) { this.simulator.setTimeoutRequest(true); } } /** * Called if the custom UI code wants to send something to the custom logic/the javascript code. */ protected sendToCustomLogic(msg: any) { this.simulator.customCode?.receivedFromCustomUi(msg); } /** * Called on key press or key release. * Sets/clears the corresponding port bits. * @param key E.g. "key_Digit2", "key_KeyQ", "key_Enter", "key_Space", "key_ShiftLeft" (CAPS) or "key_ShiftRight" (SYMBOL). * @param on true=pressed, false=released */ protected keyChanged(key: string, on: boolean) { // Determine port let port; switch (key) { case 'key_Digit1': case 'key_Digit2': case 'key_Digit3': case 'key_Digit4': case 'key_Digit5': port = 0xF7FE; break; case 'key_Digit6': case 'key_Digit7': case 'key_Digit8': case 'key_Digit9': case 'key_Digit0': port = 0xEFFE; break; case 'key_KeyQ': case 'key_KeyW': case 'key_KeyE': case 'key_KeyR': case 'key_KeyT': port = 0xFBFE; break; case 'key_KeyY': case 'key_KeyU': case 'key_KeyI': case 'key_KeyO': case 'key_KeyP': port = 0xDFFE; break; case 'key_KeyA': case 'key_KeyS': case 'key_KeyD': case 'key_KeyF': case 'key_KeyG': port = 0xFDFE; break; case 'key_KeyH': case 'key_KeyJ': case 'key_KeyK': case 'key_KeyL': case 'key_Enter': port = 0xBFFE; break; case 'key_ShiftLeft': // CAPS case 'key_KeyZ': case 'key_KeyX': case 'key_KeyC': case 'key_KeyV': port = 0xFEFE; break; case 'key_KeyB': case 'key_KeyN': case 'key_KeyM': case 'key_ShiftRight': // SYMBOL case 'key_Space': port = 0x7FFE; break; default: Utility.assert(false); } Utility.assert(port); // Determine bit let bit; switch (key) { case 'key_ShiftLeft': // CAPS case 'key_KeyA': case 'key_KeyQ': case 'key_Digit1': case 'key_Digit0': case 'key_KeyP': case 'key_Enter': case 'key_Space': bit = 0b00001; break; case 'key_KeyZ': case 'key_KeyS': case 'key_KeyW': case 'key_Digit2': case 'key_Digit9': case 'key_KeyO': case 'key_KeyL': case 'key_ShiftRight': // SYMBOL bit = 0b00010; break; case 'key_KeyX': case 'key_KeyD': case 'key_KeyE': case 'key_Digit3': case 'key_Digit8': case 'key_KeyI': case 'key_KeyK': case 'key_KeyM': bit = 0b00100; break; case 'key_KeyC': case 'key_KeyF': case 'key_KeyR': case 'key_Digit4': case 'key_Digit7': case 'key_KeyU': case 'key_KeyJ': case 'key_KeyN': bit = 0b01000; break; case 'key_KeyV': case 'key_KeyG': case 'key_KeyT': case 'key_Digit5': case 'key_Digit6': case 'key_KeyY': case 'key_KeyH': case 'key_KeyB': bit = 0b10000; break; default: Utility.assert(false); } Utility.assert(bit); // Get port value Utility.assert(this.simulatedPorts); let value = this.simulatedPorts.get(port)!; Utility.assert(value != undefined); if (on) value &= ~bit; else value |= bit; // And set this.simulatedPorts.set(port, value); } /** * Called if a bit for a port should change. * @param port The port number. * @param on true = bit should be set, false = bit should be cleared * @param bitByte A byte with the right bit set. */ protected setPortBit(port: number, on: boolean, bitByte: number) { // Get port value Utility.assert(this.simulatedPorts); let value = this.simulatedPorts.get(port)!; Utility.assert(value != undefined); if (on) value |= bitByte; else value &= ~bitByte; // And set this.simulatedPorts.set(port, value); } /** * Retrieves the screen memory content and displays it. * @param reason Not used. */ public updateDisplay() { // Check if CPU did something const tStates = this.simulator.getPassedTstates(); if (this.previousTstates == tStates) return; this.previousTstates = tStates; this.restartStopTimer(); try { let cpuLoad; let slots; let slotNames; let visualMem; let screenImg; let audio; let borderColor; // Update values if (Settings.launch.zsim.cpuLoadInterruptRange > 0) cpuLoad = (this.simulator.z80Cpu.cpuLoad * 100).toFixed(0).toString(); // Visual Memory if (Settings.launch.zsim.visualMemory) { slots = this.simulator.getSlots(); const banks = this.simulator.memoryModel.getMemoryBanks(slots); slotNames = banks.map(bank => bank.name); visualMem = this.simulator.memory.getVisualMemory(); } if (Settings.launch.zsim.ulaScreen) { // A time in ms which is used for the flashing of the color attributes. The flash frequency is 1.6Hz = 625ms. const time = this.simulator.getTstatesSync() / this.simulator.getCpuFrequencySync() * 1000; const ulaData = this.simulator.getUlaScreen(); screenImg = { time, ulaData }; } if (Settings.launch.zsim.zxBorderWidth > 0) { // Get the border and set it. borderColor = this.simulator.getZxBorderColor(); } if (Settings.launch.zsim.zxBeeper) { // Audio audio = this.simulator.getZxBeeperBuffer(); } // Create message to update the webview const message = { command: 'update', cpuLoad, slotNames, visualMem, screenImg, borderColor, audio }; this.sendMessageToWebView(message); // Clear this.simulator.memory.clearVisualMemory(); } catch {} } /** * Sets the html code to display the ula screen, visual memory etc. * Depending on the Settings selection. */ protected setHtml() { // Resource path const extPath = Utility.getExtensionPath(); const resourcePath = vscode.Uri.file(extPath); const vscodeResPath = this.vscodePanel.webview.asWebviewUri(resourcePath).toString(); let html = ` <head> <meta charset="utf-8"> <base href="${vscodeResPath}/"> </head> <html> <style> .td_on {border: 3px solid; margin:0em; padding:0em; text-align:center; border-color:black; background:red; width:70px; } .td_off {border: 3px solid; margin:0em; padding:0em; text-align:center; border-color:black; width:70px; } </style> <script> const exports = {}; </script> <script src="out/src/remotes/zsimulator/zsimwebview/zxaudiobeeper.js"></script> <script src="out/src/remotes/zsimulator/zsimwebview/ulascreen.js"></script> <script src="out/src/remotes/zsimulator/zsimwebview/visualmem.js"></script> <script src="out/src/remotes/zsimulator/zsimwebview/helper.js"></script> <script src="out/src/remotes/zsimulator/zsimwebview/main.js"></script> <body> `; // CPU Load if (Settings.launch.zsim.cpuLoadInterruptRange > 0) { html += `<!-- Z80 CPU load --> <p> <label>Z80 CPU load:</label> <label id="cpu_load_id">100</label> <label>%</label> </p> <script> <!-- Store the cpu_load_id --> const cpuLoad=document.getElementById("cpu_load_id"); </script> `; } // Memory Pages / Visual Memory if (Settings.launch.zsim.visualMemory) { const zx = Settings.launch.zsim.memoryModel.includes("ZX"); const slots = this.simulator.getSlots(); const banks = this.simulator.memoryModel.getMemoryBanks(slots); html += `<!-- Visual Memory (memory activity) --> <!-- Legend, Slots --> <div style="position:relative; width:100%; height:4.5em;"> <style> .border { outline: 1px solid var(--vscode-foreground); outline-offset: 0; height:1em; position:absolute; text-align: center; } .slot { height:2em; background: gray } .transparent { height:2em; background: transparent } </style> <!-- Legend --> <span style="position:absolute; top: 0em; left:0%"> <label style="background:blue">&ensp;&ensp;</label><label>&nbsp;PROG &ensp;&ensp;</label> <label style="background:yellow">&ensp;&ensp;</label><label>&nbsp;READ &ensp;&ensp;</label> <label style="background:red">&ensp;&ensp;</label><label>&nbsp;WRITE</label> </span> <!-- Address labels --> <label style="position:absolute; top:2em; left:0%">0x0000</label> <label style="position:absolute; top:2em; left:12.5%">0x2000</label>`; // ZX screen memory marker if (zx) { html += ` <label style="position:absolute; top:1.1em; left:25%">0x4000</label> <label style="position:absolute; top:1.1em; left:35.5%">0x5B00</label>`; } else { html += ` <label style="position:absolute; top:2em; left:25%">0x4000</label>`; } html += ` <label style="position:absolute; top:2em; left:37.5%">0x6000</label> <label style="position:absolute; top:2em; left:50%">0x8000</label> <label style="position:absolute; top:2em; left:62.5%">0xA000</label> <label style="position:absolute; top:2em; left:75%">0xC000</label> <label style="position:absolute; top:2em; left:87.5%">0xE000</label> <!-- Marker ticks --> <span class="border" style="top: 3em; left:0%; height: 1.7em"></span> <span class="border" style="top: 3em; left:12.5%; height:1em;"></span>`; if (zx) { // ZX screen memory marker html += ` <span class="border" style="top: 2.0em; left:25%; height:2.5em;"></span> <span class="border" style="top: 2.0em; left:34.4%; height:2.5em;"></span> <!-- 0x5800 --> <span class="border" style="top: 2.0em; left:35.5%; height:2.5em;"></span> <!-- 0x5B00 -->`; } else { // ZX screen memory marker html += ` <span class="border" style="top: 3em; left:25%; height:1em;"></span>`; } html += ` <span class="border" style="top: 3em; left:37.5%; height:1em;"></span> <span class="border" style="top: 3em; left:50%; height:1em;"></span> <span class="border" style="top: 3em; left:62.5%; height:1em;"></span> <span class="border" style="top: 3em; left:75%; height:1em;"></span> <span class="border" style="top: 3em; left:87.5%; height:1em;"></span> `; if (zx) { // Markers for display html += ` <!-- Extra "Screen" range display --> <div class="border slot" style="top:2.2em; left:25%; width:9.4%;">SCREEN</div> <div class="border slot" style="top:2.2em; left:34.4%; width:1.1%;"></div>`; } html += ` <!-- Visual memory image, is mainly transparent and put on top --> <canvas class="slot" width="256" height="1" id="visual_mem_img_id" style="image-rendering:pixelated; position:absolute; top:3.5em; left:0; width:100%;"></canvas> <!-- Slots 2nd --> `; const count = banks.length; for (let i = 0; i < count; i++) { const bank = banks[i]; const pos = bank.start * 100 / 0x10000; const width = (bank.end + 1 - bank.start) * 100 / 0x10000; const add = `<div class="border" id="slot${i}_id" style="top:3.5em; left:${pos}%; width:${width}%; height: 2em">${bank.name}</div> `; html += add; } html += ` <script> <!-- Store the visual mem image source --> const visualMem=document.getElementById("visual_mem_img_id"); <!-- Store the slots --> const slots = [ `; for (let i = 0; i < count; i++) { const add = `document.getElementById("slot${i}_id"), `; html += add; } html += ` ]; </script> </div> <br><br> `; } // Add code for the screen if (Settings.launch.zsim.ulaScreen) { html += `<!-- Display the screen gif --> <canvas id="screen_img_id" width="256" height="192" style="image-rendering:pixelated; border:${Settings.launch.zsim.zxBorderWidth}px solid white; outline: 1px solid var(--vscode-foreground); width:95%; height:95%"> </canvas> <script> <!-- Store the screen image source --> const screenImg=document.getElementById("screen_img_id"); const screenImgContext = screenImg.getContext("2d"); const screenImgImgData = screenImgContext.createImageData(UlaScreen.SCREEN_WIDTH, UlaScreen.SCREEN_HEIGHT); </script> `; } // Add code for the ZX beeper if (Settings.launch.zsim.zxBeeper) { const initialBeeperValue = this.simulator.zxBeeper.getCurrentBeeperValue().toString(); let volume = GlobalStorage.Get<number>('audio.volume'); if (volume == undefined) volume = 0.75; html += ` <details open="true"> <summary>ZX Beeper</summary> <span style="display:table-cell; vertical-align: middle"> <img src="assets/loudspeaker.svg" width="20em"></img> &nbsp; </span> <!-- 0/1 visual output --> <span id="beeper.output" style="display:table-cell; vertical-align: middle; width: 4em">${initialBeeperValue}</span> <!-- Volume slider --> <span style="display:table-cell; vertical-align: middle;">-</span> <span style="display:table-cell; vertical-align: middle"> <input id="audio.volume" type="range" min="0" max="1" step="0.01" value="0" oninput="volumeChanged(parseFloat(this.value))"> </span> <span style="display:table-cell; vertical-align: middle">+</span> </details> <script> // Singleton for audio const zxAudioBeeper = new ZxAudioBeeper(${Settings.launch.zsim.audioSampleRate}); zxAudioBeeper.setVolume(${volume}); // Get Beeper output object const beeperOutput = document.getElementById("beeper.output"); // Get Volume slider const volumeSlider = document.getElementById("audio.volume"); volumeSlider.value = zxAudioBeeper.getVolume(); </script> `; } // Add code for the keyboard if (Settings.launch.zsim.zxKeyboard) { html += `<!-- Keyboard --> <details open="true"> <summary>ZX Keyboard</summary> <table style="width:100%"> <tr> <td id="key_Digit1" class="td_off" onClick="cellClicked(this)">1</td> <td id="key_Digit2" class="td_off" onClick="cellClicked(this)">2</td> <td id="key_Digit3" class="td_off" onClick="cellClicked(this)">3</td> <td id="key_Digit4" class="td_off" onClick="cellClicked(this)">4</td> <td id="key_Digit5" class="td_off" onClick="cellClicked(this)">5</td> <td id="key_Digit6" class="td_off" onClick="cellClicked(this)">6</td> <td id="key_Digit7" class="td_off" onClick="cellClicked(this)">7</td> <td id="key_Digit8" class="td_off" onClick="cellClicked(this)">8</td> <td id="key_Digit9" class="td_off" onClick="cellClicked(this)">9</td> <td id="key_Digit0" class="td_off" onClick="cellClicked(this)">0</td> </tr> <tr> <td id="key_KeyQ" class="td_off" onClick="cellClicked(this)">Q</td> <td id="key_KeyW" class="td_off" onClick="cellClicked(this)">W</td> <td id="key_KeyE" class="td_off" onClick="cellClicked(this)">E</td> <td id="key_KeyR" class="td_off" onClick="cellClicked(this)">R</td> <td id="key_KeyT" class="td_off" onClick="cellClicked(this)">T</td> <td id="key_KeyY" class="td_off" onClick="cellClicked(this)">Y</td> <td id="key_KeyU" class="td_off" onClick="cellClicked(this)">U</td> <td id="key_KeyI" class="td_off" onClick="cellClicked(this)">I</td> <td id="key_KeyO" class="td_off" onClick="cellClicked(this)">O</td> <td id="key_KeyP" class="td_off" onClick="cellClicked(this)">P</td> </tr> <tr> <td id="key_KeyA" class="td_off" onClick="cellClicked(this)">A</td> <td id="key_KeyS" class="td_off" onClick="cellClicked(this)">S</td> <td id="key_KeyD" class="td_off" onClick="cellClicked(this)">D</td> <td id="key_KeyF" class="td_off" onClick="cellClicked(this)">F</td> <td id="key_KeyG" class="td_off" onClick="cellClicked(this)">G</td> <td id="key_KeyH" class="td_off" onClick="cellClicked(this)">H</td> <td id="key_KeyJ" class="td_off" onClick="cellClicked(this)">J</td> <td id="key_KeyK" class="td_off" onClick="cellClicked(this)">K</td> <td id="key_KeyL" class="td_off" onClick="cellClicked(this)">L</td> <td id="key_Enter" class="td_off" onClick="cellClicked(this)">ENTER</td> </tr> <tr> <td id="key_ShiftLeft" class="td_off" onClick="cellClicked(this)">CAPS S.</td> <td id="key_KeyZ" class="td_off" onClick="cellClicked(this)">Z</td> <td id="key_KeyX" class="td_off" onClick="cellClicked(this)">X</td> <td id="key_KeyC" class="td_off" onClick="cellClicked(this)">C</td> <td id="key_KeyV" class="td_off" onClick="cellClicked(this)">V</td> <td id="key_KeyB" class="td_off" onClick="cellClicked(this)">B</td> <td id="key_KeyN" class="td_off" onClick="cellClicked(this)">N</td> <td id="key_KeyM" class="td_off" onClick="cellClicked(this)">M</td> <td id="key_ShiftRight" class="td_off" onClick="cellClicked(this)">SYMB. S.</td> <td id="key_Space" class="td_off" onClick="cellClicked(this)">SPACE</td> </tr> </table> </details> `; } // Add code for the Interface 2 joysticks if (Settings.launch.zsim.zxInterface2Joy) { html += `<!-- ZX Interface 2 Joysticks --> <details open="true"> <summary>ZX Interface 2 Joysticks</summary> <table> <tr> <td> <table style="color:black;" oncolor="red" offcolor="white"> <tr> <td> <ui-bit id="if2.joy1.fire" style="border-radius:1em;" onchange="togglePortBitNeg(this, 0xEFFE, 0x01)">F</ui-bit> </td> <td align="center"> <ui-bit id="if2.joy1.up" onchange="togglePortBitNeg(this, 0xEFFE, 0x02)">U</ui-bit> </td> </tr> <tr> <td> <ui-bit id="if2.joy1.left" onchange="togglePortBitNeg(this, 0xEFFE, 0x10)">L</ui-bit> </td> <td style="color:var(--vscode-editor-foreground)">Joy1</td> <td> <ui-bit id="if2.joy1.right" onchange="togglePortBitNeg(this, 0xEFFE, 0x08)">R</ui-bit> </td> </tr> <tr> <td></td> <td align="center"> <ui-bit id="if2.joy1.down" onchange="togglePortBitNeg(this, 0xEFFE, 0x04)">D</ui-bit> </td> </tr> </table> </td> <td></td> <td></td> <td> <table style="color:black;"> <tr> <td> <ui-bit id="if2.joy2.fire" style="border-radius:1em;" onchange="togglePortBitNeg(this, 0xF7FE, 0x10)">F</ui-bit> </td> <td align="center"> <ui-bit id="if2.joy2.up" onchange="togglePortBitNeg(this, 0xF7FE, 0x08)">U</ui-bit> </td> </tr> <tr> <td> <ui-bit id="if2.joy2.left" onchange="togglePortBitNeg(this, 0xF7FE, 0x01)">L</ui-bit> </td> <td style="color:var(--vscode-editor-foreground)">Joy2</td> <td> <ui-bit id="if2.joy2.right" onchange="togglePortBitNeg(this, 0xF7FE, 0x02)">R</ui-bit> </td> </tr> <tr> <td></td> <td align="center"> <ui-bit id="if2.joy2.down" onchange="togglePortBitNeg(this, 0xF7FE, 0x04)">D</ui-bit> </td> </tr> </table> </td> </tr> </table> </details> <script> // Add references to the html elements joystickObjs.push({ fire: document.getElementById("if2.joy1.fire"), up: document.getElementById("if2.joy1.up"), left: document.getElementById("if2.joy1.left"), right: document.getElementById("if2.joy1.right"), down: document.getElementById("if2.joy1.down") }); joystickObjs.push({ fire: document.getElementById("if2.joy2.fire"), up: document.getElementById("if2.joy2.up"), left: document.getElementById("if2.joy2.left"), right: document.getElementById("if2.joy2.right"), down: document.getElementById("if2.joy2.down") }); </script> `; } // Add code for the Kempston joystick if (Settings.launch.zsim.kempstonJoy) { html += `<!-- Kempston Joystick --> <details open="true"> <summary>Kempston Joystick</summary> <table> <tr> <td> <table style="color:black;" oncolor="red" offcolor="white" > <tr> <td> <ui-bit id="kempston.joy1.fire" style="border-radius:1em;color:black;" onchange="togglePortBit(this, 0x001F, 0x10)">F</ui-bit> </td> <td> <ui-bit id="kempston.joy1.up" onchange="togglePortBit(this, 0x001F, 0x08)">U</ui-bit> </td> </tr> <tr> <td> <ui-bit id="kempston.joy1.left" onchange="togglePortBit(this, 0x001F, 0x02)">L</ui-bit> </td> <td></td> <td> <ui-bit id="kempston.joy1.right" onchange="togglePortBit(this, 0x001F, 0x01)">R</ui-bit> </td> </tr> <tr> <td></td> <td> <ui-bit id="kempston.joy1.down" onchange="togglePortBit(this, 0x001F, 0x04)">D</ui-bit> </td> </tr> </table> </td> </table> </td> </tr> </table> </details> <script> // References to the html objects joystickObjs.push({ fire: document.getElementById("kempston.joy1.fire"), up: document.getElementById("kempston.joy1.up"), left: document.getElementById("kempston.joy1.left"), right: document.getElementById("kempston.joy1.right"), down: document.getElementById("kempston.joy1.down") }); </script> `; } // Add polling of gamepads html += ` <script src="out/src/remotes/zsimulator/zsimwebview/joysticks.js"></script> `; // Space for logging html += `<p id="log"></p> `; // Custom javascript code area let jsCode = ''; if (this.customUiPath) { try { jsCode = readFileSync(this.customUiPath).toString(); } catch (e) { jsCode = "<b>Error: reading file '" + this.customUiPath + "':" + e.message + "</b>"; } } html += `<!-- Room for extra/user editable javascript/html code --> <p> <div id="js_code_id"> ${jsCode} </div> </p> `; if (Settings.launch.zsim.customCode.debug) { html += `<!-- Debug Area --> <hr> <details open="true"> <summary>Debug Area</summary> <button onclick="reloadCustomLogicAndUi()">Reload Custom Logic and UI</button> &nbsp;&nbsp; <button onclick="copyHtmlToClipboard()">Copy all HTML to clipboard</button> </details> `; } html += `</body> </html> `; this.vscodePanel.webview.html = ''; this.vscodePanel.webview.html = html; } }
the_stack
import * as msRest from "@azure/ms-rest-js"; export const ResponseBase: msRest.CompositeMapper = { serializedName: "ResponseBase", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "ResponseBase", className: "ResponseBase", modelProperties: { _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const Identifiable: msRest.CompositeMapper = { serializedName: "Identifiable", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Identifiable", modelProperties: { ...ResponseBase.type.modelProperties, id: { readOnly: true, serializedName: "id", type: { name: "String" } } } } }; export const Response: msRest.CompositeMapper = { serializedName: "Response", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Response", modelProperties: { ...Identifiable.type.modelProperties, readLink: { readOnly: true, serializedName: "readLink", type: { name: "String" } }, webSearchUrl: { readOnly: true, serializedName: "webSearchUrl", type: { name: "String" } } } } }; export const Thing: msRest.CompositeMapper = { serializedName: "Thing", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Thing", modelProperties: { ...Response.type.modelProperties, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, url: { readOnly: true, serializedName: "url", type: { name: "String" } }, image: { readOnly: true, serializedName: "image", type: { name: "Composite", className: "ImageObject" } }, description: { readOnly: true, serializedName: "description", type: { name: "String" } }, alternateName: { readOnly: true, serializedName: "alternateName", type: { name: "String" } }, bingId: { readOnly: true, serializedName: "bingId", type: { name: "String" } } } } }; export const CreativeWork: msRest.CompositeMapper = { serializedName: "CreativeWork", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "CreativeWork", modelProperties: { ...Thing.type.modelProperties, thumbnailUrl: { readOnly: true, serializedName: "thumbnailUrl", type: { name: "String" } }, provider: { readOnly: true, serializedName: "provider", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, text: { readOnly: true, serializedName: "text", type: { name: "String" } } } } }; export const MediaObject: msRest.CompositeMapper = { serializedName: "MediaObject", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "MediaObject", modelProperties: { ...CreativeWork.type.modelProperties, contentUrl: { readOnly: true, serializedName: "contentUrl", type: { name: "String" } }, hostPageUrl: { readOnly: true, serializedName: "hostPageUrl", type: { name: "String" } }, contentSize: { readOnly: true, serializedName: "contentSize", type: { name: "String" } }, encodingFormat: { readOnly: true, serializedName: "encodingFormat", type: { name: "String" } }, hostPageDisplayUrl: { readOnly: true, serializedName: "hostPageDisplayUrl", type: { name: "String" } }, width: { readOnly: true, serializedName: "width", type: { name: "Number" } }, height: { readOnly: true, serializedName: "height", type: { name: "Number" } } } } }; export const ImageObject: msRest.CompositeMapper = { serializedName: "ImageObject", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "ImageObject", modelProperties: { ...MediaObject.type.modelProperties, thumbnail: { readOnly: true, serializedName: "thumbnail", type: { name: "Composite", className: "ImageObject" } }, imageInsightsToken: { readOnly: true, serializedName: "imageInsightsToken", type: { name: "String" } }, imageId: { readOnly: true, serializedName: "imageId", type: { name: "String" } }, accentColor: { readOnly: true, serializedName: "accentColor", type: { name: "String" } }, visualWords: { readOnly: true, serializedName: "visualWords", type: { name: "String" } } } } }; export const Answer: msRest.CompositeMapper = { serializedName: "Answer", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Answer", modelProperties: { ...Response.type.modelProperties } } }; export const SearchResultsAnswer: msRest.CompositeMapper = { serializedName: "SearchResultsAnswer", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "SearchResultsAnswer", modelProperties: { ...Answer.type.modelProperties, totalEstimatedMatches: { readOnly: true, serializedName: "totalEstimatedMatches", type: { name: "Number" } } } } }; export const Images: msRest.CompositeMapper = { serializedName: "Images", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Images", modelProperties: { ...SearchResultsAnswer.type.modelProperties, nextOffset: { readOnly: true, serializedName: "nextOffset", type: { name: "Number" } }, value: { required: true, serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "ImageObject" } } } } } } }; export const Query: msRest.CompositeMapper = { serializedName: "Query", type: { name: "Composite", className: "Query", modelProperties: { text: { required: true, serializedName: "text", type: { name: "String" } }, displayText: { readOnly: true, serializedName: "displayText", type: { name: "String" } }, webSearchUrl: { readOnly: true, serializedName: "webSearchUrl", type: { name: "String" } }, searchLink: { readOnly: true, serializedName: "searchLink", type: { name: "String" } }, thumbnail: { readOnly: true, serializedName: "thumbnail", type: { name: "Composite", className: "ImageObject" } } } } }; export const ErrorModel: msRest.CompositeMapper = { serializedName: "Error", type: { name: "Composite", className: "ErrorModel", modelProperties: { code: { required: true, serializedName: "code", defaultValue: 'None', type: { name: "String" } }, subCode: { readOnly: true, serializedName: "subCode", type: { name: "String" } }, message: { required: true, serializedName: "message", type: { name: "String" } }, moreDetails: { readOnly: true, serializedName: "moreDetails", type: { name: "String" } }, parameter: { readOnly: true, serializedName: "parameter", type: { name: "String" } }, value: { readOnly: true, serializedName: "value", type: { name: "String" } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "ErrorResponse", modelProperties: { ...Response.type.modelProperties, errors: { required: true, serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorModel" } } } } } } }; export const WebPage: msRest.CompositeMapper = { serializedName: "WebPage", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "WebPage", modelProperties: { ...CreativeWork.type.modelProperties } } }; export const discriminators = { 'ResponseBase.ImageObject' : ImageObject, 'ResponseBase.Images' : Images, 'ResponseBase.SearchResultsAnswer' : SearchResultsAnswer, 'ResponseBase.Answer' : Answer, 'ResponseBase.MediaObject' : MediaObject, 'ResponseBase.Response' : Response, 'ResponseBase.Thing' : Thing, 'ResponseBase.CreativeWork' : CreativeWork, 'ResponseBase.Identifiable' : Identifiable, 'ResponseBase.ErrorResponse' : ErrorResponse, 'ResponseBase.WebPage' : WebPage, 'ResponseBase' : ResponseBase };
the_stack
import { EdgeError } from 'edge-error' import { TagToken, utils as lexerUtils } from 'edge-lexer' import { EdgeBuffer, expressions, Parser } from 'edge-parser' import { TagContract } from '../Contracts' import { StringifiedObject } from '../StringifiedObject' import { isSubsetOf, unallowedExpression, parseJsArg } from '../utils' /** * A list of allowed expressions for the component name */ const ALLOWED_EXPRESSION_FOR_COMPONENT_NAME = [ expressions.Identifier, expressions.Literal, expressions.LogicalExpression, expressions.MemberExpression, expressions.ConditionalExpression, expressions.CallExpression, expressions.TemplateLiteral, ] as const /** * Shape of a slot */ type Slot = { outputVar: string props: any buffer: EdgeBuffer line: number filename: string } /** * Returns the component name and props by parsing the component jsArg expression */ function getComponentNameAndProps( expression: any, parser: Parser, filename: string ): [string, string] { let name: string /** * Use the first expression inside the sequence expression as the name * of the component */ if (expression.type === expressions.SequenceExpression) { name = expression.expressions.shift() } else { name = expression } /** * Ensure the component name is a literal value or an expression that * outputs a literal value */ isSubsetOf(name, ALLOWED_EXPRESSION_FOR_COMPONENT_NAME, () => { unallowedExpression( `"${parser.utils.stringify(name)}" is not a valid argument for component name`, filename, parser.utils.getExpressionLoc(name) ) }) /** * Parse rest of sequence expressions as an objectified string. */ if (expression.type === expressions.SequenceExpression) { /** * We only need to entertain the first expression of the sequence * expression, as components allows a max of two arguments */ const firstSequenceExpression = expression.expressions[0] if ( firstSequenceExpression && [expressions.ObjectExpression, expressions.AssignmentExpression].includes( firstSequenceExpression.type ) ) { return [ parser.utils.stringify(name), StringifiedObject.fromAcornExpressions([firstSequenceExpression], parser), ] } return [parser.utils.stringify(name), parser.utils.stringify(firstSequenceExpression)] } /** * When top level expression is not a sequence expression, then we assume props * as empty stringified object. */ return [parser.utils.stringify(name), '{}'] } /** * Parses the slot component to fetch it's name and props */ function getSlotNameAndProps(token: TagToken, parser: Parser): [string, null | string] { /** * We just generate the acorn AST only, since we don't want parser to transform * ast to edge statements for a `@slot` tag. */ const parsed = parser.utils.generateAST( token.properties.jsArg, token.loc, token.filename ).expression isSubsetOf(parsed, [expressions.Literal, expressions.SequenceExpression], () => { unallowedExpression( `"${token.properties.jsArg}" is not a valid argument type for the @slot tag`, token.filename, parser.utils.getExpressionLoc(parsed) ) }) /** * Fetch the slot name */ let name: any if (parsed.type === expressions.SequenceExpression) { name = parsed.expressions[0] } else { name = parsed } /** * Validating the slot name to be a literal value, since slot names cannot be dynamic */ isSubsetOf(name, [expressions.Literal], () => { unallowedExpression( 'slot name must be a valid string literal', token.filename, parser.utils.getExpressionLoc(name) ) }) /** * Return the slot name with empty props, when the expression is a literal * value. */ if (parsed.type === expressions.Literal) { return [name.raw, null] } /** * Make sure the sequence expression has only 2 arguments in it. Though it doesn't hurt * the rendering of component, we must not run code with false expectations. */ if (parsed.expressions.length > 2) { throw new EdgeError('maximum of 2 arguments are allowed for @slot tag', 'E_MAX_ARGUMENTS', { line: parsed.loc.start.line, col: parsed.loc.start.column, filename: token.filename, }) } isSubsetOf(parsed.expressions[1], [expressions.Identifier], () => { unallowedExpression( `"${parser.utils.stringify( parsed.expressions[1] )}" is not valid prop identifier for @slot tag`, token.filename, parser.utils.getExpressionLoc(parsed.expressions[1]) ) }) /** * Returning the slot name and slot props name */ return [name.raw, parsed.expressions[1].name] } /** * The component tag implementation. It is one of the most complex tags and * can be used as a reference for creating other tags. */ export const componentTag: TagContract = { block: true, seekable: true, tagName: 'component', compile(parser, buffer, token) { const asyncKeyword = parser.asyncMode ? 'async ' : '' const awaitKeyword = parser.asyncMode ? 'await ' : '' const parsed = parseJsArg(parser, token) /** * Check component jsProps for allowed expressions */ isSubsetOf( parsed, ALLOWED_EXPRESSION_FOR_COMPONENT_NAME.concat(expressions.SequenceExpression as any), () => { unallowedExpression( `"${token.properties.jsArg}" is not a valid argument type for the @component tag`, token.filename, parser.utils.getExpressionLoc(parsed) ) } ) /** * Pulling the name and props for the component. The underlying method will * ensure that the arguments passed to component tag are valid */ const [name, props] = getComponentNameAndProps(parsed, parser, token.filename) /** * Loop over all the children and set them as part of slots. If no slot * is defined, then the content will be part of the main slot */ const slots: { [slotName: string]: Slot } = {} /** * Main slot collects everything that is out of the named slots * inside a component */ const mainSlot: Slot = { outputVar: 'slot_main', props: {}, buffer: buffer.create(token.filename, { outputVar: 'slot_main', }), line: -1, filename: token.filename, } let slotsCounter = 0 /** * Loop over all the component children */ token.children.forEach((child) => { /** * If children is not a slot, then add it to the main slot */ if (!lexerUtils.isTag(child, 'slot')) { /** * Ignore first newline inside the unnamed main slot */ if (mainSlot.buffer.size === 0 && child.type === 'newline') { return } parser.processToken(child, mainSlot.buffer) return } /** * Fetch slot and props */ const [slotName, slotProps] = getSlotNameAndProps(child, parser) slotsCounter++ /** * Create a new slot with buffer to process the children */ if (!slots[slotName]) { /** * Slot buffer points to the component file name, since slots doesn't * have their own file names. */ slots[slotName] = { outputVar: `slot_${slotsCounter}`, buffer: buffer.create(token.filename, { outputVar: `slot_${slotsCounter}`, }), props: slotProps, line: -1, filename: token.filename, } /** * Only start the frame, when there are props in use for a given slot. */ if (slotProps) { parser.stack.defineScope() parser.stack.defineVariable(slotProps) } } /** * Self process the slot children. */ child.children.forEach((grandChildren) => { parser.processToken(grandChildren, slots[slotName].buffer) }) /** * Close the frame after process the slot children */ if (slotProps) { parser.stack.clearScope() } }) const obj = new StringifiedObject() /** * Creating a shallow copy of context for the component slots and its children */ obj.add('$context', 'Object.assign({}, $context)') /** * Add main slot to the stringified object, when main slot * is not defined otherwise. */ if (!slots['main']) { if (mainSlot.buffer.size) { mainSlot.buffer.wrap(`${asyncKeyword}function () { const $context = this.$context;`, '}') obj.add('main', mainSlot.buffer.disableFileAndLineVariables().flush()) } else { obj.add('main', 'function () { return "" }') } } /** * We convert the slots to an objectified string, that is passed to `template.renderWithState`, * which will pass it to the component as it's local state. */ Object.keys(slots).forEach((slotName) => { if (slots[slotName].buffer.size) { const fnCall = slots[slotName].props ? `${asyncKeyword}function (${slots[slotName].props}) { const $context = this.$context;` : `${asyncKeyword}function () { const $context = this.$context;` slots[slotName].buffer.wrap(fnCall, '}') obj.add(slotName, slots[slotName].buffer.disableFileAndLineVariables().flush()) } else { obj.add(slotName, 'function () { return "" }') } }) const caller = new StringifiedObject() caller.add('filename', '$filename') caller.add('line', '$lineNumber') caller.add('col', 0) /** * Write the line to render the component with it's own state */ buffer.outputExpression( `${awaitKeyword}template.compileComponent(${name})(template, template.getComponentState(${props}, ${obj.flush()}, ${caller.flush()}), $context)`, token.filename, token.loc.start.line, false ) }, }
the_stack
import { expect } from 'chai'; import { Tests } from 'test/lib/tests'; describe('UI interactions', () => { describe('Environments menu', () => { const tests = new Tests('ui'); it('Verify environments men item content', async () => { await tests.helpers.assertHasActiveEnvironment('FT env'); await tests.helpers.assertEnvironmentServerIconsExists(1, 'cors'); await tests.helpers.assertEnvironmentServerIconsExists(1, 'https'); await tests.helpers.assertEnvironmentServerIconsExists(1, 'proxy-mode'); await tests.helpers.contextMenuOpen( '.environments-menu .nav-item .nav-link.active' ); await tests.helpers.waitElementExist('.context-menu'); }); }); describe('Inputs autofocus', () => { const tests = new Tests('ui'); it('Focus "documentation" input, add route, and assert "path" input has focus', async () => { const documentationSelector = 'input[formcontrolname="documentation"]'; await tests.helpers.setElementValue(documentationSelector, 'test'); const documentationInput = await tests.helpers.getElement( documentationSelector ); expect(await documentationInput.isFocused()).to.equal(true); await tests.helpers.addRoute(); const pathInput = await tests.helpers.getElement( 'input[formcontrolname="endpoint"]' ); expect(await pathInput.isFocused()).to.equal(true); }); }); describe('Add CORS headers', () => { const tests = new Tests('ui'); const environmentHeadersSelector = 'app-headers-list#environment-headers .headers-list'; it('Switch to environment settings and check headers count', async () => { await tests.helpers.switchViewInHeader('ENV_SETTINGS'); await tests.helpers.countElements(environmentHeadersSelector, 1); }); describe('Check environment headers', () => { ['Content-Type', 'application/xml'].forEach((expected, index) => { it(`Row 1 input ${ index + 1 } should be equal to ${expected}`, async () => { const value = await tests.helpers.getElementValue( `${environmentHeadersSelector}:nth-of-type(1) input:nth-of-type(${ index + 1 })` ); expect(value).to.equal(expected); }); }); }); it('Click on "Add CORS headers" button and check headers count', async () => { await tests.helpers.elementClick('button.settings-add-cors'); await tests.helpers.countElements(environmentHeadersSelector, 4); }); describe('Check environment headers', () => { [ 'Content-Type', 'application/xml', 'Access-Control-Allow-Origin', '*', 'Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS', 'Access-Control-Allow-Headers', 'Content-Type, Origin, Accept, Authorization, Content-Length, X-Requested-With' ].forEach((expected, index) => { it(`Row ${Math.ceil((index + 1) / 2)} input ${ index + 1 } should be equal to ${expected}`, async () => { const value = await tests.helpers.getElementValue( `${environmentHeadersSelector}:nth-of-type(${Math.ceil( (index + 1) / 2 )}) input:nth-of-type(${(index + 1) % 2 === 0 ? 2 : 1})` ); expect(value).to.equal(expected); }); }); }); }); describe('Headers && Rules tabs', () => { const tests = new Tests('ui'); it('Headers tab shows the header count', async () => { const headersTabSelector = '#route-responses-menu .nav.nav-tabs .nav-item:nth-child(2)'; let text = await tests.helpers.getElementText(headersTabSelector); expect(text).to.equal('Headers (1)'); await tests.helpers.switchTab('HEADERS'); await tests.helpers.addHeader('route-response-headers', { key: 'route-header', value: 'route-header' }); // this is needed for the tab re-render to complete await tests.app.client.pause(100); text = await tests.helpers.getElementText(headersTabSelector); expect(text).to.equal('Headers (2)'); await tests.helpers.addHeader('route-response-headers', { key: 'route-header-2', value: 'route-header-2' }); // this is needed for the tab re-render to complete await tests.app.client.pause(100); text = await tests.helpers.getElementText(headersTabSelector); expect(text).to.equal('Headers (3)'); await tests.helpers.addRouteResponse(); await tests.helpers.countRouteResponses(2); // this is needed for the tab re-render to complete await tests.app.client.pause(100); text = await tests.helpers.getElementText(headersTabSelector); expect(text).to.equal('Headers'); await tests.helpers.switchTab('HEADERS'); await tests.helpers.addHeader('route-response-headers', { key: 'route-header-3', value: 'route-header-3' }); // this is needed for the tab re-render to complete await tests.app.client.pause(100); text = await tests.helpers.getElementText(headersTabSelector); expect(text).to.equal('Headers (1)'); }); it('Rules tab shows the rule count', async () => { const rulesTabSelector = '#route-responses-menu .nav.nav-tabs .nav-item:nth-child(3)'; let text = await tests.helpers.getElementText(rulesTabSelector); expect(text).to.equal('Rules'); await tests.helpers.switchTab('RULES'); await tests.helpers.addResponseRule({ modifier: 'var', target: 'params', value: '10', operator: 'equals' }); // this is needed for the tab re-render to complete await tests.app.client.pause(100); text = await tests.helpers.getElementText(rulesTabSelector); expect(text).to.equal('Rules (1)'); await tests.helpers.addResponseRule({ modifier: 'test', target: 'query', value: 'true', operator: 'equals' }); // this is needed for the tab re-render to complete await tests.app.client.pause(100); text = await tests.helpers.getElementText(rulesTabSelector); expect(text).to.equal('Rules (2)'); await tests.helpers.addRouteResponse(); await tests.helpers.countRouteResponses(3); // this is needed for the tab re-render to complete await tests.app.client.pause(100); text = await tests.helpers.getElementText(rulesTabSelector); expect(text).to.equal('Rules'); await tests.helpers.switchTab('RULES'); await tests.helpers.addResponseRule({ modifier: 'var', target: 'params', value: '10', operator: 'equals' }); // this is needed for the tab re-render to complete await tests.app.client.pause(100); text = await tests.helpers.getElementText(rulesTabSelector); expect(text).to.equal('Rules (1)'); }); }); describe('Input number mask', () => { const tests = new Tests('ui'); const portSelector = 'input[formcontrolname="port"]'; it('should allow numbers', async () => { await tests.helpers.setElementValue(portSelector, '1234'); await tests.helpers.assertElementValue(portSelector, '1234'); }); it('should prevent entering letters and other characters', async () => { await tests.helpers.addElementValue(portSelector, 'a.e-+'); await tests.helpers.assertElementValue(portSelector, '1234'); }); it('should enforce max constraint', async () => { await tests.helpers.setElementValue(portSelector, '1000000'); await tests.helpers.assertElementValue(portSelector, '65535'); }); }); describe('Valid path mask', () => { const tests = new Tests('ui'); const prefixSelector = 'input[formcontrolname="endpointPrefix"]'; it('should remove leading slash', async () => { await tests.helpers.setElementValue(prefixSelector, '/prefix'); await tests.helpers.assertElementValue(prefixSelector, 'prefix'); }); it('should deduplicate slashes', async () => { await tests.helpers.setElementValue(prefixSelector, 'prefix//path'); await tests.helpers.assertElementValue(prefixSelector, 'prefix/path'); }); }); describe('Body editor reset undo state when navigating', () => { const tests = new Tests('ui'); const bodySelector = '.ace_content'; it('should navigate to second route and verify body', async () => { await tests.helpers.selectRoute(2); await tests.helpers.assertElementText(bodySelector, '42'); }); it('should try to undo (ctrl-z) and content should stay the same', async () => { const bodyElement = await tests.app.client.$(bodySelector); await tests.helpers.elementClick(bodySelector); await bodyElement.keys(['Control', 'z']); await tests.helpers.assertElementText(bodySelector, '42'); }); }); describe('Headers typeahead', () => { const tests = new Tests('ui'); const typeaheadEntrySelector = 'ngb-typeahead-window button:first-of-type'; const testCases = [ { description: 'should use the typeahead in the route headers', headers: 'route-response-headers', preHook: async () => { await tests.helpers.switchTab('HEADERS'); } }, { description: 'should use the typeahead in the environment headers', headers: 'environment-headers', preHook: async () => { await tests.helpers.switchViewInHeader('ENV_SETTINGS'); } }, { description: 'should use the typeahead in the proxy request headers', headers: 'proxy-req-headers', preHook: async () => { await tests.helpers.switchViewInHeader('ENV_SETTINGS'); } }, { description: 'should use the typeahead in the proxy response headers', headers: 'proxy-res-headers', preHook: async () => { await tests.helpers.switchViewInHeader('ENV_SETTINGS'); } } ]; testCases.forEach((testCase) => { const headersSelector = `app-headers-list#${testCase.headers}`; const firstHeaderSelector = `${headersSelector} .headers-list:last-of-type input:nth-of-type(1)`; it(testCase.description, async () => { await testCase.preHook(); await tests.helpers.elementClick(`${headersSelector} button`); await tests.helpers.setElementValue(firstHeaderSelector, 'typ'); await tests.helpers.waitElementExist(typeaheadEntrySelector); await tests.helpers.elementClick(typeaheadEntrySelector); const headerName = await tests.helpers.getElementValue( firstHeaderSelector ); expect(headerName).to.equal('Content-Type'); }); }); }); describe('Status code dropdown', () => { const tests = new Tests('ui'); const dropdownId = 'status-code'; it('should be able to select a status code by clicking', async () => { await tests.helpers.openDropdown(dropdownId); await tests.helpers.selectDropdownItem(dropdownId, 1); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', 'routes.0.responses.0.statusCode', 100 ); }); it('should be able to filter status codes and select the last one', async () => { await tests.helpers.openDropdown(dropdownId); await tests.helpers.setDropdownInputValue(dropdownId, '45'); await tests.app.client.pause(100); await tests.helpers.assertDropdownItemsNumber(dropdownId, 2); await tests.helpers.assertDropdownItemText( dropdownId, 1, '450 - Blocked by Windows Parental Controls (Microsoft)' ); await tests.helpers.assertDropdownItemText( dropdownId, 2, '451 - Unavailable For Legal Reasons' ); await tests.helpers.selectDropdownItem(dropdownId, 2); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', 'routes.0.responses.0.statusCode', 451 ); }); it('should be able to select a status code with keyboard arrows', async () => { await tests.helpers.openDropdown(dropdownId); await tests.app.client.pause(100); await tests.app.client.keys(['ArrowUp', 'Enter']); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', 'routes.0.responses.0.statusCode', 561 ); await tests.helpers.assertDropdownToggleText( dropdownId, '561 - Unauthorized (AWS ELB)' ); }); it('should be able to filter status codes and select one with keyboard arrows', async () => { await tests.helpers.openDropdown(dropdownId); await tests.helpers.setDropdownInputValue(dropdownId, '30'); await tests.app.client.pause(100); await tests.app.client.keys(['ArrowDown', 'ArrowDown', 'Enter']); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', 'routes.0.responses.0.statusCode', 301 ); await tests.helpers.assertDropdownToggleText( dropdownId, '301 - Moved Permanently' ); }); it('should be able to enter a custom status codes', async () => { await tests.helpers.openDropdown(dropdownId); await tests.helpers.setDropdownInputValue(dropdownId, '999'); await tests.app.client.pause(100); await tests.helpers.assertDropdownItemsNumber(dropdownId, 0); await tests.helpers.assertElementText( `#${dropdownId}-dropdown-menu .message`, 'Press enter for custom status code' ); await tests.app.client.keys(['Enter']); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', 'routes.0.responses.0.statusCode', 999 ); }); it('should not be able to enter a custom status codes out of bounds', async () => { await tests.helpers.openDropdown(dropdownId); await tests.helpers.setDropdownInputValue(dropdownId, '99'); await tests.app.client.keys(['Enter']); await tests.app.client.pause(100); await tests.helpers.assertDropdownToggleText(dropdownId, '999 - Unknown'); }); }); describe('HTTP methods dropdown', () => { const tests = new Tests('ui'); const dropdownId = 'methods'; it('should be able to select a method by clicking', async () => { await tests.helpers.openDropdown(dropdownId); await tests.helpers.selectDropdownItem(dropdownId, 3); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', 'routes.0.method', 'put' ); }); it('should be able to select a method by navigating with keyboard', async () => { await tests.helpers.openDropdown(dropdownId); await tests.app.client.keys(['ArrowUp', 'Enter']); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', 'routes.0.method', 'options' ); }); }); describe('Response rules random or sequential', () => { const tests = new Tests('ui'); const randomResponseSelector = '#route-responses-random'; const sequentialResponseSelector = '#route-responses-sequential'; it('should enable random responses', async () => { await tests.helpers.elementClick(randomResponseSelector); await tests.helpers.assertHasClass( `${randomResponseSelector} i`, 'text-primary' ); await tests.helpers.assertHasClass( `${sequentialResponseSelector} i`, 'text-primary', true ); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', ['routes.0.randomResponse', 'routes.0.sequentialResponse'], [true, false] ); }); it('should enable sequential responses and random responses should be disabled', async () => { await tests.helpers.elementClick(sequentialResponseSelector); await tests.helpers.assertHasClass( `${randomResponseSelector} i`, 'text-primary', true ); await tests.helpers.assertHasClass( `${sequentialResponseSelector} i`, 'text-primary' ); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', ['routes.0.randomResponse', 'routes.0.sequentialResponse'], [false, true] ); }); it('should re-enable random responses and sequential responses should be disabled', async () => { await tests.helpers.elementClick(randomResponseSelector); await tests.helpers.assertHasClass( `${randomResponseSelector} i`, 'text-primary' ); await tests.helpers.assertHasClass( `${sequentialResponseSelector} i`, 'text-primary', true ); await tests.helpers.waitForAutosave(); await tests.helpers.verifyObjectPropertyInFile( './tmp/storage/environment-0.json', ['routes.0.randomResponse', 'routes.0.sequentialResponse'], [true, false] ); }); }); });
the_stack
declare module 'pilotjs/vendors/Emitter' { // ==== ./vendors/Emitter.js ==== type EventListener = (...args: any[]) => any; namespace Emitter { export class Event<T = any, D = undefined, R = any> { target: T; details: D; result?: R; constructor(type: string | Object | Event); isDefaultPrevented(): boolean; preventDefault(); stopPropagation(); isPropagationStopped(): boolean; } } class Emitter { constructor(); on(events: string, fn: EventListener): this; off(events: string, fn: EventListener): this; one(events: string, fn: EventListener): this; emit(type: string, args: any[]): any; trigger(type: string, args: any[], details?: any): this; static readonly version: string; static apply<T extends object>(target: T): T & Emitter; static getListeners(target: Object, name: string): EventListener[]; } export = Emitter; } declare module 'pilotjs' { // ==== ./src/action-queue.js ==== import Emitter = require("pilotjs/vendors/Emitter"); namespace Pilot { export type ActionQueuePriority = number; export type ActionId = number; export interface Action { type: string; uid?: ActionId; priority?: ActionQueuePriority; } class ActionQueue extends Emitter { constructor(); push(request: Request, action: Action): ActionId; static readonly PRIORITY_HIGH: ActionQueuePriority; static readonly PRIORITY_LOW: ActionQueuePriority; } // ==== ./src/loader.js ==== export type LoaderProcessor = () => void; export interface LoaderOptions { persist?: boolean; processing?: LoaderProcessor; } export type LoaderModelFetcher = () => void; export interface LoaderModelObject { name: string; fetch: LoaderModelFetcher; match: Match; } export type LoaderModel = LoaderModelObject | LoaderModelFetcher; class Loader { readonly models: Record<string, LoaderModel | undefined>; readonly names: string[]; constructor(models: Record<string, LoaderModel | undefined> | Loader, options: LoaderOptions); defaults(): Record<string, Object | undefined>; fetch(): Promise<any>; dispatch(): Promise<any>; extend(models: Record<string, LoaderModel | undefined>): Loader; getLastReq(): Request | undefined; extract(model: LoaderModel): Object; bind(route: Route, model: LoaderModel); setDebug(debug: boolean); static readonly ACTION_NAVIGATE: string; static readonly ACTION_NONE: string; static readonly PRIORITY_LOW: typeof ActionQueue.PRIORITY_LOW; static readonly PRIORITY_HIGH: typeof ActionQueue.PRIORITY_HIGH; } // ==== ./src/match.js ==== export type MatchFn = (key: string) => boolean; export type MatchArray = string[]; export type Match = MatchArray | MatchFn; // ==== ./src/querystring.js ==== export type QueryItem = string | number | symbol; export type Query = Record<QueryItem, QueryItem | QueryItem[] | undefined>; interface QueryString { parse(search: string): Query; stringify(query: Query): string; } // ==== ./src/request.js ==== class Request { href: string; protocol: string; host: string; hostname: string; port: string; path: string; pathname: string; search: string; query: Query; params: Record<string, string | undefined>; hash: string; route: Route; router: Pilot; referrer?: string; redirectHref?: string; alias?: string; constructor(url: string | URL, referrer?: string, router?: string); clone(): Request; is(id: string): boolean; redirectTo(href: string, interrupt?: boolean); toString(): string; } // ==== ./src/route.js ==== export interface RouteUrlParamsConfig { default?: any; decode: (value: string) => any; } export type UrlBuilder = (params: Record<string, any>, query: Query) => string; export interface RouteUrlObject { pattern: string; params?: Record<string, RouteUrlParamsConfig | undefined>; toUrl?: (params: Record<string, any>, query: Query, builder: UrlBuilder) => string; } export type RouteUrl = string | RouteUrlObject; export interface RouteOptions { model?: Loader; aliases?: Record<string, RouteUrlObject | undefined>; } export type Model = Record<string, Object | undefined>; class Route extends Emitter { id: string; active?: boolean; regions: string[]; router: Pilot; model: Model; parentId?: string; parentRoute?: Route; constructor(options: RouteOptions, router: Pilot); protected init(); protected _initOptions(options: RouteOptions); protected _initMixins(); handling(url: URL, req: Request, currentRoute: Route, model: Record<string, Object | undefined>); match(URL: URL, req: Request): boolean; fetch(req: Request): Promise<Object>; getUrl(params: Record<string, string | undefined>, query: Query | 'inherit'): string; is(id: string): boolean; on(event: 'before-init', fn: (event: Emitter.Event<Route>) => any): this; on(event: 'init', fn: (event: Emitter.Event<Route>) => any): this; on(event: 'model', fn: (event: Emitter.Event<Route>, model: Model, req: Request) => any): this; on(event: 'route-start', fn: (event: Emitter.Event<Route>, req: Request) => any): this; on(event: 'route-change', fn: (event: Emitter.Event<Route>, req: Request) => any): this; on(event: 'route', fn: (event: Emitter.Event<Route>, req: Request) => any): this; on(event: 'route-end', fn: (event: Emitter.Event<Route>, req: Request) => any): this; on(events: string, fn: EventListener): this; one(event: 'before-init', fn: (event: Emitter.Event<Route>) => any): this; one(event: 'init', fn: (event: Emitter.Event<Route>) => any): this; one(event: 'model', fn: (event: Emitter.Event<Route>, model: Model, req: Request) => any): this; one(event: 'route-start', fn: (event: Emitter.Event<Route>, req: Request) => any): this; one(event: 'route-change', fn: (event: Emitter.Event<Route>, req: Request) => any): this; one(event: 'route', fn: (event: Emitter.Event<Route>, req: Request) => any): this; one(event: 'route-end', fn: (event: Emitter.Event<Route>, req: Request) => any): this; one(events: string, fn: EventListener): this; static readonly Region: typeof Region; } class Region extends Route { constructor(name: string, options: RouteOptions, route: Route); } // ==== ./src/status.js ==== class Status { code: number; details?: any; constructor(code: number, details?: any); toJSON(): Object; static from(value: any): Status; } // ==== ./src/url.js ==== class URL { protocol: string; protocolSeparator: string; credhost: string; cred: string; username: string; password: string; host: string; hostname: string; port: string; origin: string; path: string; pathname: string; segment1: string; segment2: string; search: string; query: Query; params: Record<string, string | string[] | undefined>; hash: string; constructor(url: string, base?: string | URL | Location); setQuery(query: string | Query, remove?: boolean | string[]): URL; addToQuery(query: Query): URL; removeFromQuery(query: string | string[]): URL; update(): URL; toString(): string; static parse(url: string): URL; static readonly parseQueryString: QueryString["parse"]; static readonly stringifyQueryString: QueryString["stringify"]; static toMatcher(pattern: string | RegExp): RegExp; static match(pattern: string | RegExp, url: string | URL): Record<string, string | undefined>; } // ==== ./src/pilot.js ==== export type AccessFunction = (route: Route) => Promise<void>; export interface PilotRouteOption { url?: RouteUrlObject; } export interface PilotRouteOptions { url?: string; access?: AccessFunction; } export type PilotRouteMap = PilotRouteOptions | Record<string, PilotRouteOption | undefined>; export interface PilotNavDetails { initiator?: string; replaceState?: boolean; force?: boolean; } export interface PilotCompatibleLogger { add(key: string, details?: any); call(key: string, details: any, wrappedContent: () => void); } export type PilotListenFilter = (url: string) => boolean; export interface PilotListenOptions { logger?: PilotCompatibleLogger; autoStart?: boolean; filter?: PilotListenFilter; replaceState?: boolean; } } class Pilot extends Emitter { model: Object; request: Pilot.Request; route?: Pilot.Route; activeRoute?: Pilot.Route; activeUrl: Pilot.URL; url?: Pilot.URL; activeRequest?: Pilot.Request; routes: Pilot.Route[]; constructor(map: Pilot.PilotRouteMap); getUrl(id: string, params?: Record<string, string | undefined>, query?: Pilot.Query | 'inherit'): string; go(id: string, params?: Record<string, string | undefined>, query?: Pilot.Query | 'inherit', details?: Object): Promise<any>; nav(href: string | Pilot.URL | Request, details?: Pilot.PilotNavDetails): Promise<any>; listenFrom(target: HTMLElement, options: Pilot.PilotListenOptions); reload(); on(event: 'before-route', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request) => any): this; on(event: 'error', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request, error: unknown) => any): this; on(event: 'route-fail', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request, currentRoute: Pilot.Route, error: unknown) => any): this; on(event: 'route', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request, currentRoute: Pilot.Route) => any): this; on(event: 'route-end', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request, currentRoute: Pilot.Route) => any): this; on(event: 'beforereload', fn: (event: Emitter.Event<Pilot>) => any): this; on(event: 'reload', fn: (event: Emitter.Event<Pilot>) => any): this; on(event: 'reloadend', fn: (event: Emitter.Event<Pilot, { cancelled: boolean }>) => any): this; on(events: string, fn: EventListener): this; one(event: 'before-route', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request) => any): this; one(event: 'error', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request, error: unknown) => any): this; one(event: 'route-fail', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request, currentRoute: Pilot.Route, error: unknown) => any): this; one(event: 'route', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request, currentRoute: Pilot.Route) => any): this; one(event: 'route-end', fn: (event: Emitter.Event<Pilot, Pilot.PilotNavDetails>, req: Request, currentRoute: Pilot.Route) => any): this; one(event: 'beforereload', fn: (event: Emitter.Event<Pilot>) => any): this; one(event: 'reload', fn: (event: Emitter.Event<Pilot>) => any): this; one(event: 'reloadend', fn: (event: Emitter.Event<Pilot, { cancelled: boolean }>) => any): this; one(events: string, fn: EventListener): this; static create(map: Pilot.PilotRouteMap): Pilot; static readonly queryString: Pilot.QueryString; static readonly version: string; } export default Pilot; }
the_stack
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { GraphVizComponent } from './graph-viz.component'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { MockTranslatePipe } from 'tests/unit-test-utils'; import { GraphDetailService } from './graph-detail.service'; import { DeviceInfoService } from 'services/contextual/device-info.service'; import { PlayerPositionService } from 'pages/exploration-player-page/services/player-position.service'; import { EventEmitter } from '@angular/core'; import { FocusManagerService } from 'services/stateful/focus-manager.service'; import { I18nLanguageCodeService } from 'services/i18n-language-code.service'; describe('GraphVizComponent', () => { let component: GraphVizComponent; let graphDetailService: GraphDetailService; let deviceInfoService: DeviceInfoService; let playerPositionService: PlayerPositionService; let focusManagerService: FocusManagerService; let fixture: ComponentFixture<GraphVizComponent>; let i18nLanguageCodeService: I18nLanguageCodeService; let mockNewCardAvailableEmitter = new EventEmitter(); beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [GraphVizComponent, MockTranslatePipe], providers: [ GraphDetailService, DeviceInfoService ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { graphDetailService = TestBed.inject(GraphDetailService); deviceInfoService = TestBed.inject(DeviceInfoService); playerPositionService = TestBed.get(PlayerPositionService); focusManagerService = TestBed.inject(FocusManagerService); fixture = TestBed.createComponent(GraphVizComponent); component = fixture.componentInstance; i18nLanguageCodeService = TestBed.inject(I18nLanguageCodeService); spyOn(i18nLanguageCodeService, 'isCurrentLanguageRTL').and.returnValue( true); // Graph visulization // 1 // p----------p // - // 1 - // - // - // - p // p // // Note: Here 'p' represents the points, '-' represents the line and the // number above the line represents it's weight. // // These values are random, however the values have been injected into the // code during execution via the console to test if the values are valid. // I have used round number for x. y to make the tests easier to // understand. There is one vertex with floating point number to make sure // that the tests do not fail when a floating point number is used. component.graph = { vertices: [ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' } ], isDirected: false, isWeighted: true, isLabeled: false, edges: [ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ] }; component.canAddVertex = true; component.canDeleteVertex = true; component.canMoveVertex = true; component.canEditVertexLabel = true; component.canAddEdge = true; component.canDeleteEdge = true; component.canEditEdgeWeight = true; component.interactionIsActive = true; component.canEditOptions = true; }); // This compoenent gets executed when a graph made is diaplyed in the editor // or the interaction in the player. it('should initialise component, when a graph is displayed', () => { component.ngOnInit(); // Only the basic values are initialised in ngOnInit() function. The rest // of the values are initialised in ngAfterViewInit(), .i.e, after the // initialisation of the components view is completed. expect(component.VERTEX_RADIUS).toBe(graphDetailService.VERTEX_RADIUS); expect(component.EDGE_WIDTH).toBe(graphDetailService.EDGE_WIDTH); expect(component.selectedEdgeWeightValue).toBe(0); expect(component.shouldShowWrongWeightWarning).toBe(false); expect(component.isMobile).toBe(false); }); it('should set isMobile to true on initailisation if device' + ' used by the user is a mobile', () => { spyOn(deviceInfoService, 'isMobileDevice').and.returnValue(true); component.ngOnInit(); expect(component.isMobile).toBe(true); }); it('should reset current mode when user submits answer', () => { spyOnProperty(playerPositionService, 'onNewCardAvailable').and.returnValue( mockNewCardAvailableEmitter); // Function ngOnInit is run to add the componentSubscriptions. component.ngOnInit(); // Pre-check. expect(component.state.currentMode).toBe(0); mockNewCardAvailableEmitter.emit(); expect(component.state.currentMode).toBeNull(); }); it('should get RTL language status correctly', () => { expect(component.isLanguageRTL()).toEqual(true); }); it('should set graph properties after the view is initialized', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ width: 120, getAttribute: (attr) => { if (attr === 'height') { return 250; } }, getBBox: () => { return { height: 120, width: 527, x: 144, y: -14, }; }, }])); spyOn(component, 'init').and.stub(); component.ngAfterViewInit(); expect(component.vizWidth).toBe(120); expect(component.graphOptions).toEqual([{ text: 'Labeled', option: 'isLabeled' }, { text: 'Directed', option: 'isDirected' }, { text: 'Weighted', option: 'isWeighted' }]); expect(component.helpText).toBeNull(); expect(component.svgViewBox).toBe('0 0 671 250'); // Function init() is only called when the interaction is active. // Therefore, we verify that the value of interactionIsActive is true // before calling the function init(). expect(component.interactionIsActive).toBe(true); expect(component.init).toHaveBeenCalled(); }); it('should not intialise buttons and help text if interaction is not active' , () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ width: 120, getAttribute: (attr) => { if (attr === 'height') { return 250; } }, getBBox: () => { return { height: 120, width: 527, x: 144, y: -14, }; }, }])); spyOn(component, 'init').and.stub(); component.interactionIsActive = false; component.ngAfterViewInit(); // Function init() is only called when the interaction is active. // Therefore, we verify that the value of interactionIsActive is false // before verifying that the function init() is not called. expect(component.interactionIsActive).toBe(false); expect(component.init).not.toHaveBeenCalled(); }); it('should initialise buttons when interaction is initialised and is' + ' active', () => { expect(component.buttons).toEqual([]); component.initButtons(); expect(component.buttons).toEqual([{ text: '\uF0B2', description: 'I18N_INTERACTIONS_GRAPH_MOVE', mode: component._MODES.MOVE }, { text: '\uF0C1', description: 'I18N_INTERACTIONS_GRAPH_ADD_EDGE', mode: component._MODES.ADD_EDGE }, { text: '\uF067', description: 'I18N_INTERACTIONS_GRAPH_ADD_NODE', mode: component._MODES.ADD_VERTEX }, { text: '\uF068', description: 'I18N_INTERACTIONS_GRAPH_DELETE', mode: component._MODES.DELETE } ]); }); it('should not initialise buttons when all flags are false', () => { component.canMoveVertex = false; component.canAddEdge = false; component.canAddVertex = false; component.canDeleteVertex = false; component.canDeleteEdge = false; expect(component.buttons).toEqual([]); component.initButtons(); expect(component.buttons).toEqual([]); }); // Please note that the conditions where both canDeleteVertex // and canDeleteEdge are either true or false is tested above. it('should initialise delete button when canDeleteVertex' + ' flag is true', () => { component.canDeleteVertex = true; component.canDeleteEdge = false; expect(component.buttons).toEqual([]); component.initButtons(); expect(component.buttons).toContain({ text: '\uF068', description: 'I18N_INTERACTIONS_GRAPH_DELETE', mode: component._MODES.DELETE }); }); it('should initialise delete button when canDeleteEdge flag is true', () => { component.canDeleteVertex = false; component.canDeleteEdge = true; expect(component.buttons).toEqual([]); component.initButtons(); expect(component.buttons).toContain({ text: '\uF068', description: 'I18N_INTERACTIONS_GRAPH_DELETE', mode: component._MODES.DELETE }); }); // The init function is called after the ngAfterViewInit function is executed. it('should set help text when user in mobile and user can add edges', () => { spyOn(component, 'initButtons').and.callThrough(); component.canMoveVertex = false; component.canAddEdge = true; component.canAddVertex = false; component.canDeleteVertex = false; component.canDeleteEdge = false; component.isMobile = true; component.helpText = null; expect(component.state.currentMode).toBe(component._MODES.MOVE); expect(component.buttons).toEqual([]); component.init(); expect(component.initButtons).toHaveBeenCalled(); expect(component.buttons[0]).toEqual({ text: '\uF0C1', description: 'I18N_INTERACTIONS_GRAPH_ADD_EDGE', mode: component._MODES.ADD_EDGE }); expect(component.state.currentMode).toBe(component._MODES.ADD_EDGE); expect(component.isMobile).toBe(true); expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_EDGE_INITIAL_HELPTEXT'); }); it('should set help text when user in mobile and user can move' + ' vertices in the graph', () => { spyOn(component, 'initButtons').and.callThrough(); component.canMoveVertex = true; component.canAddEdge = false; component.canAddVertex = false; component.canDeleteVertex = false; component.canDeleteEdge = false; component.isMobile = true; component.helpText = null; component.state.currentMode = component._MODES.ADD_EDGE; expect(component.buttons).toEqual([]); component.init(); expect(component.initButtons).toHaveBeenCalled(); expect(component.buttons[0]).toEqual({ text: '\uF0B2', description: 'I18N_INTERACTIONS_GRAPH_MOVE', mode: component._MODES.MOVE }); expect(component.state.currentMode).toBe(component._MODES.MOVE); // The help text must be displayed only if the user is using a mobile. // Therefore we check that the value of isMobile is true. expect(component.isMobile).toBe(true); expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_MOVE_INITIAL_HELPTEXT'); }); it('should not set help text when user is in mobile and cannot move' + ' vertices and add edges', () => { spyOn(component, 'initButtons').and.callThrough(); component.canAddEdge = false; component.canMoveVertex = false; component.isMobile = true; component.helpText = null; expect(component.buttons).toEqual([]); expect(component.state.currentMode).toBe(component._MODES.MOVE); component.init(); expect(component.buttons[0]).toEqual({ text: '\uF067', description: 'I18N_INTERACTIONS_GRAPH_ADD_NODE', mode: component._MODES.ADD_VERTEX }); expect(component.state.currentMode).toBe(component._MODES.ADD_VERTEX); expect(component.initButtons).toHaveBeenCalled(); // The help text must be displayed only if the user is using a mobile. // Therefore we check that the value of isMobile is true. expect(component.isMobile).toBe(true); expect(component.helpText).toBe(''); }); it('should not set help text when user is not in mobile', () => { spyOn(component, 'initButtons').and.callThrough(); component.isMobile = false; component.helpText = null; component.init(); expect(component.initButtons).toHaveBeenCalled(); // The help text must be displayed only if the user is using a mobile. // Therefore we check that the value of isMobile is false to make sure that // the help text was not set. expect(component.isMobile).toBe(false); expect(component.helpText).toBe(''); }); it('should return default edge colour if interaction is not active', () => { component.interactionIsActive = false; expect(component.getEdgeColor(0)).toBe(component.DEFAULT_COLOR); }); it('should return delete edge colour when mouse hovers over edge' + 'to delete it', () => { component.interactionIsActive = true; component.state.hoveredEdge = 0; component.state.currentMode = component._MODES.DELETE; // Pre-check. expect(component.canDeleteEdge).toBe(true); expect(component.getEdgeColor(0)).toBe(component.DELETE_COLOR); }); it('should return hover edge colour when mouse hovers over edge', () => { component.interactionIsActive = true; component.state.hoveredEdge = 0; // Pre-check. // This check is to make sure the first if condition is false. expect(component.state.currentMode).not.toBe(component._MODES.DELETE); expect(component.interactionIsActive).toBe(true); expect(component.getEdgeColor(0)).toBe(component.HOVER_COLOR); }); it('should return select edge colour when mouse selects an edge', () => { component.interactionIsActive = true; component.state.selectedEdge = 0; // Pre-check. // This check is to make sure the first if condition is false. expect(component.state.currentMode).not.toBe(component._MODES.DELETE); expect(component.state.hoveredEdge).toBeNull(); expect(component.interactionIsActive).toBe(true); expect(component.getEdgeColor(0)).toBe(component.SELECT_COLOR); }); it('should return default edge colour when edge is not selected' + ' or hovered over', () => { component.interactionIsActive = true; component.state.selectedEdge = 0; // Pre-check. expect(component.state.hoveredEdge).toBeNull(); expect(component.interactionIsActive).toBe(true); expect(component.getEdgeColor(1)).toBe(component.DEFAULT_COLOR); }); // Tests for getVertexColor function. it('should return default vertex colour if interaction is not active', () => { component.interactionIsActive = false; expect(component.getVertexColor(0)).toBe(component.DEFAULT_COLOR); }); it('should return delete vertex colour when mouse hovers over vertex' + 'to delete it', () => { component.interactionIsActive = true; component.state.hoveredVertex = 0; component.state.currentMode = component._MODES.DELETE; // Pre-check. expect(component.canDeleteEdge).toBe(true); expect(component.interactionIsActive).toBe(true); expect(component.getVertexColor(0)).toBe(component.DELETE_COLOR); }); it('should return hover vertex colour when mouse drags a vertex', () => { component.interactionIsActive = true; component.state.currentlyDraggedVertex = 0; // Pre-check. // This check is to make sure the first if condition is false. expect(component.state.currentMode).not.toBe(component._MODES.DELETE); expect(component.interactionIsActive).toBe(true); expect(component.getVertexColor(0)).toBe(component.HOVER_COLOR); }); it('should return hover vertex colour when mouse hovers over vertex', () => { component.interactionIsActive = true; component.state.hoveredVertex = 0; // Pre-check. // This check is to make sure the first if condition is false. expect(component.state.currentMode).not.toBe(component._MODES.DELETE); expect(component.interactionIsActive).toBe(true); expect(component.getVertexColor(0)).toBe(component.HOVER_COLOR); }); it('should return select vertex colour when mouse selects an vertex', () => { component.interactionIsActive = true; component.state.selectedVertex = 0; // Pre-check. // This check is to make sure the first if condition is false. expect(component.state.currentMode).not.toBe(component._MODES.DELETE); expect(component.state.hoveredVertex).toBeNull(); expect(component.interactionIsActive).toBe(true); expect(component.getVertexColor(0)).toBe(component.SELECT_COLOR); }); it('should return default vertex colour when vertex is not selected' + ' or hovered over', () => { component.interactionIsActive = true; component.state.selectedVertex = 0; // Pre-check. expect(component.state.hoveredVertex).toBeNull(); expect(component.interactionIsActive).toBe(true); expect(component.getVertexColor(1)).toBe(component.DEFAULT_COLOR); }); it('should return arrow points when directed option is selected in' + 'the graph interaction', () => { spyOn(graphDetailService, 'getDirectedEdgeArrowPoints').and.callThrough(); // Pre-check; expect(component.graph).toEqual({ vertices: [ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' } ], isDirected: false, isWeighted: true, isLabeled: false, edges: [ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ] }); expect(component.getDirectedEdgeArrowPoints(0)) .toBe('196,50 186,45 186,55'); expect(graphDetailService.getDirectedEdgeArrowPoints).toHaveBeenCalledWith( component.graph, 0); }); it('should return edge center points when weighted option is selected in' + 'the graph interaction', () => { spyOn(graphDetailService, 'getEdgeCentre').and.callThrough(); // Pre-check; expect(component.graph).toEqual({ vertices: [ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' } ], isDirected: false, isWeighted: true, isLabeled: false, edges: [ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ] }); expect(component.getEdgeCentre(0)).toEqual({ x: 175, y: 50 }); expect(graphDetailService.getEdgeCentre).toHaveBeenCalledWith( component.graph, 0); }); it('should change location of vertex when dragged by mouse', () => { // These values are the coordinates of the mouse when the mouse event // was triggered. let dummyMouseEvent = new MouseEvent('mousemove', { clientX: 775, clientY: 307 }); spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ width: 120, getAttribute: (attr) => { if (attr === 'height') { return 250; } }, getBBox: () => { return { height: 120, width: 527, x: 144, y: -14, }; }, createSVGPoint: () => { return { matrixTransform: (matrix) => { return { x: 775, y: 307 }; }, x: 0, y: 0 }; }, getScreenCTM: () => { return { inverse: () => { return; } }; }, }])); spyOn(component, 'init').and.stub(); component.state.currentlyDraggedVertex = 0; component.state.vertexDragStartX = 0; component.state.vertexDragStartY = 0; component.state.mouseDragStartX = 0; component.state.mouseDragStartY = 0; component.ngAfterViewInit(); component.mousemoveGraphSVG(dummyMouseEvent); expect(component.state.mouseX).toBe(775); expect(component.state.mouseY).toBe(307); expect(component.graph.vertices[component.state.currentlyDraggedVertex]) .toEqual({x: 775, y: 307, label: ''}); }); it('should not change position of vertex when interaction is not' + ' active', () => { component.state.currentlyDraggedVertex = 0; component.interactionIsActive = false; // These values are the coordinates of the mouse when the mouse event // was triggered. let dummyMouseEvent = new MouseEvent('mousemove', { clientX: 775, clientY: 307 }); component.mousemoveGraphSVG(dummyMouseEvent); expect(component.state.mouseX).toBe(0); expect(component.state.mouseY).toBe(0); expect(component.graph.vertices[component.state.currentlyDraggedVertex]) .toEqual({ x: 150, y: 50, label: '' }); }); it('should add vertex when graph is clicked and interaction is' + ' active', () => { component.state.currentMode = component._MODES.ADD_VERTEX; component.state.mouseX = 20; component.state.mouseY = 20; expect(component.graph.vertices).toEqual([ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' } ]); component.onClickGraphSVG(); // Function onClickGraphSVG() must only run if the interaction is active. // Therefore the value of interactionIsActive is verified to be true before // the rest of the lines are executed. expect(component.interactionIsActive).toBe(true); expect(component.canAddEdge).toBe(true); expect(component.graph.vertices).toEqual([ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' }, { x: 20, y: 20, label: '' } ]); }); it('should not add vertex when the user is not allowed to add a' + ' vertex', () => { component.state.currentMode = component._MODES.ADD_VERTEX; component.state.mouseX = 20; component.state.mouseY = 20; component.interactionIsActive = true; component.canAddVertex = false; expect(component.graph.vertices).toEqual([ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' } ]); component.onClickGraphSVG(); // Function onClickGraphSVG() must only run if the interaction is active. // Therefore the value of interactionIsActive is verified to be true before // the rest of the lines are executed. expect(component.interactionIsActive).toBe(true); expect(component.graph.vertices).toEqual([ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' } ]); }); it('should not add vertex when interaction is not active', () => { component.state.currentMode = component._MODES.ADD_VERTEX; component.state.mouseX = 20; component.state.mouseY = 20; component.state.selectedVertex = 1; component.state.selectedEdge = 1; component.interactionIsActive = false; expect(component.graph.vertices).toEqual([ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' } ]); expect(component.state.selectedVertex).toBe(1); expect(component.state.selectedEdge).toBe(1); component.onClickGraphSVG(); // Function onClickGraphSVG() must only run if the interaction is active. // Therefore the value of interactionIsActive is verified to be false before // testing if a vertice was not added. expect(component.interactionIsActive).toBe(false); expect(component.graph.vertices).toEqual([ { x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' } ]); expect(component.state.selectedVertex).toBe(1); expect(component.state.selectedEdge).toBe(1); }); it('should set selectedVertex to null if hoveredVertex is null', () => { component.state.selectedVertex = 1; component.onClickGraphSVG(); expect(component.interactionIsActive).toBe(true); // This to test the pre-condition for setting selectedVertex to null. expect(component.state.hoveredVertex).toBeNull(); expect(component.state.selectedVertex).toBeNull(); }); it('should not set selectedVertex to null if hoveredVertex is not' + ' null', () => { component.state.selectedVertex = 1; component.state.hoveredVertex = 1; expect(component.state.selectedVertex).toBe(1); component.onClickGraphSVG(); expect(component.interactionIsActive).toBe(true); // This to test the pre-condition for setting selectedVertex to null. expect(component.state.hoveredVertex).toBe(1); expect(component.state.selectedVertex).toBe(1); }); it('should set selectedEdge to null if hoveredVertex is null', () => { component.state.selectedEdge = 1; component.onClickGraphSVG(); expect(component.interactionIsActive).toBe(true); // This to test the pre-condition for setting selectedEdge to null. expect(component.state.hoveredEdge).toBeNull(); expect(component.state.selectedEdge).toBeNull(); }); it('should not set selectedEdge to null if hoveredEdge is not' + ' null', () => { component.state.selectedEdge = 1; component.state.hoveredEdge = 1; expect(component.state.selectedEdge).toBe(1); component.onClickGraphSVG(); expect(component.interactionIsActive).toBe(true); // This to test the pre-condition for setting selectedVertex to null. expect(component.state.hoveredEdge).toBe(1); expect(component.state.selectedEdge).toBe(1); }); it('should toggle isLabeled flag when user selects Labeled option', () => { expect(component.graph.isLabeled).toBe(false); component.toggleGraphOption('isLabeled'); expect(component.graph.isLabeled).toBe(true); component.toggleGraphOption('isLabeled'); expect(component.graph.isLabeled).toBe(false); }); it('should toggle isWeighted option when user selects' + ' Weighted option', () => { expect(component.graph.isWeighted).toBe(true); component.toggleGraphOption('isWeighted'); expect(component.graph.isWeighted).toBe(false); component.toggleGraphOption('isWeighted'); expect(component.graph.isWeighted).toBe(true); }); it('should set isDirected to true when user selects Directed option', () => { expect(component.graph.isDirected).toBe(false); component.toggleGraphOption('isDirected'); expect(component.graph.isDirected).toBe(true); }); it('should set isDirected to false and extra edges are removed' + 'when user deselects Directed option', () => { component.graph.isDirected = true; component.graph.edges.push({ src: 2, weight: 1, dst: 1 }); component.toggleGraphOption('isDirected'); expect(component.graph.isDirected).toBe(false); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); }); it('should set to move mode when move button is clicked', () => { spyOn(Event.prototype, 'preventDefault'); component.state.addEdgeVertex = 1; component.state.selectedVertex = 1; component.state.selectedEdge = 1; component.state.currentlyDraggedVertex = 1; component.state.hoveredVertex = 1; component.state.currentMode = null; expect(component.helpText).toBe(''); let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.MOVE, dummyMouseEvent); // This is a pre-condition for setting a mode. expect(component.interactionIsActive).toBe(true); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.state.currentMode).toBe(component._MODES.MOVE); expect(component.state.addEdgeVertex).toBeNull(); expect(component.state.selectedVertex).toBeNull(); expect(component.state.selectedEdge).toBeNull(); expect(component.state.currentlyDraggedVertex).toBeNull(); expect(component.state.hoveredVertex).toBeNull(); // The value of help text changes only if user is using a mobile. expect(component.helpText).toBeNull(); }); it('should set helkp text for move button if user is using a mobile', () => { spyOn(Event.prototype, 'preventDefault'); component.isMobile = true; expect(component.helpText).toBe(''); let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.MOVE, dummyMouseEvent); // This is a pre-condition for setting a mode. expect(component.interactionIsActive).toBe(true); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.state.currentMode).toBe(component._MODES.MOVE); // The value of help text changes only if user is using a mobile. expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_MOVE_INITIAL_HELPTEXT'); }); it('should set to add edge mode when add edge button is clicked', () => { spyOn(Event.prototype, 'preventDefault'); component.state.addEdgeVertex = 1; component.state.selectedVertex = 1; component.state.selectedEdge = 1; component.state.currentlyDraggedVertex = 1; component.state.hoveredVertex = 1; component.state.currentMode = null; expect(component.helpText).toBe(''); let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.ADD_EDGE, dummyMouseEvent); // This is a pre-condition for setting a mode. expect(component.interactionIsActive).toBe(true); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.state.currentMode).toBe(component._MODES.ADD_EDGE); expect(component.state.addEdgeVertex).toBeNull(); expect(component.state.selectedVertex).toBeNull(); expect(component.state.selectedEdge).toBeNull(); expect(component.state.currentlyDraggedVertex).toBeNull(); expect(component.state.hoveredVertex).toBeNull(); // The value of help text changes only if user is using a mobile. expect(component.helpText).toBeNull(); }); it('should set help text for add edge button if user is using mobile', () => { spyOn(Event.prototype, 'preventDefault'); component.isMobile = true; expect(component.helpText).toBe(''); let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.ADD_EDGE, dummyMouseEvent); // This is a pre-condition for setting a mode. expect(component.interactionIsActive).toBe(true); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.state.currentMode).toBe(component._MODES.ADD_EDGE); // The value of help text changes only if user is using a mobile. expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_EDGE_INITIAL_HELPTEXT'); }); it('should set to add edge mode when add edge button is clicked', () => { spyOn(Event.prototype, 'preventDefault'); component.state.addEdgeVertex = 1; component.state.selectedVertex = 1; component.state.selectedEdge = 1; component.state.currentlyDraggedVertex = 1; component.state.hoveredVertex = 1; component.state.currentMode = null; expect(component.helpText).toBe(''); let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.ADD_VERTEX, dummyMouseEvent); // This is a pre-condition for setting a mode. expect(component.interactionIsActive).toBe(true); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.state.currentMode).toBe(component._MODES.ADD_VERTEX); expect(component.state.addEdgeVertex).toBeNull(); expect(component.state.selectedVertex).toBeNull(); expect(component.state.selectedEdge).toBeNull(); expect(component.state.currentlyDraggedVertex).toBeNull(); expect(component.state.hoveredVertex).toBeNull(); // The value of help text changes only if user is using a mobile. expect(component.helpText).toBeNull(); }); it('should set help text to null for add vertex button if user is' + ' using mobile', () => { spyOn(Event.prototype, 'preventDefault'); component.isMobile = true; expect(component.helpText).toBe(''); let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.ADD_VERTEX, dummyMouseEvent); // This is a pre-condition for setting a mode. expect(component.interactionIsActive).toBe(true); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.state.currentMode).toBe(component._MODES.ADD_VERTEX); // The value of help text changes only if user is using a mobile. expect(component.helpText).toBeNull(); }); it('should set to add delete mode when delete button is clicked', () => { spyOn(Event.prototype, 'preventDefault'); component.state.addEdgeVertex = 1; component.state.selectedVertex = 1; component.state.selectedEdge = 1; component.state.currentlyDraggedVertex = 1; component.state.hoveredVertex = 1; component.state.currentMode = null; expect(component.helpText).toBe(''); let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.DELETE, dummyMouseEvent); // This is a pre-condition for setting a mode. expect(component.interactionIsActive).toBe(true); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.state.currentMode).toBe(component._MODES.DELETE); expect(component.state.addEdgeVertex).toBeNull(); expect(component.state.selectedVertex).toBeNull(); expect(component.state.selectedEdge).toBeNull(); expect(component.state.currentlyDraggedVertex).toBeNull(); expect(component.state.hoveredVertex).toBeNull(); // The value of help text changes only if user is using a mobile. expect(component.helpText).toBeNull(); }); it('should set help text to null for delete button if user is' + ' using mobile', () => { spyOn(Event.prototype, 'preventDefault'); component.isMobile = true; expect(component.helpText).toBe(''); let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.DELETE, dummyMouseEvent); // This is a pre-condition for setting a mode. expect(component.interactionIsActive).toBe(true); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.state.currentMode).toBe(component._MODES.DELETE); // The value of help text changes only if user is using a mobile. expect(component.helpText).toBeNull(); }); it('should set mode if interaction is not active', () => { spyOn(Event.prototype, 'preventDefault'); spyOn(component, 'setMode'); component.interactionIsActive = false; let dummyMouseEvent = new MouseEvent('click'); component.onClickModeButton(component._MODES.DELETE, dummyMouseEvent); expect(component.setMode).not.toHaveBeenCalled(); }); it('should delete vertex when user clicks on the vertex', () => { component.state.currentMode = component._MODES.DELETE; spyOn(component, 'deleteVertex').and.callThrough(); expect(component.graph.vertices).toEqual([{ x: 150, y: 50, label: '' }, { x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' }]); component.onClickVertex(0); expect(component.deleteVertex).toHaveBeenCalledWith(0); expect(component.graph.vertices).toEqual([{ x: 200, y: 50, label: '' }, { x: 150, y: 100, label: '' }, { x: 196.60939025878906, y: 95.05902099609375, label: '' }]); }); it('should add vertex when user clicks on the graph', () => { component.state.currentMode = component._MODES.ADD_VERTEX; component.graph.isLabeled = true; spyOn(component, 'beginEditVertexLabel').and.callThrough(); spyOn(focusManagerService, 'setFocus'); expect(component.state.selectedVertex).toBeNull(); component.onClickVertex(0); expect(component.beginEditVertexLabel).toHaveBeenCalledWith(0); expect(component.state.selectedVertex).toBe(0); expect(focusManagerService.setFocus) .toHaveBeenCalledWith('vertexLabelEditBegun'); }); it('should start adding edge when user clicks a vertex in a mobile', () => { component.state.currentMode = component._MODES.ADD_EDGE; component.isMobile = true; spyOn(component, 'onTouchInitialVertex').and.callThrough(); spyOn(component, 'beginAddEdge').and.callThrough(); expect(component.state.hoveredVertex).toBeNull(); expect(component.state.addEdgeVertex).toBeNull(); expect(component.helpText).toBe(''); component.onClickVertex(0); expect(component.onTouchInitialVertex).toHaveBeenCalledWith(0); expect(component.state.hoveredVertex).toBe(0); expect(component.beginAddEdge).toHaveBeenCalledWith(0); expect(component.state.addEdgeVertex).toBe(0); expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_EDGE_FINAL_HELPTEXT'); }); it('should move vertex when user clicks a vertex in a mobile', () => { component.state.currentMode = component._MODES.MOVE; component.isMobile = true; component.state.mouseX = 20; component.state.mouseY = 20; spyOn(component, 'onTouchInitialVertex').and.callThrough(); spyOn(component, 'beginDragVertex').and.callThrough(); expect(component.state.currentlyDraggedVertex).toBeNull(); expect(component.state.hoveredVertex).toBeNull(); expect(component.state.vertexDragStartX).toBe(0); expect(component.state.vertexDragStartY).toBe(0); expect(component.state.mouseDragStartX).toBe(0); expect(component.state.mouseDragStartY).toBe(0); expect(component.helpText).toBe(''); component.onClickVertex(0); expect(component.onTouchInitialVertex).toHaveBeenCalledWith(0); expect(component.state.hoveredVertex).toBe(0); expect(component.beginDragVertex).toHaveBeenCalledWith(0); expect(component.state.currentlyDraggedVertex).toBe(0); expect(component.state.vertexDragStartX).toBe(150); expect(component.state.vertexDragStartY).toBe(50); expect(component.state.mouseDragStartX).toBe(20); expect(component.state.mouseDragStartY).toBe(20); expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_MOVE_FINAL_HELPTEXT'); }); it('should show help text to start edge creation when a user is using a' + ' mobile', () => { component.state.addEdgeVertex = 0; component.state.hoveredVertex = 1; component.isMobile = true; expect(component.helpText).toBe(''); component.onClickVertex(0); expect(component.state.hoveredVertex).toBeNull(); expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_EDGE_INITIAL_HELPTEXT'); expect(component.state.addEdgeVertex).toBeNull(); }); it('should stop moving vertex when user is using a mobile clicks on the' + ' graph', () => { component.state.currentMode = component._MODES.MOVE; component.state.addEdgeVertex = 1; component.state.hoveredVertex = 1; component.state.currentlyDraggedVertex = 1; component.isMobile = true; spyOn(component, 'onTouchFinalVertex').and.callThrough(); spyOn(component, 'endDragVertex').and.callThrough(); expect(component.helpText).toBe(''); component.onClickVertex(0); expect(component.onTouchFinalVertex).toHaveBeenCalledWith(0); expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_MOVE_INITIAL_HELPTEXT'); expect(component.endDragVertex).toHaveBeenCalled(); expect(component.state.hoveredVertex).toBeNull(); }); it('should add an edge when user using a mobile clicks on the final' + ' vertex', () => { component.state.currentMode = component._MODES.ADD_EDGE; component.state.addEdgeVertex = 1; component.state.hoveredVertex = 1; component.state.currentlyDraggedVertex = 1; component.isMobile = true; spyOn(component, 'onTouchFinalVertex').and.callThrough(); spyOn(component, 'tryAddEdge').and.callThrough(); spyOn(component, 'endAddEdge').and.callThrough(); expect(component.helpText).toBe(''); component.onClickVertex(0); expect(component.onTouchFinalVertex).toHaveBeenCalledWith(0); expect(component.tryAddEdge).toHaveBeenCalledWith(1, 0); expect(component.endAddEdge).toHaveBeenCalled(); expect(component.helpText) .toBe('I18N_INTERACTIONS_GRAPH_EDGE_INITIAL_HELPTEXT'); expect(component.state.hoveredVertex).toBeNull(); }); it('should add edge when user presses mouse down.', () => { component.state.currentMode = component._MODES.ADD_EDGE; spyOn(component, 'beginAddEdge').and.callThrough(); expect(component.state.addEdgeVertex).toBeNull(); component.onMousedownVertex(0); expect(component.isMobile).toBe(false); expect(component.canAddEdge).toBe(true); expect(component.beginAddEdge).toHaveBeenCalledWith(0); expect(component.state.addEdgeVertex).toBe(0); }); it('should drag vertex when user presses mouse down.', () => { component.state.currentMode = component._MODES.MOVE; component.state.mouseX = 20; component.state.mouseY = 20; spyOn(component, 'beginDragVertex').and.callThrough(); expect(component.state.addEdgeVertex).toBeNull(); expect(component.state.currentlyDraggedVertex).toBeNull(); expect(component.state.vertexDragStartX).toBe(0); expect(component.state.vertexDragStartY).toBe(0); expect(component.state.mouseDragStartX).toBe(0); expect(component.state.mouseDragStartY).toBe(0); component.onMousedownVertex(0); expect(component.isMobile).toBe(false); expect(component.canMoveVertex).toBe(true); expect(component.beginDragVertex).toHaveBeenCalledWith(0); expect(component.state.currentlyDraggedVertex).toBe(0); expect(component.state.vertexDragStartX).toBe(150); expect(component.state.vertexDragStartY).toBe(50); expect(component.state.mouseDragStartX).toBe(20); expect(component.state.mouseDragStartY).toBe(20); }); it('should not run onMousedownVertex when user uses a mobile phone', () => { component.isMobile = true; spyOn(component, 'beginAddEdge'); spyOn(component, 'beginDragVertex'); expect(component.state.addEdgeVertex).toBeNull(); component.onMousedownVertex(0); expect(component.isMobile).toBe(true); expect(component.beginAddEdge).not.toHaveBeenCalled(); expect(component.beginDragVertex).not.toHaveBeenCalled(); }); it('should not run onMouseleaveVertex when user uses a mobile phone', () => { component.isMobile = true; expect(component.state.hoveredVertex).toBeNull(); component.onMouseleaveVertex(0); expect(component.state.hoveredVertex).toBeNull(); }); it('should set hoveredVertex to null from index when' + ' once user\'s mouse leaves vertex', () => { component.state.hoveredVertex = 0; component.onMouseleaveVertex(0); expect(component.state.hoveredVertex).toBeNull(); }); it('should edit vertex label when user clicks the label', () => { component.graph.isLabeled = true; spyOn(component, 'beginEditVertexLabel').and.callThrough(); spyOn(focusManagerService, 'setFocus'); expect(component.state.selectedVertex).toBeNull(); component.onClickVertexLabel(0); expect(component.canEditVertexLabel).toBe(true); expect(component.state.hoveredVertex).toBeNull(); expect(component.beginEditVertexLabel).toHaveBeenCalledWith(0); expect(focusManagerService.setFocus) .toHaveBeenCalledWith('vertexLabelEditBegun'); }); it('should delete edge when user clicks the edge', () => { component.state.currentMode = component._MODES.DELETE; component.state.hoveredEdge = 0; spyOn(component, 'deleteEdge').and.callThrough(); expect(component.canDeleteEdge).toBe(true); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); component.onClickEdge(0); expect(component.deleteEdge).toHaveBeenCalledWith(0); expect(component.state.hoveredEdge).toBeNull(); expect(component.graph.edges).toEqual([ { src: 1, weight: 1, dst: 2 } ]); }); it('should edit edge weight when user clicks the edge weight', () => { component.state.hoveredEdge = 0; spyOn(focusManagerService, 'setFocus'); spyOn(component, 'beginEditEdgeWeight').and.callThrough(); expect(component.canDeleteEdge).toBe(true); expect(component.state.selectedEdge).toBeNull(); expect(component.selectedEdgeWeightValue).toBeUndefined(); expect(component.shouldShowWrongWeightWarning).toBeUndefined(); component.onClickEdge(0); expect(component.graph.isWeighted).toBe(true); expect(component.canEditEdgeWeight).toBe(true); expect(component.beginEditEdgeWeight).toHaveBeenCalledWith(0); expect(component.state.selectedEdge).toBe(0); expect(component.selectedEdgeWeightValue).toBe(1); expect(component.shouldShowWrongWeightWarning).toBe(false); expect(focusManagerService.setFocus) .toHaveBeenCalledWith('edgeWeightEditBegun'); }); // This function only executes on mouse actions. it('should not add edge when user is using a mobile', () => { component.isMobile = true; spyOn(component, 'tryAddEdge'); spyOn(component, 'endAddEdge'); spyOn(component, 'endDragVertex'); component.onMouseupDocument(); expect(component.tryAddEdge).not.toHaveBeenCalled(); expect(component.endAddEdge).not.toHaveBeenCalled(); expect(component.endDragVertex).not.toHaveBeenCalled(); }); it('should start adding edge when user\'s mouse button goes up', fakeAsync(() => { component.state.currentMode = component._MODES.ADD_EDGE; component.state.hoveredVertex = 2; component.state.addEdgeVertex = 0; spyOn(component, 'tryAddEdge').and.callThrough(); expect(component.isMobile).toBe(false); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); component.onMouseupDocument(); tick(10); expect(component.tryAddEdge).toHaveBeenCalledWith(0, 2); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 }, { src: 0, weight: 1, dst: 2 } ]); })); it('should not add edge if it is already present', fakeAsync(() => { component.state.currentMode = component._MODES.ADD_EDGE; component.state.hoveredVertex = 1; component.state.addEdgeVertex = 0; spyOn(component, 'tryAddEdge').and.callThrough(); expect(component.isMobile).toBe(false); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); component.onMouseupDocument(); tick(10); expect(component.tryAddEdge).toHaveBeenCalledWith(0, 1); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); })); it('should not add edge if the start and end are same', fakeAsync(() => { component.state.currentMode = component._MODES.ADD_EDGE; component.state.hoveredVertex = 0; component.state.addEdgeVertex = 0; spyOn(component, 'tryAddEdge').and.callThrough(); expect(component.isMobile).toBe(false); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); component.onMouseupDocument(); tick(10); expect(component.tryAddEdge).toHaveBeenCalledWith(0, 0); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); })); it('should not add edge if an edge is already present between' + 'the destination and source for a non directed graph', fakeAsync(() => { component.state.currentMode = component._MODES.ADD_EDGE; component.state.hoveredVertex = 0; component.state.addEdgeVertex = 1; spyOn(component, 'tryAddEdge').and.callThrough(); spyOn(component, 'endAddEdge').and.callThrough(); expect(component.isMobile).toBe(false); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); component.onMouseupDocument(); tick(10); expect(component.tryAddEdge).toHaveBeenCalledWith(1, 0); expect(component.graph.edges).toEqual([ { src: 0, weight: 1, dst: 1 }, { src: 1, weight: 1, dst: 2 } ]); expect(component.endAddEdge).toHaveBeenCalled(); })); it('should end add edge when user clicks anything other than a' + ' vertex', fakeAsync(() => { component.state.currentMode = component._MODES.ADD_EDGE; component.state.addEdgeVertex = 0; spyOn(component, 'endAddEdge').and.callThrough(); component.onMouseupDocument(); tick(10); expect(component.state.hoveredVertex).toBeNull(); expect(component.endAddEdge).toHaveBeenCalled(); expect(component.state.addEdgeVertex).toBeNull(); })); it('should end moving vertex when user releases mouse button', fakeAsync(() => { component.state.currentMode = component._MODES.MOVE; component.state.currentlyDraggedVertex = 0; spyOn(component, 'endDragVertex').and.callThrough(); component.onMouseupDocument(); tick(10); expect(component.endDragVertex).toHaveBeenCalled(); expect(component.state.currentlyDraggedVertex).toBeNull(); })); it('should return selected vertex label when called', () => { component.state.selectedVertex = 0; component.graph.vertices[0].label = 'vertex_label'; spyOnProperty(component, 'selectedVertexLabel', 'get').and.callThrough(); expect(component.selectedVertexLabel).toBe('vertex_label'); }); it('should return empty string when no vertex is selected', () => { component.state.selectedVertex = null; component.graph.vertices[0].label = 'vertex_label'; spyOnProperty(component, 'selectedVertexLabel', 'get').and.callThrough(); expect(component.selectedVertexLabel).toBe(''); }); it('should set selected vertex label when called', () => { component.state.selectedVertex = 0; component.graph.vertices[0].label = 'vertex_label'; spyOnProperty(component, 'selectedVertexLabel', 'set').and .callThrough(); component.selectedVertexLabel = 'test'; expect(component.graph.vertices[0].label).toBe('test'); }); it('should set selected edge weight when called', () => { component.selectedEdgeWeightValue = 0; spyOnProperty(component, 'selectedEdgeWeight', 'set').and .callThrough(); component.selectedEdgeWeight = 2; expect(component.selectedEdgeWeightValue).toBe(2); }); it('should set selected edge weight to an empty string when' + ' null is passed', () => { component.selectedEdgeWeightValue = 0; spyOnProperty(component, 'selectedEdgeWeight', 'set').and .callThrough(); component.selectedEdgeWeight = null; expect(component.selectedEdgeWeightValue).toBe(''); }); it('should return selected edge weight when called', () => { component.state.selectedEdge = 0; component.selectedEdgeWeightValue = 1; spyOnProperty(component, 'selectedEdgeWeight', 'get').and.callThrough(); expect(component.selectedEdgeWeight).toBe(1); }); it('should return empty string when no edge is selected', () => { component.state.selectedEdge = null; spyOnProperty(component, 'selectedEdgeWeight', 'get').and.callThrough(); expect(component.selectedEdgeWeight).toBe(''); }); it('should return true when weight value is valid', () => { component.selectedEdgeWeightValue = 1; spyOn(component, 'isValidEdgeWeight').and.callThrough(); expect(component.isValidEdgeWeight()).toBe(true); }); it('should return false when weight value is invalid', () => { component.selectedEdgeWeightValue = 'invalid_value'; spyOn(component, 'isValidEdgeWeight').and.callThrough(); expect(component.isValidEdgeWeight()).toBe(false); }); it('should update edge weight when function is called', () => { component.selectedEdgeWeightValue = 2; component.state.selectedEdge = 0; expect(component.graph.edges[0].weight).toBe(1); component.onUpdateEdgeWeight(); expect(component.graph.edges[0].weight).toBe(2); expect(component.state.selectedEdge).toBeNull(); }); it('should edit edge weight when user clicks the edge weight', () => { spyOn(focusManagerService, 'setFocus'); spyOn(component, 'beginEditEdgeWeight').and.callThrough(); expect(component.canDeleteEdge).toBe(true); expect(component.state.selectedEdge).toBeNull(); expect(component.selectedEdgeWeightValue).toBeUndefined(); expect(component.shouldShowWrongWeightWarning).toBeUndefined(); component.onClickEdgeWeight(0); expect(component.graph.isWeighted).toBe(true); expect(component.canEditEdgeWeight).toBe(true); expect(component.beginEditEdgeWeight).toHaveBeenCalledWith(0); expect(component.state.selectedEdge).toBe(0); expect(component.selectedEdgeWeightValue).toBe(1); expect(component.shouldShowWrongWeightWarning).toBe(false); expect(focusManagerService.setFocus) .toHaveBeenCalledWith('edgeWeightEditBegun'); }); });
the_stack
'use strict'; import { isObject } from 'chord/base/common/checker'; import { decodeHtml } from 'chord/base/browser/htmlContent'; import { IAudio } from 'chord/music/api/audio'; import { ISong } from 'chord/music/api/song'; import { ILyric } from 'chord/music/api/lyric'; import { IAlbum } from 'chord/music/api/album'; import { IArtist } from 'chord/music/api/artist'; import { ICollection } from 'chord/music/api/collection'; // import { IGenre } from "chord/music/api/genre"; import { ITag } from "chord/music/api/tag"; import { IUserProfile } from "chord/music/api/user"; import { getSongUrl, getAlbumUrl, getArtistUrl, getCollectionUrl, getUserUrl, getSongId, getAlbumId, getArtistId, getCollectionId, getUserId, } from "chord/music/common/origin"; import { makeLyric as _makeLyric } from 'chord/music/utils/lyric'; const _origin = 'qq'; const _getSongUrl: (id: string) => string = getSongUrl.bind(null, _origin); const _getSongId: (id: string) => string = getSongId.bind(null, _origin); const _getAlbumUrl: (id: string) => string = getAlbumUrl.bind(null, _origin); const _getAlbumId: (id: string) => string = getAlbumId.bind(null, _origin); const _getArtistUrl: (id: string) => string = getArtistUrl.bind(null, _origin); const _getArtistId: (id: string) => string = getArtistId.bind(null, _origin); const _getCollectionUrl: (id: string) => string = getCollectionUrl.bind(null, _origin); const _getCollectionId: (id: string) => string = getCollectionId.bind(null, _origin); const _getUserUrl: (id: string) => string = getUserUrl.bind(null, _origin); const _getUserId: (id: string) => string = getUserId.bind(null, _origin); export const AUDIO_FORMAT_MAP = { '96m4a': 'C400', '128mp3': 'M500', '320mp3': 'M800', '1ape': 'A000', '1000flac': 'F000', }; export const KBPS_MAP = { '96aac': 96, '128': 128, '320': 320, '128mp3': 128, '320mp3': 320, // ape file is not accessable, so missing it 'ape': 1, 'flac': 1000, }; export const FORMAT_MAP = { '96aac': 'm4a', '128': 'mp3', '320': 'mp3', '128mp3': 'mp3', '320mp3': 'mp3', 'ape': 'ape', 'flac': 'flac', }; function getQQAlbumCoverUrl(mid: string): string { return 'http://y.gtimg.cn/music/photo_new/T002R300x300M000' + mid + '.jpg?max_age=2592000'; } function getQQArtistAvatarUrl(mid: string): string { return 'http://y.gtimg.cn/music/photo_new/T001R300x300M000' + mid + '.jpg?max_age=2592000'; } function makeAudios(info: any): Array<IAudio> { return Object.keys(info) .filter(key => FORMAT_MAP[key.replace(/size_?/, '').toLowerCase()] && key.startsWith('size') && info[key]) .map(key => { let chunk = key.replace(/size_?/, '').toLowerCase(); let format = FORMAT_MAP[chunk]; let kbps = KBPS_MAP[chunk]; let size: number = info[key]; let audio: IAudio = { format, kbps, size, }; return audio; }) .sort((x, y) => y.kbps - x.kbps); } export function makeSong(info: any): ISong { let songInfo = info['track_info'] || info; let otherInfo = info['info'] || []; let songOriginalId = songInfo['id'] || songInfo['songid']; // filter songs which have not original id // e.g. https://y.qq.com/n/yqq/song2/112/0045hAmL0VbG1A.html at #19 if (!songOriginalId) return null; songOriginalId = songOriginalId.toString(); let songMid = songInfo['mid'] || songInfo['songmid']; let songMediaMid = songInfo['strMediaMid'] || (songInfo['file'] ? songInfo['file']['media_mid'] : songMid); let songName = songInfo['name'] || songInfo['songname']; songName = decodeHtml(songName); let albumOriginalId = songInfo['album'] ? songInfo['album']['id'].toString() : songInfo['albumid'].toString(); let albumMid = songInfo['album'] ? songInfo['album']['mid'] : songInfo['albummid']; let albumName = songInfo['album'] ? songInfo['album']['name'] : songInfo['albumname']; albumName = decodeHtml(albumName); let albumCoverUrl = getQQAlbumCoverUrl(albumMid); let artistOriginalId = songInfo['singer'][0]['id'].toString(); let artistMid = songInfo['singer'][0]['mid']; let artistName = songInfo['singer'][0]['name']; artistName = decodeHtml(artistName); let artistAvatarUrl = getQQArtistAvatarUrl(artistMid); let track = songInfo['index_album'] || songInfo['belongCD']; let cdSerial = (songInfo['index_cd'] || songInfo['cdIdx']) + 1; let songWriters = []; let songWritersInfo = otherInfo.filter(_info => _info['作词'] == 'title' && _info['content'][0])[0]; if (songWritersInfo) { songWriters = songWritersInfo['content'].map(_info => _info['value']); } let singers = []; let singersInfo = otherInfo.filter(_info => _info['title'] == '演唱者' && _info['content'][0])[0]; if (singersInfo) { singers = singersInfo['content'].map(_info => _info['value']); } let composer = ''; let composerInfo = otherInfo.filter(_info => _info['title'] == '作曲' && _info['content'][0])[0]; if (composerInfo) { composer = composerInfo['content'][0]['value']; } let genres = []; let genresInfo = otherInfo.filter(_info => _info['title'] == '歌曲流派' && _info['content'][0])[0]; if (genresInfo) { genres = genresInfo['content'].map(_info => { return { id: _info['id'].toString(), name: _info['value'], }; }); } let audios = makeAudios(songInfo['file'] || songInfo); let song: ISong = { songId: _getSongId(songOriginalId), type: 'song', origin: _origin, songOriginalId, songMid, songMediaMid, url: _getSongUrl(songMid), songName, subTitle: songInfo['subtitle'] || '', songWriters, singers, albumId: _getAlbumId(albumOriginalId), albumOriginalId, albumMid, albumName, albumCoverUrl, artistId: _getArtistId(artistOriginalId), artistOriginalId, artistMid, artistName, artistAvatarUrl, composer, track, cdSerial, genres, // millisecond duration: songInfo['interval'] * 1000, releaseDate: Date.parse(songInfo['time_public']) || 0, playCount: 0, audios, }; return song; } export function makeSongs(info: any): Array<ISong> { return (info || []).map(songInfo => makeSong(songInfo)).filter(song => !!song); } export function makeLyric(songId: string, lyricInfo: string, transInfo: string): ILyric { if (!lyricInfo) return null; let lyric = _makeLyric(lyricInfo); let chunksMap = {}; lyric.chunks.forEach(chunk => chunksMap[chunk.point] = chunk); if (transInfo) { let trans = _makeLyric(transInfo); trans.chunks.forEach((chunk, index) => { let lyricChunk = chunksMap[chunk.point]; if (lyricChunk) lyricChunk.translation = chunk.text; }); } lyric.songId = _getSongId(songId); return lyric; } export function makeAlbum(info: any): IAlbum { let albumOriginalId = (info['id'] || info['albumid'] || info['albumID'] || info['album_id']).toString(); let albumMid = info['mid'] || info['album_mid'] || info['albumMID'] || info['albummid']; let albumName = info['name'] || info['album_name'] || info['albumName']; albumName = decodeHtml(albumName); let albumCoverUrl = getQQAlbumCoverUrl(albumMid); let artistOriginalId = info['singerid'] || info['singer_id'] || info['singerID']; let artistMid; let artistName; if (artistOriginalId) { artistOriginalId = artistOriginalId.toString(); artistMid = info['singermid'] || info['singer_mid'] || info['singerMID']; artistName = info['singername'] || info['singer_name'] || info['singerName']; } else { if (isObject(info['singers'])) { let singerInfo = info['singers'][0]; artistOriginalId = singerInfo['singer_id'].toString(); artistMid = singerInfo['singer_mid']; artistName = singerInfo['singer_name']; } else { throw new Error(`[Error] [qq.parser.makeAlbum]: can not parse info: ${JSON.stringify(info)}`); } } artistName = decodeHtml(artistName); let tags: Array<ITag> = info['genre'] ? [{ id: null, name: info['genre'] }] : []; let releaseDate = Date.parse(info['aDate'] || info['pub_time'] || info['publicTime'] || info['public_time']); let songs: Array<ISong> = (info['list'] || []).map(song => makeSong(song)).filter(song => !!song); let album: IAlbum = { albumId: _getAlbumId(albumOriginalId), type: 'album', origin: _origin, albumOriginalId: albumOriginalId, albumMid, url: _getAlbumUrl(albumMid), albumName, albumCoverUrl: albumCoverUrl, artistId: _getArtistId(artistOriginalId), artistOriginalId, artistMid, artistName, tags, description: info['desc'] || null, releaseDate, company: info['company'] || null, songs: songs, songCount: info['total_song_num'] || info['song_count'], }; return album; } export function makeAlbums(info: any): Array<IAlbum> { return (info || []).map(albumInfo => makeAlbum(albumInfo)); } export function makeArtist(info: any): IArtist { let artistOriginalId = (info['singer_id'] || info['id'] || info['singerid']).toString(); let artistMid = info['singer_mid'] || info['mid'] || info['singermid']; let artistName = info['singer_name'] || info['name'] || info['singername']; artistName = decodeHtml(artistName); let artistAvatarUrl = getQQArtistAvatarUrl(artistMid); let likeCount = info['num']; let artist: IArtist = { artistId: _getArtistId(artistOriginalId), type: 'artist', origin: _origin, artistOriginalId: artistOriginalId, artistMid, url: _getArtistUrl(artistMid), artistName, artistAvatarUrl: artistAvatarUrl, description: info['SingerDesc'], songs: [], albums: [], likeCount, }; return artist; } export function makeArtists(info: any): Array<IArtist> { return (info || []).map(artistInfo => makeArtist(artistInfo)); } export function makeCollection(info: any): ICollection { let collectionOriginalId = (info['disstid'] || info['dissid'] || info['tid'] || info['content_id']).toString(); let collectionCoverUrl = info['logo'] || info['imgurl'] || info['diss_cover'] || info['cover']; if (!collectionCoverUrl || !collectionCoverUrl.startsWith('http')) { collectionCoverUrl = 'http://y.gtimg.cn/mediastyle/global/img/cover_like.png?max_age=2592000'; } let collectionName = info['dissname'] || info['diss_name'] || info['title']; collectionName = decodeHtml(collectionName); let tags: Array<ITag> = (info['tags'] || []).map(tag => ({ id: tag['id'].toString(), name: tag['name'] })); let songs: Array<ISong> = (info['songlist'] || []).map(songInfo => makeSong(songInfo)).filter(song => !!song); let duration = songs.length != 0 ? songs.map(s => s.duration).reduce((x, y) => x + y) : null; let userOriginalId; let userMid; let userName; if (info['creator'] && !isObject(info['creator'])) { userOriginalId = info['creator']; userMid = info['creator']; userName = info['username']; } else { userOriginalId = info['creator'] ? (info['creator']['creator_uin'] || info['creator']['qq']).toString() : info['uin']; userMid = info['creator'] ? info['creator']['encrypt_uin'].toString() : (info['encrypt_uin'] || info['uin']); userName = info['creator'] ? info['creator']['name'] : info['nickname']; } let userId = _getUserId(userOriginalId); userName = decodeHtml(userName); let playCount = info['visitnum'] || info['listennum'] || info['listen_num']; let releaseDate = (info['ctime'] * 1000) || typeof (info['createtime']) == 'number' ? info['createtime'] * 1000 : Date.parse(info['createtime']); let songCount = info['total_song_num'] || info['song_count'] || info['songnum'] || info['song_cnt']; let collection: ICollection = { collectionId: _getCollectionId(collectionOriginalId), type: 'collection', origin: _origin, collectionOriginalId, url: _getCollectionUrl(collectionOriginalId), collectionName, collectionCoverUrl, userId, userMid, userName, // millisecond releaseDate, description: info['desc'] || info['introduction'], tags, duration, songs, songCount, playCount, }; return collection; } export function makeEmptyCollection(collectionOriginalId: string): ICollection { let collection: ICollection = { collectionId: _getCollectionId(collectionOriginalId), type: 'collection', origin: _origin, collectionOriginalId, url: _getCollectionUrl(collectionOriginalId), songs: [], }; return collection; } export function makeCollections(info: any): Array<ICollection> { return (info || []).map(collectionInfo => makeCollection(collectionInfo)); } export function makeUserProfile(info: any): IUserProfile { let userInfo = info['creator'] || info; let musicInfo = info['mymusic'] || info; let createdCollectionsInfo = info['mydiss'] || info; // qq number // if there is not qq number, using encrypt_uin let userOriginalId = (userInfo['uin'] || info['uin'] || info['encrypt_uin']).toString(); let userProfile = { userId: _getUserId(userOriginalId), type: 'userProfile', origin: _origin, userOriginalId, url: _getUserUrl(userOriginalId), userName: userInfo['nick'] || info['nick_name'], userMid: userInfo['encrypt_uin'] || info['encrypt_uin'], userAvatarUrl: userInfo['headpic'] || info['logo'], followerCount: info['listen_num'] != undefined ? info['listen_num'] : userInfo['nums']['fansnum'], followingCount: info['follow_num'] != undefined ? info['follow_num'] : userInfo['nums']['followusernum'], songCount: musicInfo[1] ? musicInfo[1]['num0'] : null, artistCount: userInfo['nums'] ? userInfo['nums']['followsingernum'] : null, albumCount: musicInfo[1] ? musicInfo[1]['num1'] : null, favoriteCollectionCount: musicInfo[1] ? musicInfo[1]['num2'] : null, createdCollectionCount: info['songlist_num'] != undefined ? info['songlist_num'] : createdCollectionsInfo['num'], description: info['desc'], }; return userProfile; } export function makeUserProfiles(info: any): Array<IUserProfile> { return (info || []).map(_info => makeUserProfile(_info)); }
the_stack
import { Binding, Expression } from 'aurelia-binding'; import { GlobalValidationConfiguration } from './config'; import { Validator } from './validator'; import { validateTrigger } from './validate-trigger'; import { getPropertyInfo } from './property-info'; import { ValidationRenderer, RenderInstruction } from './validation-renderer'; import { ValidateResult } from './validate-result'; import { ValidateInstruction } from './validate-instruction'; import { ControllerValidateResult } from './controller-validate-result'; import { PropertyAccessorParser, PropertyAccessor } from './property-accessor-parser'; import { ValidateEvent } from './validate-event'; /** * Orchestrates validation. * Manages a set of bindings, renderers and objects. * Exposes the current list of validation results for binding purposes. */ export class ValidationController { public static inject = [Validator, PropertyAccessorParser, GlobalValidationConfiguration]; // Registered bindings (via the validate binding behavior) private bindings = new Map<Binding, BindingInfo>(); // Renderers that have been added to the controller instance. private renderers: ValidationRenderer[] = []; /** * Validation results that have been rendered by the controller. */ private results: ValidateResult[] = []; /** * Validation errors that have been rendered by the controller. */ public errors: ValidateResult[] = []; /** * Whether the controller is currently validating. */ public validating: boolean = false; // Elements related to validation results that have been rendered. private elements = new Map<ValidateResult, Element[]>(); // Objects that have been added to the controller instance (entity-style validation). private objects = new Map<any, any>(); /** * The trigger that will invoke automatic validation of a property used in a binding. */ public validateTrigger: validateTrigger; // Promise that resolves when validation has completed. private finishValidating: Promise<any> = Promise.resolve(); private eventCallbacks: ((event: ValidateEvent) => void)[] = []; constructor( private validator: Validator, private propertyParser: PropertyAccessorParser, config?: GlobalValidationConfiguration, ) { this.validateTrigger = config instanceof GlobalValidationConfiguration ? config.getDefaultValidationTrigger() : GlobalValidationConfiguration.DEFAULT_VALIDATION_TRIGGER; } /** * Subscribe to controller validate and reset events. These events occur when the * controller's "validate"" and "reset" methods are called. * @param callback The callback to be invoked when the controller validates or resets. */ public subscribe(callback: (event: ValidateEvent) => void) { this.eventCallbacks.push(callback); return { dispose: () => { const index = this.eventCallbacks.indexOf(callback); if (index === -1) { return; } this.eventCallbacks.splice(index, 1); } }; } /** * Adds an object to the set of objects that should be validated when validate is called. * @param object The object. * @param rules Optional. The rules. If rules aren't supplied the Validator implementation will lookup the rules. */ public addObject(object: any, rules?: any): void { this.objects.set(object, rules); } /** * Removes an object from the set of objects that should be validated when validate is called. * @param object The object. */ public removeObject(object: any): void { this.objects.delete(object); this.processResultDelta( 'reset', this.results.filter(result => result.object === object), []); } /** * Adds and renders an error. */ public addError<TObject>( message: string, object: TObject, propertyName: string | PropertyAccessor<TObject, string> | null = null ): ValidateResult { let resolvedPropertyName: string | number | null; if (propertyName === null) { resolvedPropertyName = propertyName; } else { resolvedPropertyName = this.propertyParser.parse(propertyName); } const result = new ValidateResult({ __manuallyAdded__: true }, object, resolvedPropertyName, false, message); this.processResultDelta('validate', [], [result]); return result; } /** * Removes and unrenders an error. */ public removeError(result: ValidateResult) { if (this.results.indexOf(result) !== -1) { this.processResultDelta('reset', [result], []); } } /** * Adds a renderer. * @param renderer The renderer. */ public addRenderer(renderer: ValidationRenderer) { this.renderers.push(renderer); renderer.render({ kind: 'validate', render: this.results.map(result => ({ result, elements: this.elements.get(result) as Element[] })), unrender: [] }); } /** * Removes a renderer. * @param renderer The renderer. */ public removeRenderer(renderer: ValidationRenderer) { this.renderers.splice(this.renderers.indexOf(renderer), 1); renderer.render({ kind: 'reset', render: [], unrender: this.results.map(result => ({ result, elements: this.elements.get(result) as Element[] })) }); } /** * Registers a binding with the controller. * @param binding The binding instance. * @param target The DOM element. * @param rules (optional) rules associated with the binding. Validator implementation specific. */ public registerBinding(binding: Binding, target: Element, rules?: any) { this.bindings.set(binding, { target, rules, propertyInfo: null }); } /** * Unregisters a binding with the controller. * @param binding The binding instance. */ public unregisterBinding(binding: Binding) { this.resetBinding(binding); this.bindings.delete(binding); } /** * Interprets the instruction and returns a predicate that will identify * relevant results in the list of rendered validation results. */ private getInstructionPredicate(instruction?: ValidateInstruction): (result: ValidateResult) => boolean { if (instruction) { const { object, propertyName, rules } = instruction; let predicate: (result: ValidateResult) => boolean; if (instruction.propertyName) { predicate = x => x.object === object && x.propertyName === propertyName; } else { predicate = x => x.object === object; } if (rules) { return x => predicate(x) && this.validator.ruleExists(rules, x.rule); } return predicate; } else { return () => true; } } /** * Validates and renders results. * @param instruction Optional. Instructions on what to validate. If undefined, all * objects and bindings will be validated. */ public validate(instruction?: ValidateInstruction): Promise<ControllerValidateResult> { // Get a function that will process the validation instruction. let execute: () => Promise<ValidateResult[]>; if (instruction) { // tslint:disable-next-line:prefer-const let { object, propertyName, rules } = instruction; // if rules were not specified, check the object map. rules = rules || this.objects.get(object); // property specified? if (instruction.propertyName === undefined) { // validate the specified object. execute = () => this.validator.validateObject(object, rules); } else { // validate the specified property. execute = () => this.validator.validateProperty(object, propertyName, rules); } } else { // validate all objects and bindings. execute = () => { const promises: Promise<ValidateResult[]>[] = []; for (const [object, rules] of Array.from(this.objects)) { promises.push(this.validator.validateObject(object, rules)); } for (const [binding, { rules }] of Array.from(this.bindings)) { const propertyInfo = getPropertyInfo(binding.sourceExpression as Expression, binding.source); if (!propertyInfo || this.objects.has(propertyInfo.object)) { continue; } promises.push(this.validator.validateProperty(propertyInfo.object, propertyInfo.propertyName, rules)); } return Promise.all(promises).then(resultSets => resultSets.reduce((a, b) => a.concat(b), [])); }; } // Wait for any existing validation to finish, execute the instruction, render the results. this.validating = true; const returnPromise: Promise<ControllerValidateResult> = this.finishValidating .then(execute) .then((newResults: ValidateResult[]) => { const predicate = this.getInstructionPredicate(instruction); const oldResults = this.results.filter(predicate); this.processResultDelta('validate', oldResults, newResults); if (returnPromise === this.finishValidating) { this.validating = false; } const result: ControllerValidateResult = { instruction, valid: newResults.find(x => !x.valid) === undefined, results: newResults }; this.invokeCallbacks(instruction, result); return result; }) .catch(exception => { // recover, to enable subsequent calls to validate() this.validating = false; this.finishValidating = Promise.resolve(); return Promise.reject(exception); }); this.finishValidating = returnPromise; return returnPromise; } /** * Resets any rendered validation results (unrenders). * @param instruction Optional. Instructions on what to reset. If unspecified all rendered results * will be unrendered. */ public reset(instruction?: ValidateInstruction) { const predicate = this.getInstructionPredicate(instruction); const oldResults = this.results.filter(predicate); this.processResultDelta('reset', oldResults, []); this.invokeCallbacks(instruction, null); } /** * Gets the elements associated with an object and propertyName (if any). */ private getAssociatedElements({ object, propertyName }: ValidateResult): Element[] { const elements: Element[] = []; for (const [binding, { target }] of Array.from(this.bindings)) { const propertyInfo = getPropertyInfo(binding.sourceExpression as Expression, binding.source); if (propertyInfo && propertyInfo.object === object && propertyInfo.propertyName === propertyName) { elements.push(target); } } return elements; } private processResultDelta( kind: 'validate' | 'reset', oldResults: ValidateResult[], newResults: ValidateResult[] ) { // prepare the instruction. const instruction: RenderInstruction = { kind, render: [], unrender: [] }; // create a shallow copy of newResults so we can mutate it without causing side-effects. newResults = newResults.slice(0); // create unrender instructions from the old results. for (const oldResult of oldResults) { // get the elements associated with the old result. const elements = this.elements.get(oldResult) as Element[]; // remove the old result from the element map. this.elements.delete(oldResult); // create the unrender instruction. instruction.unrender.push({ result: oldResult, elements }); // determine if there's a corresponding new result for the old result we are unrendering. const newResultIndex = newResults.findIndex( x => x.rule === oldResult.rule && x.object === oldResult.object && x.propertyName === oldResult.propertyName); if (newResultIndex === -1) { // no corresponding new result... simple remove. this.results.splice(this.results.indexOf(oldResult), 1); if (!oldResult.valid) { this.errors.splice(this.errors.indexOf(oldResult), 1); } } else { // there is a corresponding new result... const newResult = newResults.splice(newResultIndex, 1)[0]; // get the elements that are associated with the new result. const elements = this.getAssociatedElements(newResult); this.elements.set(newResult, elements); // create a render instruction for the new result. instruction.render.push({ result: newResult, elements }); // do an in-place replacement of the old result with the new result. // this ensures any repeats bound to this.results will not thrash. this.results.splice(this.results.indexOf(oldResult), 1, newResult); if (!oldResult.valid && newResult.valid) { this.errors.splice(this.errors.indexOf(oldResult), 1); } else if (!oldResult.valid && !newResult.valid) { this.errors.splice(this.errors.indexOf(oldResult), 1, newResult); } else if (!newResult.valid) { this.errors.push(newResult); } } } // create render instructions from the remaining new results. for (const result of newResults) { const elements = this.getAssociatedElements(result); instruction.render.push({ result, elements }); this.elements.set(result, elements); this.results.push(result); if (!result.valid) { this.errors.push(result); } } // render. for (const renderer of this.renderers) { renderer.render(instruction); } } /** * Validates the property associated with a binding. */ public validateBinding(binding: Binding) { if (!binding.isBound) { return; } const propertyInfo = getPropertyInfo(binding.sourceExpression as Expression, binding.source); let rules; const registeredBinding = this.bindings.get(binding); if (registeredBinding) { rules = registeredBinding.rules; registeredBinding.propertyInfo = propertyInfo; } if (!propertyInfo) { return; } const { object, propertyName } = propertyInfo; this.validate({ object, propertyName, rules }); } /** * Resets the results for a property associated with a binding. */ public resetBinding(binding: Binding) { const registeredBinding = this.bindings.get(binding); let propertyInfo = getPropertyInfo(binding.sourceExpression as Expression, binding.source); if (!propertyInfo && registeredBinding) { propertyInfo = registeredBinding.propertyInfo; } if (registeredBinding) { registeredBinding.propertyInfo = null; } if (!propertyInfo) { return; } const { object, propertyName } = propertyInfo; this.reset({ object, propertyName }); } /** * Changes the controller's validateTrigger. * @param newTrigger The new validateTrigger */ public changeTrigger(newTrigger: validateTrigger) { this.validateTrigger = newTrigger; const bindings = Array.from(this.bindings.keys()); for (const binding of bindings) { const source = binding.source; binding.unbind(); binding.bind(source); } } /** * Revalidates the controller's current set of errors. */ public revalidateErrors() { for (const { object, propertyName, rule } of this.errors) { if (rule.__manuallyAdded__) { continue; } const rules = [[rule]]; this.validate({ object, propertyName, rules }); } } private invokeCallbacks(instruction: ValidateInstruction | undefined, result: ControllerValidateResult | null) { if (this.eventCallbacks.length === 0) { return; } const event = new ValidateEvent( result ? 'validate' : 'reset', this.errors, this.results, instruction || null, result); for (let i = 0; i < this.eventCallbacks.length; i++) { this.eventCallbacks[i](event); } } } /** * Information related to an "& validate" decorated binding. */ interface BindingInfo { /** * The DOM element associated with the binding. */ target: Element; /** * The rules associated with the binding via the validate binding behavior's rules parameter. */ rules?: any; /** * The object and property associated with the binding. */ propertyInfo: { object: any; propertyName: string; } | null; }
the_stack
import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc incremental compilation (semantic changes)', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.enableMultipleCompilations(); env.tsconfig(); }); function expectToHaveWritten(files: string[]): void { const set = env.getFilesWrittenSinceLastFlush(); const expectedSet = new Set<string>(); for (const file of files) { expectedSet.add(file); expectedSet.add(file.replace(/\.js$/, '.d.ts')); } expect(set).toEqual(expectedSet); // Reset for the next compilation. env.flushWrittenFileTracking(); } describe('changes to public api', () => { it('should not recompile dependent components when public api is unchanged', () => { // Testing setup: ADep is a component with an input and an output, and is consumed by two // other components - ACmp within its same NgModule, and BCmp which depends on ADep via an // NgModule import. // // ADep is changed during the test without affecting its public API, and the test asserts // that both ACmp and BCmp which consume ADep are not re-emitted. env.write('a/dep.ts', ` import {Component, Input, Output, EventEmitter} from '@angular/core'; @Component({ selector: 'a-dep', template: 'a-dep', }) export class ADep { @Input() input!: string; @Output() output = new EventEmitter<string>(); } `); env.write('a/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'a-cmp', template: '<a-dep></a-dep>', }) export class ACmp {} `); env.write('a/mod.ts', ` import {NgModule} from '@angular/core'; import {ADep} from './dep'; import {ACmp} from './cmp'; @NgModule({ declarations: [ADep, ACmp], exports: [ADep], }) export class AMod {} `); env.write('b/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'b-cmp', template: '<a-dep></a-dep>', }) export class BCmp {} `); env.write('b/mod.ts', ` import {NgModule} from '@angular/core'; import {BCmp} from './cmp'; import {AMod} from '../a/mod'; @NgModule({ declarations: [BCmp], imports: [AMod], }) export class BMod {} `); env.driveMain(); env.flushWrittenFileTracking(); // Change ADep without affecting its public API. env.write('a/dep.ts', ` import {Component, Input, Output, EventEmitter} from '@angular/core'; @Component({ selector: 'a-dep', template: 'a-dep', }) export class ADep { @Input() input!: string; @Output() output = new EventEmitter<number>(); // changed from string to number } `); env.driveMain(); expectToHaveWritten([ // ADep is written because it was updated. '/a/dep.js', // AMod is written because it has a direct dependency on ADep. '/a/mod.js', // Nothing else is written because the public API of AppCmpB was not affected ]); }); it('should not recompile components that do not use a changed directive', () => { // Testing setup: ADep is a directive with an input and output, which is visible to two // components which do not use ADep in their templates - ACmp within the same NgModule, and // BCmp which has visibility of ADep via an NgModule import. // // During the test, ADep's public API is changed, and the test verifies that neither ACmp // nor BCmp are re-emitted. env.write('a/dep.ts', ` import {Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[a-dep]', }) export class ADep { @Input() input!: string; @Output() output = new EventEmitter<string>(); } `); env.write('a/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'a-cmp', template: 'Does not use a-dep.', }) export class ACmp {} `); env.write('a/mod.ts', ` import {NgModule} from '@angular/core'; import {ADep} from './dep'; import {ACmp} from './cmp'; @NgModule({ declarations: [ADep, ACmp], exports: [ADep], }) export class AMod {} `); env.write('b/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'b-cmp', template: 'Does not use a-dep.', }) export class BCmp {} `); env.write('b/mod.ts', ` import {NgModule} from '@angular/core'; import {BCmp} from './cmp'; import {AMod} from '../a/mod'; @NgModule({ declarations: [BCmp], imports: [AMod], }) export class BMod {} `); env.driveMain(); env.flushWrittenFileTracking(); // Update ADep and change its public API. env.write('a/dep.ts', ` import {Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[a-dep]', template: 'a-dep', }) export class ADep { @Input() input!: string; @Output('output-renamed') // public binding name of the @Output is changed. output = new EventEmitter<string>(); } `); env.driveMain(); expectToHaveWritten([ // ADep is written because it was updated. '/a/dep.js', // AMod is written because it has a direct dependency on ADep. '/a/mod.js', // Nothing else is written because neither ACmp nor BCmp depend on ADep. ]); }); it('should recompile components for which a directive usage is introduced', () => { // Testing setup: Cmp is a component with a template that would match a directive with the // selector '[dep]' if one existed. Dep is a directive with a different selector initially. // // During the test, Dep's selector is updated to '[dep]', causing it to begin matching the // template of Cmp. The test verifies that Cmp is re-emitted after this change. env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[does-not-match]', }) export class Dep {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', // selector changed to now match inside Cmp's template }) export class Dep {} `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because the directives matched in its template have changed. '/cmp.js', ]); }); it('should recompile components for which a directive usage is removed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, Dep's selector is changed, causing it to no longer match the template of // Cmp. The test verifies that Cmp is re-emitted after this change. env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[does-not-match]', // selector changed to no longer match Cmp's template }) export class Dep {} `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because the directives matched in its template have changed. '/cmp.js', ]); }); it('should recompile dependent components when an input is added', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an input is added to Dep, and the test verifies that Cmp is re-emitted. env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { @Input() input!: string; // adding this changes Dep's public API } `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an input is renamed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an input of Dep is renamed, and the test verifies that Cmp is // re-emitted. env.write('dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { @Input() input!: string; } `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { @Input('renamed') input!: string; // renaming this changes Dep's public API } `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an input is removed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an input of Dep is removed, and the test verifies that Cmp is // re-emitted. env.write('dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { @Input() input!: string; } `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { // Dep's input has been removed, which changes its public API } `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an output is added', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an output of Dep is added, and the test verifies that Cmp is re-emitted. env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { @Output() output = new EventEmitter<string>(); // added, which changes Dep's public API } `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an output is renamed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an output of Dep is renamed, and the test verifies that Cmp is // re-emitted. env.write('dep.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { @Output() output = new EventEmitter<string>(); } `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { @Output('renamed') output = new EventEmitter<string>(); // public API changed } `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an output is removed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an output of Dep is removed, and the test verifies that Cmp is // re-emitted. env.write('dep.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { @Output() output = new EventEmitter<string>(); } `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep { // Dep's output has been removed, which changes its public API } `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when exportAs clause changes', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]' and an exportAs clause. // // During the test, the exportAs clause of Dep is changed, and the test verifies that Cmp is // re-emitted. env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', exportAs: 'depExport1', }) export class Dep {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', exportAs: 'depExport2', // changing this changes Dep's public API }) export class Dep {} `); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile components when a pipe is newly matched because it was renamed', () => { // Testing setup: Cmp uses two pipes (PipeA and PipeB) in its template. // // During the test, the selectors of these pipes are swapped. This ensures that Cmp's // template is still valid, since both pipe names continue to be valid within it. However, // as the identity of each pipe is now different, the effective public API of those pipe // usages has changed. The test then verifies that Cmp is re-emitted. env.write('pipes.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'pipeA', }) export class PipeA { transform(value: any): any { return value; } } @Pipe({ name: 'pipeB', }) export class PipeB { transform(value: any): any { return value; } } `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '{{ value | pipeA }} {{ value | pipeB }}', }) export class Cmp { value!: string; } `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {PipeA, PipeB} from './pipes'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp, PipeA, PipeB], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('pipes.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'pipeB', // swapped with PipeB's selector }) export class PipeA { transform(value: any): any { return value; } } @Pipe({ name: 'pipeA', // swapped with PipeA's selector }) export class PipeB { transform(value: any): any { return value; } } `); env.driveMain(); expectToHaveWritten([ // PipeA and PipeB have directly changed. '/pipes.js', // Mod depends directly on PipeA and PipeB. '/mod.js', // Cmp depends on the public APIs of PipeA and PipeB, which have changed (as they've // swapped). '/cmp.js', ]); }); }); describe('external declarations', () => { it('should not recompile components that use external declarations that are not changed', () => { // Testing setup: Two components (MyCmpA and MyCmpB) both depend on an external directive // which matches their templates, via an NgModule import. // // During the test, MyCmpA is invalidated, and the test verifies that only MyCmpA and not // MyCmpB is re-emitted. env.write('node_modules/external/index.d.ts', ` import * as ng from '@angular/core'; export declare class ExternalDir { static ɵdir: ng.ɵɵDirectiveDefWithMeta<ExternalDir, "[external]", never, {}, {}, never>; } export declare class ExternalMod { static ɵmod: ng.ɵɵNgModuleDefWithMeta<ExternalMod, [typeof ExternalDir], never, [typeof ExternalDir]>; } `); env.write('cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', }) export class MyCmpA {} `); env.write('cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', }) export class MyCmpB {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {ExternalMod} from 'external'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], imports: [ExternalMod], }) export class MyMod {} `); env.driveMain(); env.flushWrittenFileTracking(); // Invalidate MyCmpA, causing it to be re-emitted. env.invalidateCachedFile('cmp-a.ts'); env.driveMain(); expectToHaveWritten([ // MyMod is written because it has a direct reference to MyCmpA, which was invalidated. '/mod.js', // MyCmpA is written because it was invalidated. '/cmp-a.js', // MyCmpB should not be written because it is unaffected. ]); }); it('should recompile components once an external declaration is changed', () => { // Testing setup: Two components (MyCmpA and MyCmpB) both depend on an external directive // which matches their templates, via an NgModule import. // // During the test, the external directive is invalidated, and the test verifies that both // components are re-emitted as a result. env.write('node_modules/external/index.d.ts', ` import * as ng from '@angular/core'; export declare class ExternalDir { static ɵdir: ng.ɵɵDirectiveDefWithMeta<ExternalDir, "[external]", never, {}, {}, never>; } export declare class ExternalMod { static ɵmod: ng.ɵɵNgModuleDefWithMeta<ExternalMod, [typeof ExternalDir], never, [typeof ExternalDir]>; } `); env.write('cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', }) export class MyCmpA {} `); env.write('cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', }) export class MyCmpB {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {ExternalMod} from 'external'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], imports: [ExternalMod], }) export class MyMod {} `); env.driveMain(); env.flushWrittenFileTracking(); // Invalidate the external file. Only the referential identity of external symbols matters // for emit reuse, so invalidating this should cause all dependent components to be // re-emitted. env.invalidateCachedFile('node_modules/external/index.d.ts'); env.driveMain(); expectToHaveWritten([ // MyMod is written because it has a direct reference to ExternalMod, which was // invalidated. '/mod.js', // MyCmpA is written because it uses ExternalDir, which has not changed public API but has // changed identity. '/cmp-a.js', // MyCmpB is written because it uses ExternalDir, which has not changed public API but has // changed identity. '/cmp-b.js', ]); }); }); describe('symbol identity', () => { it('should recompile components when their declaration name changes', () => { // Testing setup: component Cmp depends on component Dep, which is directly exported. // // During the test, Dep's name is changed while keeping its public API the same. The test // verifies that Cmp is re-emitted. env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<dep></dep>', }) export class Cmp {} `); env.write('dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', }) export class Dep {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `); env.driveMain(); env.write('dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', }) export class ChangedDep {} // Dep renamed to ChangedDep. `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {ChangedDep} from './dep'; @NgModule({ declarations: [Cmp, ChangedDep] }) export class Mod {} `); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep and Mod were directly updated. '/dep.js', '/mod.js', // Cmp required a re-emit because the name of Dep changed. '/cmp.js', ]); }); it('should not recompile components that use a local directive', () => { // Testing setup: a single source file 'cmp.ts' declares components `Cmp` and `Dir`, where // `Cmp` uses `Dir` in its template. This test verifies that the local reference of `Cmp` // that is emitted into `Dir` does not inadvertently cause `cmp.ts` to be emitted even when // nothing changed. env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', }) export class Dep {} @Component({ selector: 'cmp', template: '<dep></dep>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp, Dep} from './cmp'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `); env.driveMain(); env.invalidateCachedFile('mod.ts'); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Only `mod.js` should be written because it was invalidated. '/mod.js', ]); }); it('should recompile components when the name by which they are exported changes', () => { // Testing setup: component Cmp depends on component Dep, which is directly exported. // // During the test, Dep's exported name is changed while keeping its declaration name the // same. The test verifies that Cmp is re-emitted. env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<dep></dep>', }) export class Cmp {} `); env.write('dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', }) export class Dep {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `); env.driveMain(); env.write('dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', }) class Dep {} export {Dep as ChangedDep}; // the export name of Dep is changed. `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {ChangedDep} from './dep'; @NgModule({ declarations: [Cmp, ChangedDep] }) export class Mod {} `); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep and Mod were directly updated. '/dep.js', '/mod.js', // Cmp required a re-emit because the exported name of Dep changed. '/cmp.js', ]); }); it('should recompile components when a re-export is renamed', () => { // Testing setup: CmpUser uses CmpDep in its template. CmpDep is both directly and // indirectly exported, and the compiler is guided into using the indirect export. // // During the test, the indirect export name is changed, and the test verifies that CmpUser // is re-emitted. env.write('cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<cmp-dep></cmp-dep>', }) export class CmpUser {} `); env.write('cmp-dep.ts', ` import {Component} from '@angular/core'; export {CmpDep as CmpDepExport}; @Component({ selector: 'cmp-dep', template: 'Dep', }) class CmpDep {} `); env.write('module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {CmpDepExport} from './cmp-dep'; @NgModule({ declarations: [CmpUser, CmpDepExport] }) export class Module {} `); env.driveMain(); // Verify that the reference emitter used the export of `CmpDep` that appeared first in // the source, i.e. `CmpDepExport`. const userCmpJs = env.getContents('cmp-user.js'); expect(userCmpJs).toContain('CmpDepExport'); env.write('cmp-dep.ts', ` import {Component} from '@angular/core'; export {CmpDep as CmpDepExport2}; @Component({ selector: 'cmp-dep', template: 'Dep', }) class CmpDep {} `); env.write('module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {CmpDepExport2} from './cmp-dep'; @NgModule({ declarations: [CmpUser, CmpDepExport2] }) export class Module {} `); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // CmpDep and its module were directly updated. '/cmp-dep.js', '/module.js', // CmpUser required a re-emit because it was previous emitted as `CmpDepExport`, but // that export has since been renamed. '/cmp-user.js', ]); // Verify that `CmpUser` now correctly imports `CmpDep` using its renamed // re-export `CmpDepExport2`. const userCmp2Js = env.getContents('cmp-user.js'); expect(userCmp2Js).toContain('CmpDepExport2'); }); it('should not recompile components when a directive is changed into a component', () => { env.write('cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<div dep></div>', }) export class CmpUser {} `); env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep {} `); env.write('module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {Dep} from './dep'; @NgModule({ declarations: [CmpUser, Dep] }) export class Module {} `); env.driveMain(); env.write('dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: '[dep]', template: 'Dep', }) export class Dep {} `); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep was directly changed. '/dep.js', // Module required a re-emit because its direct dependency (Dep) was changed. '/module.js', // CmpUser did not require a re-emit because its semantic dependencies were not affected. // Dep is still matched and still has the same public API. ]); }); it('should recompile components when a directive and pipe are swapped', () => { // CmpUser uses a directive DepA and a pipe DepB, with the same selector/name 'dep'. // // During the test, the decorators of DepA and DepB are swapped, effectively changing the // SemanticSymbol types for them into different species while ensuring that CmpUser's // template is still valid. The test then verifies that CmpUser is re-emitted. env.write('cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<dep>{{1 | dep}}</dep>', }) export class CmpUser {} `); env.write('dep.ts', ` import {Directive, Pipe} from '@angular/core'; @Directive({ selector: 'dep', }) export class DepA {} @Pipe({ name: 'dep', }) export class DepB { transform() {} } `); env.write('module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {DepA, DepB} from './dep'; @NgModule({ declarations: [CmpUser, DepA, DepB], }) export class Module {} `); env.driveMain(); // The annotations on DepA and DepB are swapped. This ensures that when we're comparing the // public API of these symbols to the prior program, the prior symbols are of a different // type (pipe vs directive) than the new symbols, which should lead to a re-emit. env.write('dep.ts', ` import {Directive, Pipe} from '@angular/core'; @Pipe({ name: 'dep', }) export class DepA { transform() {} } @Directive({ selector: 'dep', }) export class DepB {} `); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep was directly changed. '/dep.js', // Module required a re-emit because its direct dependency (Dep) was changed. '/module.js', // CmpUser required a re-emit because the shape of its matched symbols changed. '/cmp-user.js', ]); }); it('should not recompile components when a component is changed into a directive', () => { // Testing setup: CmpUser depends on a component Dep with an attribute selector. // // During the test, Dep is changed into a directive, and the test verifies that CmpUser is // not re-emitted (as the public API of a directive and a component are the same). env.write('cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<div dep></div>', }) export class CmpUser {} `); env.write('dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: '[dep]', template: 'Dep', }) export class Dep {} `); env.write('module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {Dep} from './dep'; @NgModule({ declarations: [CmpUser, Dep] }) export class Module {} `); env.driveMain(); env.write('dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', }) export class Dep {} `); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep was directly changed. '/dep.js', // Module required a re-emit because its direct dependency (Dep) was changed. '/module.js', // CmpUser did not require a re-emit because its semantic dependencies were not affected. // Dep is still matched and still has the same public API. ]); }); }); describe('remote scoping', () => { it('should not recompile an NgModule nor component when remote scoping is unaffected', () => { // Testing setup: MyCmpA and MyCmpB are two components with an indirect import cycle. That // is, each component consumes the other in its template. This forces the compiler to use // remote scoping to set the directiveDefs of at least one of the components in their // NgModule. // // During the test, an unrelated change is made to the template of MyCmpB, and the test // verifies that the NgModule for the components is not re-emitted. env.write('cmp-a-template.html', `<cmp-b><cmp-b>`); env.write('cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', }) export class MyCmpA {} `); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write('cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', }) export class MyCmpB {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], }) export class MyMod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('cmp-b-template.html', `<cmp-a>Update</cmp-a>`); env.driveMain(); expectToHaveWritten([ // MyCmpB is written because its template was updated. '/cmp-b.js', // MyCmpA should not be written because MyCmpB's public API didn't change. // MyMod should not be written because remote scoping didn't change. ]); }); it('should recompile an NgModule and component when an import cycle is introduced', () => { // Testing setup: MyCmpA and MyCmpB are two components where MyCmpB consumes MyCmpA in its // template. // // During the test, MyCmpA's template is updated to consume MyCmpB, creating an effective // import cycle and forcing the compiler to use remote scoping for at least one of the // components. The test verifies that the components' NgModule is emitted as a result. env.write('cmp-a-template.html', ``); env.write('cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', }) export class MyCmpA {} `); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write('cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', }) export class MyCmpB {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], }) export class MyMod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('cmp-a-template.html', `<cmp-b><cmp-b>`); env.driveMain(); expectToHaveWritten([ // MyMod is written because its remote scopes have changed. '/mod.js', // MyCmpA is written because its template was updated. '/cmp-a.js', // MyCmpB is written because it now requires remote scoping, where previously it did not. '/cmp-b.js', ]); // Validate the correctness of the assumptions made above: // * CmpA should not be using remote scoping. // * CmpB should be using remote scoping. const moduleJs = env.getContents('mod.js'); expect(moduleJs).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJs).toContain('setComponentScope(MyCmpB,'); }); it('should recompile an NgModule and component when an import cycle is removed', () => { // Testing setup: MyCmpA and MyCmpB are two components that each consume the other in their // template, forcing the compiler to utilize remote scoping for at least one of them. // // During the test, MyCmpA's template is updated to no longer consume MyCmpB, breaking the // effective import cycle and causing remote scoping to no longer be required. The test // verifies that the components' NgModule is emitted as a result. env.write('cmp-a-template.html', `<cmp-b><cmp-b>`); env.write('cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', }) export class MyCmpA {} `); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write('cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', }) export class MyCmpB {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], }) export class MyMod {} `); env.driveMain(); // Validate the correctness of the assumption that CmpB will be the remotely scoped // component due to the above cycle: const moduleJs = env.getContents('mod.js'); expect(moduleJs).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJs).toContain('setComponentScope(MyCmpB,'); env.flushWrittenFileTracking(); env.write('cmp-a-template.html', ``); env.driveMain(); expectToHaveWritten([ // MyMod is written because its remote scopes have changed. '/mod.js', // MyCmpA is written because its template was updated. '/cmp-a.js', // MyCmpB is written because it no longer needs remote scoping. '/cmp-b.js', ]); }); it('should recompile an NgModule when a remotely scoped component\'s scope is changed', () => { // Testing setup: MyCmpA and MyCmpB are two components that each consume the other in // their template, forcing the compiler to utilize remote scoping for MyCmpB (which is // verified). Dir is a directive which is initially unused by either component. // // During the test, MyCmpB is updated to additionally consume Dir in its template. This // changes the remote scope of MyCmpB, requiring a re-emit of its NgModule which the test // verifies. env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir {} `); env.write('cmp-a-template.html', `<cmp-b><cmp-b>`); env.write('cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', }) export class MyCmpA {} `); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write('cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', }) export class MyCmpB {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; import {Dir} from './dir'; @NgModule({ declarations: [MyCmpA, MyCmpB, Dir], }) export class MyMod {} `); env.driveMain(); env.flushWrittenFileTracking(); // Validate the correctness of the assumption that MyCmpB will be remotely scoped: const moduleJs = env.getContents('mod.js'); expect(moduleJs).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJs).toContain('setComponentScope(MyCmpB,'); env.write('cmp-b-template.html', `<cmp-a dir>Update</cmp-a>`); env.driveMain(); expectToHaveWritten([ // MyCmpB is written because its template was updated. '/cmp-b.js', // MyMod should be written because one of its remotely scoped components has a changed // scope. '/mod.js' // MyCmpA should not be written because none of its dependencies have changed in their // public API. ]); }); it('should recompile an NgModule when its set of remotely scoped components changes', () => { // Testing setup: three components (MyCmpA, MyCmpB, and MyCmpC) are declared. MyCmpA // consumes the other two in its template, and MyCmpB consumes MyCmpA creating an effective // import cycle that forces the compiler to use remote scoping for MyCmpB (which is // verified). // // During the test, MyCmpC's template is changed to depend on MyCmpA, forcing remote // scoping for it as well. The test verifies that the NgModule is re-emitted as a new // component within it now requires remote scoping. env.write('cmp-a-template.html', `<cmp-b><cmp-b> <cmp-c></cmp-c>`); env.write('cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', }) export class MyCmpA {} `); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write('cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', }) export class MyCmpB {} `); env.write('cmp-c-template.html', ``); env.write('cmp-c.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-c', templateUrl: './cmp-c-template.html', }) export class MyCmpC {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; import {MyCmpC} from './cmp-c'; @NgModule({ declarations: [MyCmpA, MyCmpB, MyCmpC], }) export class MyMod {} `); env.driveMain(); env.flushWrittenFileTracking(); // Validate the correctness of the assumption that MyCmpB will be the only remotely // scoped component due to the MyCmpA <-> MyCmpB cycle: const moduleJsBefore = env.getContents('mod.js'); expect(moduleJsBefore).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJsBefore).toContain('setComponentScope(MyCmpB,'); expect(moduleJsBefore).not.toContain('setComponentScope(MyCmpC,'); env.write('cmp-c-template.html', `<cmp-a>Update</cmp-a>`); env.driveMain(); // Validate the correctness of the assumption that MyCmpB and MyCmpC are now both // remotely scoped due to the MyCmpA <-> MyCmpB and MyCmpA <-> MyCmpC cycles: const moduleJsAfter = env.getContents('mod.js'); expect(moduleJsAfter).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJsAfter).toContain('setComponentScope(MyCmpB,'); expect(moduleJsAfter).toContain('setComponentScope(MyCmpC,'); expectToHaveWritten([ // MyCmpC is written because its template was updated. '/cmp-c.js', // MyMod should be written because MyCmpC became remotely scoped '/mod.js' // MyCmpA and MyCmpB should not be written because none of their dependencies have // changed in their public API. ]); }); }); describe('NgModule declarations', () => { it('should recompile components when a matching directive is added in the direct scope', () => { // Testing setup: A component Cmp has a template which would match a directive Dir, // except Dir is not included in Cmp's NgModule. // // During the test, Dir is added to the NgModule, causing it to begin matching in Cmp's // template. The test verifies that Cmp is re-emitted to account for this. env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/mod.js', // Cmp is written as a matching directive was added to Mod's scope. '/cmp.js', ]); }); it('should recompile components when a matching directive is removed from the direct scope', () => { // Testing setup: Cmp is a component with a template that matches a directive Dir. // // During the test, Dir is removed from Cmp's NgModule, which causes it to stop matching // in Cmp's template. The test verifies that Cmp is re-emitted as a result. env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/mod.js', // Cmp is written as a matching directive was removed from Mod's scope. '/cmp.js', ]); }); it('should recompile components when a matching directive is added in the transitive scope', () => { // Testing setup: A component Cmp has a template which would match a directive Dir, // except Dir is not included in Cmp's NgModule. // // During the test, Dir is added to the NgModule via an import, causing it to begin // matching in Cmp's template. The test verifies that Cmp is re-emitted to account for // this. env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', }) export class Cmp {} `); env.write('deep.ts', ` import {NgModule} from '@angular/core'; @NgModule({ declarations: [], exports: [], }) export class Deep {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Deep} from './deep'; @NgModule({ declarations: [Cmp], imports: [Deep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('deep.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [Dir], }) export class Deep {} `); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/deep.js', // Mod is written as its direct dependency (Deep) was changed. '/mod.js', // Cmp is written as a matching directive was added to Mod's transitive scope. '/cmp.js', ]); }); it('should recompile components when a matching directive is removed from the transitive scope', () => { // Testing setup: Cmp is a component with a template that matches a directive Dir, due to // Dir's NgModule being imported into Cmp's NgModule. // // During the test, this import link is removed, which causes Dir to stop matching in // Cmp's template. The test verifies that Cmp is re-emitted as a result. env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', }) export class Cmp {} `); env.write('deep.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [Dir], }) export class Deep {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Deep} from './deep'; @NgModule({ declarations: [Cmp], imports: [Deep], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('deep.ts', ` import {NgModule} from '@angular/core'; @NgModule({ declarations: [], exports: [], }) export class Deep {} `); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/deep.js', // Mod is written as its direct dependency (Deep) was changed. '/mod.js', // Cmp is written as a matching directive was removed from Mod's transitive scope. '/cmp.js', ]); }); it('should not recompile components when a non-matching directive is added in scope', () => { // Testing setup: A component Cmp has a template which does not match a directive Dir, // and Dir is not included in Cmp's NgModule. // // During the test, Dir is added to the NgModule, making it visible in Cmp's template. // However, Dir still does not match the template. The test verifies that Cmp is not // re-emitted. env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/mod.js', // Cmp is not written as its used directives remains the same, since Dir does not match // within its template. ]); }); }); describe('error recovery', () => { it('should recompile a component when a matching directive is added that first contains an error', () => { // Testing setup: Cmp is a component which would match a directive with the selector // '[dir]'. // // During the test, an initial incremental compilation adds an import to a hypothetical // directive Dir to the NgModule, and adds Dir as a declaration. However, the import // points to a non-existent file. // // During a second incremental compilation, that missing file is added with a declaration // for Dir as a directive with the selector '[dir]', causing it to begin matching in // Cmp's template. The test verifies that Cmp is re-emitted once the program is correct. env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `); expect(env.driveDiagnostics().length).not.toBe(0); env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir {} `); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Mod is written as it was changed in the first incremental compilation, but had // errors and so was not written then. '/mod.js', // Dir is written as it was added in the second incremental compilation. '/dir.js', // Cmp is written as the cumulative effect of the two changes was to add Dir to its // scope and thus match in Cmp's template. '/cmp.js', ]); }); }); it('should correctly emit components when public API changes during a broken program', () => { // Testing setup: a component Cmp exists with a template that matches directive Dir. Cmp also // references an extra file with a constant declaration. // // During the test, a first incremental compilation both adds an input to Dir (changing its // public API) as well as introducing a compilation error by adding invalid syntax to the // extra file. // // A second incremental compilation then fixes the invalid syntax, and the test verifies that // Cmp is re-emitted due to the earlier public API change to Dir. env.write('other.ts', ` export const FOO = true; `); env.write('dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir { @Input() dirIn!: string; } `); env.write('cmp.ts', ` import {Component} from '@angular/core'; import './other'; @Component({ selector: 'test-cmp', template: '<div dir></div>', }) export class Cmp {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `); env.driveMain(); env.flushWrittenFileTracking(); env.write('dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir { @Input() dirIn_changed!: string; } `); env.write('other.ts', ` export const FOO = ; `); expect(env.driveDiagnostics().length).not.toBe(0); env.flushWrittenFileTracking(); env.write('other.ts', ` export const FOO = false; `); env.driveMain(); expectToHaveWritten([ // Mod is written as its direct dependency (Dir) was changed. '/mod.js', // Dir is written as it was directly changed. '/dir.js', // other.js is written as it was directly changed. '/other.js', // Cmp is written as Dir's public API has changed. '/cmp.js', ]); }); }); });
the_stack
import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; import * as cloudwatch from "../cloudwatch"; export namespace metrics { type S3MetricName = "BucketSizeBytes" | "NumberOfObjects" | "AllRequests" | "GetRequests" | "PutRequests" | "DeleteRequests" | "HeadRequests" | "PostRequests" | "SelectRequests" | "SelectScannedBytes" | "SelectReturnedBytes" | "ListRequests" | "BytesDownloaded" | "BytesUploaded" | "4xxErrors" | "5xxErrors" | "FirstByteLatency" | "TotalRequestLatency"; export interface S3MetricChange extends cloudwatch.MetricChange { /** * Optional bucket to filter metrics down to. */ bucket?: aws.s3.Bucket; /** * This dimension filters the data that you have stored in a bucket by the following types * of storage: * * * StandardStorage - The number of bytes used for objects in the STANDARD storage class. * * IntelligentTieringAAStorage - The number of bytes used for objects in the Archive * Access tier of INTELLIGENT_TIERING storage class. * * IntelligentTieringDAAStorage - The number of bytes used for objects in the Deep * Archive Access tier of INTELLIGENT_TIERING storage class. * * IntelligentTieringFAStorage - The number of bytes used for objects in the Frequent * Access tier of INTELLIGENT_TIERING storage class. * * IntelligentTieringIAStorage - The number of bytes used for objects in the Infrequent * Access tier of INTELLIGENT_TIERING storage class. * * StandardIAStorage - The number of bytes used for objects in the Standard-Infrequent * Access (STANDARD_IA) storage class. This extra data is necessary to identify and * restore your object. You are charged GLACIER rates for this additional storage. * * StandardIASizeOverhead - The number of bytes used for objects smaller than 128 KB in * size in the STANDARD_IA storage class. * * IntAAObjectOverhead - For each object in INTELLIGENT_TIERING storage class in the * Archive Access tier, GLACIER adds 32 KB of storage for index and related metadata. * This extra data is necessary to identify and restore your object. You are charged * GLACIER rates for this additional storage. * * IntAAS3ObjectOverhead - For each object in INTELLIGENT_TIERING storage class in the * Archive Access tier, Amazon S3 uses 8 KB of storage for the name of the object and * other metadata. You are charged STANDARD rates for this additional storage. * * IntDAAObjectOverhead - For each object in INTELLIGENT_TIERING storage class in the * Deep Archive Access tier, GLACIER adds 32 KB of storage for index and related * metadata. This extra data is necessary to identify and restore your object. You are * charged S3 Glacier Deep Archive storage rates for this additional storage. * * IntDAAS3ObjectOverhead - For each object in INTELLIGENT_TIERING storage class in the * Deep Archive Access tier, Amazon S3 adds 8 KB of storage for index and related * metadata. This extra data is necessary to identify and restore your object. You are * charged STANDARD rates for this additional storage. * * OneZoneIAStorage - The number of bytes used for objects in the OneZone-Infrequent * Access (ONEZONE_IA) storage class. * * OneZoneIASizeOverhead - The number of bytes used for objects smaller than 128 KB in * size in the ONEZONE_IA storage class. * * ReducedRedundancyStorage - The number of bytes used for objects in the Reduced * Redundancy Storage (RRS) class. * * GlacierStorage - The number of bytes used for objects in the GLACIER storage class. * * GlacierStagingStorage - The number of bytes used for parts of Multipart objects * before the CompleteMultipartUpload request is completed on objects in the GLACIER * storage class. * * GlacierObjectOverhead - For each archived object, GLACIER adds 32 KB of storage for * index and related metadata. This extra data is necessary to identify and restore * your object. You are charged GLACIER rates for this additional storage. * * GlacierS3ObjectOverhead - For each object archived to GLACIER , Amazon S3 uses 8 KB * of storage for the name of the object and other metadata. You are charged STANDARD * rates for this additional storage. * * DeepArchiveStorage - The number of bytes used for objects in the S3 Glacier Deep * Archive storage class. * * DeepArchiveObjectOverhead - For each archived object, S3 Glacier Deep Archive adds * 32 KB of storage for index and related metadata. This extra data is necessary to * identify and restore your object. You are charged S3 Glacier Deep Archive rates * for this additional storage. * * DeepArchiveS3ObjectOverhead - For each object archived to S3 Glacier Deep Archive, * Amazon S3 uses 8 KB of storage for the name of the object and other metadata. You * are charged STANDARD rates for this additional storage. * * DeepArchiveStagingStorage – The number of bytes used for parts of Multipart objects * before the CompleteMultipartUpload request is completed on objects in the S3 * Glacier Deep Archive storage class. * * AllStorageTypes - All available storage types, used by NumberOfObjects metric * * For more information, see * [Metrics-and-dimensions](https://docs.aws.amazon.com/AmazonS3/latest/userguide/metrics-dimensions.html). */ storageType?: "StandardStorage" | "IntelligentTieringAAStorage" | "IntelligentTieringDAAStorage" | "IntelligentTieringFAStorage" | "IntelligentTieringIAStorage" | "StandardIAStorage" | "StandardIASizeOverhead" | "IntAAObjectOverhead" | "IntAAS3ObjectOverhead" | "IntDAAObjectOverhead" | "IntDAAS3ObjectOverhead" | "OneZoneIAStorage" | "OneZoneIASizeOverhead" | "ReducedRedundancyStorage" | "GlacierStorage" | "GlacierStagingStorage" | "GlacierObjectOverhead" | "GlacierS3ObjectOverhead" | "DeepArchiveStorage" | "DeepArchiveObjectOverhead" | "DeepArchiveS3ObjectOverhead" | "DeepArchiveStagingStorage" | "AllStorageTypes"; /** * This dimension filters metrics configurations that you specify for request metrics on a * bucket, for example, a prefix or a tag. You specify a filter id when you create a metrics * configuration. For more information, see * [Metrics-Configurations-for-Buckets](https://docs.aws.amazon.com/AmazonS3/latest/dev/metrics-configurations.html). */ filterId?: string; } /** * Creates an AWS/S3 metric with the requested [metricName]. See * https://docs.aws.amazon.com/AmazonS3/latest/dev/cloudwatch-monitoring.html for list of all * metric-names. * * Note, individual metrics can easily be obtained without supplying the name using the other * [metricXXX] functions. * * Amazon CloudWatch metrics for Amazon S3 can help you understand and improve the performance * of applications that use Amazon S3. There are two ways that you can use CloudWatch with * Amazon S3. * * Daily Storage Metrics for Buckets ‐ You can monitor bucket storage using CloudWatch, which * collects and processes storage data from Amazon S3 into readable, daily metrics. These * storage metrics for Amazon S3 are reported once per day and are provided to all customers at * no additional cost. * * Request metrics ‐ You can choose to monitor Amazon S3 requests to quickly identify and act on * operational issues. The metrics are available at 1 minute intervals after some latency to * process. These CloudWatch metrics are billed at the same rate as the Amazon CloudWatch Custom * Metrics. For information on CloudWatch pricing, see Amazon CloudWatch Pricing. To learn more * about how to opt-in to getting these metrics, see Metrics Configurations for Buckets. * * When enabled, request metrics are reported for all object operations. By default, these * 1-minute metrics are available at the Amazon S3 bucket level. You can also define a filter * for the metrics collected –using a shared prefix or object tag– allowing you to align metrics * filters to specific business applications, workflows, or internal organizations. * * The following dimensions are used to filter Amazon S3 metrics: * * 1. "BucketName": This dimension filters the data you request for the identified bucket only. * 2. "StorageType": This dimension filters the data that you have stored in a bucket by the * following types of storage: * * * StandardStorage - The number of bytes used for objects in the STANDARD storage class. * * IntelligentTieringFAStorage - The number of bytes used for objects in the Frequent Access * tier of INTELLIGENT_TIERING storage class. * * IntelligentTieringIAStorage - The number of bytes used for objects in the Infrequent * Access tier of INTELLIGENT_TIERING storage class. * * StandardIAStorage - The number of bytes used for objects in the Standard - Infrequent * Access (STANDARD_IA) storage class. * * StandardIASizeOverhead - The number of bytes used for objects smaller than 128 KB in size * in the STANDARD_IA storage class. * * OneZoneIAStorage - The number of bytes used for objects in the OneZone - Infrequent * Access (ONEZONE_IA) storage class. * * OneZoneIASizeOverhead - The number of bytes used for objects smaller than 128 KB in size * in the ONEZONE_IA storage class. * * ReducedRedundancyStorage - The number of bytes used for objects in the Reduced Redundancy * Storage (RRS) class. * * GlacierStorage - The number of bytes used for objects in the Glacier (GLACIER) storage * class. * * GlacierStorageOverhead - For each object archived to Glacier, Amazon S3 uses 8 KB of * storage for the name of the object and other metadata. You are charged standard Amazon S3 * rates for this additional storage. For each archived object, Glacier adds 32 KB of * storage for index and related metadata. This extra data is necessary to identify and * restore your object. You are charged Glacier rates for this additional storage. * * 3. "FilterId": This dimension filters metrics configurations that you specify for request * metrics on a bucket, for example, a prefix or a tag. You specify a filter id when you * create a metrics configuration. For more information, see * [Metrics-Configurations-for-Buckets](https://docs.aws.amazon.com/AmazonS3/latest/dev/metrics-configurations.html). */ function metric(metricName: S3MetricName, change: S3MetricChange = {}) { const dimensions: Record<string, pulumi.Input<string>> = {}; if (change.bucket !== undefined) { dimensions.BucketName = change.bucket.bucket; } if (change.storageType !== undefined) { dimensions.StorageType = change.storageType; } if (change.filterId !== undefined) { dimensions.FilterId = change.filterId; } return new cloudwatch.Metric({ namespace: "AWS/S3", name: metricName, ...change, }).withDimensions(dimensions); } /** * The amount of data in bytes stored in a bucket in the STANDARD storage class, * INTELLIGENT_TIERING storage class, Standard - Infrequent Access (STANDARD_IA) storage class, * OneZone - Infrequent Access (ONEZONE_IA), Reduced Redundancy Storage (RRS) class, or Glacier * (GLACIER) storage class. This value is calculated by summing the size of all objects in the * bucket (both current and noncurrent objects), including the size of all parts for all * incomplete multipart uploads to the bucket. * * Units: Bytes * * Valid statistics: Average */ export function bucketSizeBytes(change?: S3MetricChange) { return metric("BucketSizeBytes", { unit: "Bytes", ...change }); } /** * The total number of objects stored in a bucket for all storage classes except for the GLACIER * storage class. This value is calculated by counting all objects in the bucket (both current * and noncurrent objects) and the total number of parts for all incomplete multipart uploads to * the bucket. * * Units: Count * * Valid statistics: Average */ export function numberOfObjects(change?: S3MetricChange) { return metric("NumberOfObjects", { unit: "Count", ...change }); } /** * The total number of HTTP requests made to an Amazon S3 bucket, regardless of type. If you're * using a metrics configuration with a filter, then this metric only returns the HTTP requests * made to the objects in the bucket that meet the filter's requirements. * * Units: Count * * Valid statistics: Sum */ export function allRequests(change?: S3MetricChange) { return metric("AllRequests", { statistic: "Sum", unit: "Count", ...change }); } /** * The number of HTTP GET requests made for objects in an Amazon S3 bucket. This doesn't include * list operations. * * Note: Paginated list-oriented requests, like List Multipart Uploads, List Parts, Get Bucket * Object versions, and others, are not included in this metric. * * Units: Count * * Valid statistics: Sum */ export function getRequests(change?: S3MetricChange) { return metric("GetRequests", { statistic: "Sum", unit: "Count", ...change }); } /** * The number of HTTP PUT requests made for objects in an Amazon S3 bucket. * * Units: Count * * Valid statistics: Sum */ export function putRequests(change?: S3MetricChange) { return metric("PutRequests", { statistic: "Sum", unit: "Count", ...change }); } /** * The number of HTTP DELETE requests made for objects in an Amazon S3 bucket. This also * includes Delete Multiple Objects requests. This metric shows the number of requests, not the * number of objects deleted. * * Units: Count * * Valid statistics: Sum */ export function deleteRequests(change?: S3MetricChange) { return metric("DeleteRequests", { statistic: "Sum", unit: "Count", ...change }); } /** * The number of HTTP HEAD requests made to an Amazon S3 bucket. * * Units: Count * * Valid statistics: Sum */ export function headRequests(change?: S3MetricChange) { return metric("HeadRequests", { statistic: "Sum", unit: "Count", ...change }); } /** * The number of HTTP POST requests made to an Amazon S3 bucket. * * Note: Delete Multiple Objects and SELECT Object Content requests are not included in this * metric. * * Units: Count * * Valid statistics: Sum */ export function postRequests(change?: S3MetricChange) { return metric("PostRequests", { statistic: "Sum", unit: "Count", ...change }); } /** * The number of Amazon S3 SELECT Object Content requests made for objects in an Amazon S3 * bucket. * * Units: Count * * Valid statistics: Sum */ export function selectRequests(change?: S3MetricChange) { return metric("SelectRequests", { statistic: "Sum", unit: "Count", ...change }); } /** * The number of bytes of data scanned with Amazon S3 SELECT Object Content requests in an * Amazon S3 bucket. * * Units: Bytes * * Valid statistics: Average (bytes per request), Sum (bytes per period), Sample Count, Min, Max */ export function selectScannedBytes(change?: S3MetricChange) { return metric("SelectScannedBytes", { unit: "Bytes", ...change }); } /** * The number of bytes of data returned with Amazon S3 SELECT Object Content requests in an * Amazon S3 bucket. * * Units: Bytes * * Valid statistics: Average (bytes per request), Sum (bytes per period), Sample Count, Min, Max */ export function selectReturnedBytes(change?: S3MetricChange) { return metric("SelectReturnedBytes", { unit: "Bytes", ...change }); } /** * The number of HTTP requests that list the contents of a bucket. * * Units: Count * * Valid statistics: Sum */ export function listRequests(change?: S3MetricChange) { return metric("ListRequests", { statistic: "Sum", unit: "Bytes", ...change }); } /** * The number bytes downloaded for requests made to an Amazon S3 bucket, where the response * includes a body. * * Units: Bytes * * Valid statistics: Average (bytes per request), Sum (bytes per period), Sample Count, Min, Max */ export function bytesDownloaded(change?: S3MetricChange) { return metric("BytesDownloaded", { unit: "Bytes", ...change }); } /** * The number bytes uploaded that contain a request body, made to an Amazon S3 bucket. * * Units: Bytes * * Valid statistics: Average (bytes per request), Sum (bytes per period), Sample Count, Min, Max */ export function bytesUploaded(change?: S3MetricChange) { return metric("BytesUploaded", { unit: "Bytes", ...change }); } /** * he number of HTTP 4xx client error status code requests made to an Amazon S3 bucket with a * value of either 0 or 1. The average statistic shows the error rate, and the sum statistic * shows the count of that type of error, during each period. * * Units: Count * * Valid statistics: Average (reports per request), Sum (reports per period), Min, Max, Sample * Count */ export function errors4xx(change?: S3MetricChange) { return metric("4xxErrors", { unit: "Count", ...change }); } /** * The number of HTTP 5xx server error status code requests made to an Amazon S3 bucket with a * value of either 0 or 1. The average statistic shows the error rate, and the sum statistic * shows the count of that type of error, during each period. * * Units: Count * * Valid statistics: Average (reports per request), Sum (reports per period), Min, Max, Sample * Count */ export function errors5xx(change?: S3MetricChange) { return metric("5xxErrors", { unit: "Count", ...change }); } /** * The per-request time from the complete request being received by an Amazon S3 bucket to when * the response starts to be returned. * * Units: Milliseconds * * Valid statistics: Average, Sum, Min, Max, Sample Count */ export function firstByteLatency(change?: S3MetricChange) { return metric("FirstByteLatency", { unit: "Milliseconds", ...change }); } /** * The elapsed per-request time from the first byte received to the last byte sent to an Amazon * S3 bucket. This includes the time taken to receive the request body and send the response * body, which is not included in FirstByteLatency. * * Units: Milliseconds * * Valid statistics: Average, Sum, Min, Max, Sample Count */ export function totalRequestLatency(change?: S3MetricChange) { return metric("TotalRequestLatency", { unit: "Milliseconds", ...change }); } }
the_stack
/*! * Copyright (c) 2020 Ron Buckton (rbuckton@chronicles.org) * * This file is licensed to you under the terms of the MIT License, found in the LICENSE file * in the root of this repository or package. */ import { CharacterCodes, SyntaxKind, stringToToken, isProseFragmentLiteralKind } from "./tokens"; import { Diagnostics, DiagnosticMessages, NullDiagnosticMessages } from "./diagnostics"; import { HtmlTrivia, HtmlCloseTagTrivia, HtmlOpenTagTrivia, SingleLineCommentTrivia, MultiLineCommentTrivia, CommentTrivia } from './nodes'; import { CancelToken } from '@esfx/async-canceltoken'; import { Cancelable } from '@esfx/cancelable'; import { toCancelToken } from './core'; const enum TokenFlags { None = 0, Unterminated = 1 << 0, LineContinuation = 1 << 1, PrecedingLineTerminator = 1 << 2, PrecedingBlankLine = 1 << 3, PrecedingIndent = 1 << 4, PrecedingDedent = 1 << 5, PrecedingNonWhitespaceTrivia = 1 << 6, AnyPrecedingIndent = PrecedingIndent | PrecedingDedent, } /** {@docCategory Parse} */ export class Scanner { public readonly text: string; public readonly filename: string; private readonly cancelToken?: CancelToken; private readonly len: number = 0; private pos: number = 0; private startPos: number = 0; private tokenPos: number = 0; private token: SyntaxKind = SyntaxKind.Unknown; private tokenValue: string = ""; private tokenFlags: TokenFlags = TokenFlags.None; private htmlTrivia: HtmlTrivia[] | undefined; private diagnostics: DiagnosticMessages; private insignificantIndentLength: number = 0; private significantIndentLength: number = 0; private currentIndentLength: number = 0; private proseStartToken: SyntaxKind | undefined; constructor(filename: string, text: string, diagnostics: DiagnosticMessages, cancelable?: Cancelable) { this.filename = filename; this.text = text; this.len = text.length; this.diagnostics = diagnostics; this.cancelToken = toCancelToken(cancelable); } public getPos(): number { return this.pos; } public getLen(): number { return this.len; } public getStartPos(): number { return this.startPos; } public getTokenPos(): number { return this.tokenPos; } public getToken(): SyntaxKind { return this.token; } public getTokenText(): string { return this.text.slice(this.tokenPos, this.pos); } public getTokenValue(): string { return this.tokenValue; } public getTokenIsUnterminated() { return (this.tokenFlags & TokenFlags.Unterminated) === TokenFlags.Unterminated; } public getDiagnostics(): DiagnosticMessages { return this.diagnostics; } public getHtmlTrivia() { return this.htmlTrivia; } public isIndented() { return this.significantIndentLength > 0; } public isLineContinuation() { return (this.tokenFlags & TokenFlags.LineContinuation) === TokenFlags.LineContinuation; } public hasPrecedingIndent() { return (this.tokenFlags & TokenFlags.AnyPrecedingIndent) === TokenFlags.PrecedingIndent; } public hasPrecedingDedent() { return (this.tokenFlags & TokenFlags.AnyPrecedingIndent) === TokenFlags.PrecedingDedent; } public hasPrecedingNewLine() { return this.hasPrecedingLineTerminator() && !this.isLineContinuation(); } public hasPrecedingLineTerminator() { return (this.tokenFlags & TokenFlags.PrecedingLineTerminator) === TokenFlags.PrecedingLineTerminator; } public hasPrecedingBlankLine() { return (this.tokenFlags & TokenFlags.PrecedingBlankLine) === TokenFlags.PrecedingBlankLine; } private hasPrecedingNonWhitspaceTrivia() { return (this.tokenFlags & TokenFlags.PrecedingNonWhitespaceTrivia) === TokenFlags.PrecedingNonWhitespaceTrivia; } private isStartOfFile() { return this.startPos === 0; } private setTokenAsUnterminated() { this.tokenFlags |= TokenFlags.Unterminated; } private setHasPrecedingLineTerminator() { this.tokenFlags |= TokenFlags.PrecedingLineTerminator; this.currentIndentLength = 0; } private setHasPrecedingBlankLine() { this.tokenFlags |= TokenFlags.PrecedingBlankLine; if (this.significantIndentLength > 0) { this.setHasPrecedingDedent(); } this.insignificantIndentLength = 0; this.significantIndentLength = 0; this.currentIndentLength = 0; } private setHasPrecedingIndent() { this.tokenFlags = this.tokenFlags & ~TokenFlags.PrecedingDedent | TokenFlags.PrecedingIndent; } private setHasPrecedingDedent() { this.tokenFlags = this.tokenFlags & ~TokenFlags.PrecedingIndent | TokenFlags.PrecedingDedent; } private setIsLineContinuation() { this.tokenFlags |= TokenFlags.LineContinuation; } private setHasPrecedingNonWhitspaceTrivia() { this.tokenFlags |= TokenFlags.PrecedingNonWhitespaceTrivia; } private resetHasPrecedingNonWhitspaceTrivia() { this.tokenFlags &= ~TokenFlags.PrecedingNonWhitespaceTrivia; } public resetIndent() { this.insignificantIndentLength = this.currentIndentLength; this.significantIndentLength = 0; this.tokenFlags &= ~(TokenFlags.PrecedingIndent | TokenFlags.PrecedingDedent | TokenFlags.LineContinuation); } public speculate<T>(callback: () => T, isLookahead: boolean): T { const savePos = this.pos; const saveStartPos = this.startPos; const saveTokenPos = this.tokenPos; const saveToken = this.token; const saveTokenValue = this.tokenValue; const saveTokenFlags = this.tokenFlags; const saveHtmlTrivia = this.htmlTrivia; const saveDiagnostics = this.diagnostics; const saveInitialIndentLength = this.insignificantIndentLength; const saveSignificantIndentLength = this.significantIndentLength; const saveCurrentIndentLength = this.currentIndentLength; this.diagnostics = NullDiagnosticMessages.instance; const result = callback(); this.diagnostics = saveDiagnostics; if (!result || isLookahead) { this.pos = savePos; this.startPos = saveStartPos; this.tokenPos = saveTokenPos; this.token = saveToken; this.tokenValue = saveTokenValue; this.tokenFlags = saveTokenFlags; this.htmlTrivia = saveHtmlTrivia; this.insignificantIndentLength = saveInitialIndentLength; this.significantIndentLength = saveSignificantIndentLength; this.currentIndentLength = saveCurrentIndentLength; } return result; } public scan(): SyntaxKind { this.cancelToken?.throwIfSignaled(); this.startPos = this.pos; this.tokenValue = ""; this.tokenFlags = 0; this.htmlTrivia = undefined; while (true) { this.tokenPos = this.pos; if (this.pos >= this.len) { if (this.significantIndentLength > 0) { this.setHasPrecedingDedent(); } this.insignificantIndentLength = 0; this.significantIndentLength = 0; this.currentIndentLength = 0; return this.token = SyntaxKind.EndOfFileToken; } if (this.proseStartToken) { return this.token = this.scanProse(); } let ch = this.text.charCodeAt(this.pos++); // scan trivia switch (ch) { case CharacterCodes.LineFeed: case CharacterCodes.CarriageReturn: // newline trivia if (ch === CharacterCodes.CarriageReturn && this.text.charCodeAt(this.pos) === CharacterCodes.LineFeed) { this.pos++; } if (this.hasPrecedingLineTerminator() && !this.hasPrecedingNonWhitspaceTrivia() && !this.hasPrecedingBlankLine()) { this.setHasPrecedingBlankLine(); } this.resetHasPrecedingNonWhitspaceTrivia(); this.setHasPrecedingLineTerminator(); continue; case CharacterCodes.Space: case CharacterCodes.Tab: // significant whitespace trivia if (this.hasPrecedingLineTerminator()) this.currentIndentLength++; continue; case CharacterCodes.VerticalTab: case CharacterCodes.FormFeed: // whitspace trivia continue; case CharacterCodes.LessThan: { // html trivia const ch = this.text.charCodeAt(this.pos); if (isHtmlTagNameStart(ch) || ch === CharacterCodes.Slash || ch === CharacterCodes.GreaterThan) { this.setHasPrecedingNonWhitspaceTrivia(); this.scanHtmlTrivia(); continue; } break; } case CharacterCodes.Slash: // comment trivia switch (this.text.charCodeAt(this.pos)) { case CharacterCodes.Slash: // single-line comment this.pos++; while (this.pos < this.len) { if (isLineTerminator(this.text.charCodeAt(this.pos))) { break; } this.pos++; } this.setHasPrecedingNonWhitspaceTrivia(); continue; case CharacterCodes.Asterisk: // multi-line comment this.pos++; let commentClosed = false; while (this.pos < this.len) { if (this.text.charCodeAt(this.pos) === CharacterCodes.Asterisk && this.text.charCodeAt(this.pos + 1) === CharacterCodes.Slash) { this.pos += 2; commentClosed = true; break; } this.pos++; } if (!commentClosed) { this.getDiagnostics().report(this.pos, Diagnostics._0_expected, "*/"); } this.setHasPrecedingNonWhitspaceTrivia(); continue; } break; } // check for changes in indentation if (this.isStartOfFile() || this.hasPrecedingLineTerminator()) { if (this.isStartOfFile() || this.hasPrecedingBlankLine()) { this.insignificantIndentLength = this.currentIndentLength; this.significantIndentLength = 0; } else if (this.currentIndentLength <= this.insignificantIndentLength) { if (this.significantIndentLength > 0) { this.significantIndentLength = 0; this.setHasPrecedingDedent(); } } else if (this.significantIndentLength === 0) { this.significantIndentLength = this.currentIndentLength; this.setHasPrecedingIndent(); } else if (this.currentIndentLength > this.significantIndentLength) { this.setIsLineContinuation(); } } if (ch === CharacterCodes.Ampersand) { ch = this.scanCharacterEntity(); } // scan token switch (ch) { case CharacterCodes.At: return this.token = SyntaxKind.AtToken; case CharacterCodes.NumberSign: return this.tokenValue = this.scanLine(), this.token = SyntaxKind.LinkReference; case CharacterCodes.DoubleQuote: case CharacterCodes.SingleQuote: return this.tokenValue = this.scanString(ch, this.token = SyntaxKind.StringLiteral), this.token; case CharacterCodes.Backtick: return this.tokenValue = this.scanString(ch, this.token = SyntaxKind.TerminalLiteral), this.token; case CharacterCodes.Bar: return this.tokenValue = this.scanString(ch, this.token = SyntaxKind.Identifier), this.token; case CharacterCodes.LessThan: { const ch = this.text.charCodeAt(this.pos); if (ch === CharacterCodes.Exclamation) { return this.pos++, this.token = SyntaxKind.LessThanExclamationToken; } else if (ch === CharacterCodes.Minus) { return this.pos++, this.token = SyntaxKind.LessThanMinusToken; } else { return this.tokenValue = this.scanString(CharacterCodes.GreaterThan, this.token = SyntaxKind.UnicodeCharacterLiteral), this.token; } } case CharacterCodes.NotEqualTo: return this.token = SyntaxKind.NotEqualToToken; case CharacterCodes.ElementOf: return this.token = SyntaxKind.ElementOfToken; case CharacterCodes.NotAnElementOf: return this.token = SyntaxKind.NotAnElementOfToken; case CharacterCodes.GreaterThan: return this.skipWhiteSpace(), this.proseStartToken = this.token = SyntaxKind.GreaterThanToken; case CharacterCodes.OpenParen: return this.token = SyntaxKind.OpenParenToken; case CharacterCodes.CloseParen: return this.token = SyntaxKind.CloseParenToken; case CharacterCodes.OpenBracket: if (this.text.charCodeAt(this.pos) === CharacterCodes.GreaterThan) { return this.pos++, this.skipWhiteSpace(), this.proseStartToken = this.token = SyntaxKind.OpenBracketGreaterThanToken; } else if (this.text.charCodeAt(this.pos) === CharacterCodes.Ampersand) { const pos = this.pos++; if (this.scanCharacterEntity() === CharacterCodes.GreaterThan) { return this.skipWhiteSpace(), this.proseStartToken = this.token = SyntaxKind.OpenBracketGreaterThanToken; } this.pos = pos; } return this.token = SyntaxKind.OpenBracketToken; case CharacterCodes.CloseBracket: return this.token = SyntaxKind.CloseBracketToken; case CharacterCodes.OpenBrace: return this.token = SyntaxKind.OpenBraceToken; case CharacterCodes.CloseBrace: return this.token = SyntaxKind.CloseBraceToken; case CharacterCodes.Plus: return this.token = SyntaxKind.PlusToken; case CharacterCodes.Tilde: return this.token = SyntaxKind.TildeToken; case CharacterCodes.Comma: return this.token = SyntaxKind.CommaToken; case CharacterCodes.Colon: if (this.text.charCodeAt(this.pos) === CharacterCodes.Colon) { this.pos++; if (this.text.charCodeAt(this.pos) === CharacterCodes.Colon) { return this.pos++, this.token = SyntaxKind.ColonColonColonToken; } return this.token = SyntaxKind.ColonColonToken; } return this.token = SyntaxKind.ColonToken; case CharacterCodes.Question: return this.token = SyntaxKind.QuestionToken; case CharacterCodes.Equals: if (this.text.charCodeAt(this.pos) === CharacterCodes.Equals) { return this.pos++, this.token = SyntaxKind.EqualsEqualsToken; } return this.token = SyntaxKind.EqualsToken; case CharacterCodes.Exclamation: if (this.text.charCodeAt(this.pos) === CharacterCodes.Equals) { return this.pos++, this.token = SyntaxKind.ExclamationEqualsToken; } return this.token = SyntaxKind.Unknown; case CharacterCodes.Number0: case CharacterCodes.Number1: case CharacterCodes.Number2: case CharacterCodes.Number3: case CharacterCodes.Number4: case CharacterCodes.Number5: case CharacterCodes.Number6: case CharacterCodes.Number7: case CharacterCodes.Number8: case CharacterCodes.Number9: return this.tokenValue = this.scanNumber(), this.token = SyntaxKind.NumberLiteral; case CharacterCodes.UpperU: case CharacterCodes.LowerU: if (this.pos + 4 < this.len && this.text.charCodeAt(this.pos) === CharacterCodes.Plus && isHexDigit(this.text.charCodeAt(this.pos + 1)) && isHexDigit(this.text.charCodeAt(this.pos + 2)) && isHexDigit(this.text.charCodeAt(this.pos + 3)) && isHexDigit(this.text.charCodeAt(this.pos + 4))) { return this.tokenValue = this.text.substr(this.tokenPos, 6), this.pos += 5, this.token = SyntaxKind.UnicodeCharacterLiteral; } // fall-through default: if (isIdentifierStart(ch)) { while (isIdentifierPart(this.text.charCodeAt(this.pos))) { this.pos++; } this.tokenValue = this.text.substring(this.tokenPos, this.pos); return this.token = this.getIdentifierToken(); } this.getDiagnostics().report(this.pos, Diagnostics.Invalid_character); return this.token = SyntaxKind.Unknown; } } } public scanRange<T>(pos: number, cb: () => T) { if (pos < 0) throw new RangeError(); pos = Math.min(pos, this.len); return this.speculate(() => { // if pos - 1 is whitespace, walk back the whitespace to rescan indentation if (pos > 0 && pos < this.len) { let start = pos - 1; while (isWhiteSpace(this.text.charCodeAt(start))) { start--; } if (isLineTerminator(this.text.charCodeAt(start))) { pos = start + 1; } } this.pos = pos; this.startPos = pos; this.tokenPos = pos; this.tokenValue = ""; this.tokenFlags = 0; this.htmlTrivia = undefined; this.insignificantIndentLength = 0; this.significantIndentLength = 0; this.currentIndentLength = 0; return cb(); }, /*isLookahead*/ true); } private scanLine(): string { const start = this.pos; while (this.pos < this.len) { const ch = this.text.charCodeAt(this.pos); if (isLineTerminator(ch)) { break; } this.pos++; } return this.text.substring(start, this.pos); } private skipLineTerminator() { const ch = this.text.charCodeAt(this.pos); if (ch === CharacterCodes.CarriageReturn || ch === CharacterCodes.LineFeed) { if (ch === CharacterCodes.CarriageReturn && this.text.charCodeAt(this.pos + 1) === CharacterCodes.LineFeed) { this.pos += 2; } else { this.pos++; } } } private skipWhiteSpace(): void { while (true) { const ch = this.text.charCodeAt(this.pos); switch (ch) { case CharacterCodes.Space: case CharacterCodes.Tab: case CharacterCodes.VerticalTab: case CharacterCodes.FormFeed: this.pos++; continue; default: return; } } } private scanProse() { const previousToken = this.token; const isMultiLine = this.proseStartToken === SyntaxKind.GreaterThanToken; const atStartOfProse = previousToken === this.proseStartToken; const previousTokenWasFragment = isProseFragmentLiteralKind(previousToken); let start = this.pos; let tokenValue: string = ""; while (true) { if (this.pos >= this.len) { tokenValue += this.text.substring(start, this.pos); this.tokenValue = tokenValue; this.proseStartToken = undefined; if (!isMultiLine) { this.setTokenAsUnterminated(); this.getDiagnostics().report(this.pos, Diagnostics._0_expected, "]"); } return atStartOfProse ? SyntaxKind.ProseFull : SyntaxKind.ProseTail; } const ch = this.text.charCodeAt(this.pos); if (previousTokenWasFragment) { if (ch === CharacterCodes.Backtick) { return this.pos++ , this.tokenValue = this.scanString(ch, this.token = SyntaxKind.TerminalLiteral), this.token; } else if (ch === CharacterCodes.Bar) { return this.pos++ , this.tokenValue = this.scanString(ch, this.token = SyntaxKind.Identifier), this.token; } } if (isMultiLine) { if (isLineTerminator(ch)) { tokenValue += this.text.substring(start, this.pos); if (this.nextLineIsProse()) { tokenValue += "\n"; continue; } this.tokenValue = tokenValue; this.proseStartToken = undefined; return atStartOfProse ? SyntaxKind.ProseFull : SyntaxKind.ProseTail; } } else { if (ch === CharacterCodes.CloseBracket) { tokenValue += this.text.substring(start, this.pos); this.tokenValue = tokenValue; this.proseStartToken = undefined; return atStartOfProse ? SyntaxKind.ProseFull : SyntaxKind.ProseTail; } } if (ch === CharacterCodes.Backtick || ch === CharacterCodes.Bar) { tokenValue += this.text.substring(start, this.pos); this.tokenValue = tokenValue; return atStartOfProse ? SyntaxKind.ProseHead : SyntaxKind.ProseMiddle; } if (ch === CharacterCodes.Ampersand) { tokenValue += this.text.substring(start, this.pos); this.pos++; tokenValue += String.fromCharCode(this.scanCharacterEntity()); start = this.pos; continue; } this.pos++; } } private nextLineIsProse() { return this.speculate(() => { this.skipLineTerminator(); this.skipWhiteSpace(); if (this.pos < this.len) { if (this.text.charCodeAt(this.pos) === CharacterCodes.GreaterThan) { this.pos++; this.skipWhiteSpace(); return true; } } return false; }, /*isLookahead*/ false); } private scanHtmlTrivia() { const closingTag = this.text.charCodeAt(this.pos) === CharacterCodes.Slash; const triviaEnd = findHtmlTriviaEnd(this.text, this.pos, this.text.length); const tagNamePos = closingTag ? this.pos + 1 : this.pos; const tagNameEnd = findHtmlTriviaEnd(this.text, tagNamePos, triviaEnd); if (tagNameEnd !== -1) { const tagName = this.text.slice(tagNamePos, tagNameEnd); const tag = closingTag ? new HtmlCloseTagTrivia(tagName) : new HtmlOpenTagTrivia(tagName); tag.pos = this.tokenPos; tag.end = triviaEnd; if (!this.htmlTrivia) this.htmlTrivia = []; this.htmlTrivia.push(tag); } this.pos = triviaEnd; } private scanCharacter(decodeEntity: boolean) { let ch = this.text.charCodeAt(this.pos); this.pos++; if (decodeEntity && ch === CharacterCodes.Ampersand) { ch = this.scanCharacterEntity(); } return ch; } private scanCharacterEntity() { let value = 0; let start: number; let pos: number; if (this.text.charCodeAt(this.pos) === CharacterCodes.Hash) { const hex = this.text.charCodeAt(this.pos + 1) === CharacterCodes.LowerX || this.text.charCodeAt(this.pos + 1) === CharacterCodes.UpperX; start = this.pos + (hex ? 2 : 1); pos = start; while (pos < this.len) { const digit = hex ? this.hexDigitAt(pos) : this.decimalDigitAt(pos); if (digit === -1) break; value = value * (hex ? 16 : 10) + digit; pos++; } } else { start = pos = this.pos; while (pos < this.len) { if (!isAlphaNum(this.text.charCodeAt(pos))) break; pos++; } const entity = this.text.slice(start, pos); if (htmlCharacterEntities.hasOwnProperty(entity)) { value = htmlCharacterEntities[entity]; } } if (pos > start && this.text.charCodeAt(pos) === CharacterCodes.Semicolon) { this.pos = pos + 1; return value; } return CharacterCodes.Ampersand; } private scanString(quote: number, kind: SyntaxKind.StringLiteral | SyntaxKind.TerminalLiteral | SyntaxKind.Identifier | SyntaxKind.UnicodeCharacterLiteral): string { const diagnostic = kind === SyntaxKind.Identifier ? Diagnostics.Unterminated_identifier_literal : Diagnostics.Unterminated_string_literal; const decodeEscapeSequences = kind !== SyntaxKind.TerminalLiteral; let result = ""; let start = this.pos; while (true) { if (this.pos >= this.len) { result += this.text.slice(start, this.pos); this.setTokenAsUnterminated(); this.getDiagnostics().report(this.pos, diagnostic || Diagnostics.Unterminated_string_literal); break; } const lastPos = this.pos; let ch = this.scanCharacter(decodeEscapeSequences); if (this.pos > lastPos + 1) { // Reference-decoded characters span multiple indexes, breaking naive assumptions. // Read in everything preceding the reference, and set the new position to the // index following it. result += this.text.slice(start, lastPos); start = this.pos; } if (ch === quote) { // If this is a terminal consisting solely of one backtick character (e.g. ```), // we capture the backtick. if (quote === CharacterCodes.Backtick && result === "" && this.pos < this.len) { const peekPos = this.pos; ch = this.scanCharacter(decodeEscapeSequences); if (ch === CharacterCodes.Backtick) { result = "`"; break; } this.pos = peekPos; } result += this.text.slice(start, this.pos - 1); break; } else if (decodeEscapeSequences && ch === CharacterCodes.Backslash) { // terminals cannot have escape sequences result += this.text.slice(start, this.pos - 1); result += this.scanEscapeSequence(); start = this.pos; continue; } else if (isLineTerminator(ch)) { this.pos--; result += this.text.slice(start, this.pos); this.setTokenAsUnterminated(); this.getDiagnostics().report(this.pos, diagnostic || Diagnostics.Unterminated_string_literal); break; } } return result; } private scanEscapeSequence(): string { const start = this.pos; if (this.pos >= this.len) { this.getDiagnostics().report(start, Diagnostics.Invalid_escape_sequence); return ""; } let ch = this.text.charCodeAt(this.pos++); switch (ch) { case CharacterCodes.Number0: return "\0"; case CharacterCodes.LowerB: return "\b"; case CharacterCodes.LowerT: return "\t"; case CharacterCodes.LowerN: return "\n"; case CharacterCodes.LowerV: return "\v"; case CharacterCodes.LowerF: return "\f"; case CharacterCodes.LowerR: return "\r"; case CharacterCodes.SingleQuote: return "\'"; case CharacterCodes.DoubleQuote: return "\""; case CharacterCodes.LowerX: case CharacterCodes.LowerU: ch = this.scanHexDigits(ch === CharacterCodes.LowerX ? 2 : 4, /*mustMatchCount*/ true); if (ch >= 0) { return String.fromCharCode(ch); } else { this.getDiagnostics().report(start, Diagnostics.Invalid_escape_sequence); return ""; } // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), // the line terminator is interpreted to be "the empty code unit sequence". case CharacterCodes.CarriageReturn: if (this.pos < this.len && this.text.charCodeAt(this.pos) === CharacterCodes.LineFeed) { this.pos++; } // fall through case CharacterCodes.LineFeed: case CharacterCodes.LineSeparator: case CharacterCodes.ParagraphSeparator: return "" default: return String.fromCharCode(ch); } } private decimalDigitAt(pos: number) { const ch = this.text.charCodeAt(pos); if (ch >= CharacterCodes.Number0 && ch <= CharacterCodes.Number9) { return ch - CharacterCodes.Number0; } return -1; } private hexDigitAt(pos: number) { const ch = this.text.charCodeAt(pos); if (ch >= CharacterCodes.Number0 && ch <= CharacterCodes.Number9) { return ch - CharacterCodes.Number0; } else if (ch >= CharacterCodes.UpperA && ch <= CharacterCodes.UpperF) { return ch - CharacterCodes.UpperA + 10; } else if (ch >= CharacterCodes.LowerA && ch <= CharacterCodes.LowerF) { return ch - CharacterCodes.LowerA + 10; } return -1; } private scanHexDigits(count: number, mustMatchCount?: boolean): number { let digits = 0; let value = 0; while (digits < count || !mustMatchCount) { const digit = this.hexDigitAt(this.pos); if (digit === -1) break; value = value * 16 + digit; this.pos++; digits++; } if (digits < count) { value = -1; } return value; } private scanNumber(): string { while (isDecimalDigit(this.text.charCodeAt(this.pos))) { this.pos++; } if (this.text.charCodeAt(this.pos) === CharacterCodes.Dot) { this.pos++; while (isDecimalDigit(this.text.charCodeAt(this.pos))) { this.pos++; } } let end = this.pos; if (this.text.charCodeAt(this.pos) === CharacterCodes.UpperE || this.text.charCodeAt(this.pos) === CharacterCodes.LowerE) { this.pos++; if (this.text.charCodeAt(this.pos) === CharacterCodes.Plus || this.text.charCodeAt(this.pos) === CharacterCodes.Minus) { this.pos++; } if (isDecimalDigit(this.text.charCodeAt(this.pos))) { this.pos++; while (isDecimalDigit(this.text.charCodeAt(this.pos))) { this.pos++; } end = this.pos; } else { this.getDiagnostics().report(this.pos, Diagnostics.Digit_expected); } } return +(this.text.substring(this.tokenPos, end)) + ""; } private getIdentifierToken(): SyntaxKind { const len = this.tokenValue.length; if (len >= 2 && len <= 9) { const ch = this.tokenValue.charCodeAt(0); if (ch >= CharacterCodes.LowerA && ch <= CharacterCodes.LowerT) { const token = stringToToken(this.tokenValue); if (token !== undefined) { return this.token = token; } } } return this.token = SyntaxKind.Identifier; } } function isLineTerminator(ch: number): boolean { return ch === CharacterCodes.CarriageReturn || ch === CharacterCodes.LineFeed; } function isWhiteSpace(ch: number) { switch (ch) { case CharacterCodes.Space: case CharacterCodes.Tab: case CharacterCodes.VerticalTab: case CharacterCodes.FormFeed: return true; } return false; } function isUpperAlpha(ch: number): boolean { return ch >= CharacterCodes.UpperA && ch <= CharacterCodes.UpperZ; } function isLowerAlpha(ch: number): boolean { return ch >= CharacterCodes.LowerA && ch <= CharacterCodes.LowerZ; } function isAlpha(ch: number): boolean { return isUpperAlpha(ch) || isLowerAlpha(ch); } function isDecimalDigit(ch: number): boolean { return ch >= CharacterCodes.Number0 && ch <= CharacterCodes.Number9; } function isAlphaNum(ch: number): boolean { return isAlpha(ch) || isDecimalDigit(ch); } function isHexDigit(ch: number): boolean { return ch >= CharacterCodes.UpperA && ch <= CharacterCodes.UpperF || ch >= CharacterCodes.LowerA && ch <= CharacterCodes.LowerF || ch >= CharacterCodes.Number0 && ch <= CharacterCodes.Number9; } function isIdentifierStart(ch: number): boolean { return isAlpha(ch) || ch === CharacterCodes.Underscore; } function isIdentifierPart(ch: number): boolean { return isAlphaNum(ch) || ch === CharacterCodes.Underscore; } function isHtmlTagNameStart(ch: number): boolean { return isLowerAlpha(ch); } function isHtmlTagNamePart(ch: number): boolean { return isIdentifierPart(ch) || ch === CharacterCodes.Minus; } function findHtmlTriviaEnd(text: string, pos: number, end: number) { while (pos < end) { const ch = text.charCodeAt(pos++); if (ch === CharacterCodes.GreaterThan) { return pos; } } return end; } function findHtmlTagNameEnd(text: string, pos: number, end: number) { if (pos < end && isHtmlTagNameStart(text.charCodeAt(pos))) { pos++; while (pos < end && isHtmlTagNamePart(text.charCodeAt(pos))) { pos++; } return pos; } return -1; } export function skipTrivia(text: string, pos: number, end: number, htmlTrivia?: HtmlTrivia[], commentTrivia?: CommentTrivia[]) { scan: while (pos < end) { const ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.CarriageReturn: case CharacterCodes.LineFeed: case CharacterCodes.Space: case CharacterCodes.Tab: case CharacterCodes.VerticalTab: case CharacterCodes.FormFeed: pos++; continue; case CharacterCodes.Slash: if (pos + 1 < end) { switch (text.charCodeAt(pos + 1)) { case CharacterCodes.Slash: { const commentEnd = findSingleLineCommentTriviaEnd(text, pos + 2, end); if (commentTrivia) { const comment = new SingleLineCommentTrivia(); comment.pos = pos; comment.end = commentEnd; commentTrivia.push(comment); } pos = commentEnd; continue; } case CharacterCodes.Asterisk: { const commentEnd = findMultiLineCommentTriviaEnd(text, pos + 2, end); if (commentTrivia) { const comment = new MultiLineCommentTrivia(); comment.pos = pos; comment.end = commentEnd; commentTrivia.push(comment); } pos = commentEnd; continue; } } } break scan; case CharacterCodes.LessThan: if (pos + 1 < end) { const ch = text.charCodeAt(pos + 1); if (ch === CharacterCodes.Slash || (ch >= CharacterCodes.LowerA && ch <= CharacterCodes.LowerZ)) { const triviaEnd = findHtmlTriviaEnd(text, pos + 1, end); if (htmlTrivia) { const tagNamePos = ch === CharacterCodes.Slash ? pos + 2 : pos + 1; const tagNameEnd = findHtmlTagNameEnd(text, tagNamePos, triviaEnd); if (tagNameEnd !== -1) { const tagName = text.slice(tagNamePos, tagNameEnd); const tag = ch === CharacterCodes.Slash ? new HtmlCloseTagTrivia(tagName) : new HtmlOpenTagTrivia(tagName); tag.pos = pos; tag.end = triviaEnd; htmlTrivia.push(tag); } } pos = triviaEnd; continue; } } break scan; default: break scan; } } return pos; } export function scanHtmlTrivia(text: string, pos: number, end: number): HtmlTrivia[] | undefined { const trivia: HtmlTrivia[] = []; skipTrivia(text, pos, end, trivia); return trivia.length > 0 ? trivia : undefined; } function findMultiLineCommentTriviaEnd(text: string, pos: number, end: number) { while (pos < end) { const ch = text.charCodeAt(pos); if (ch === CharacterCodes.Asterisk && pos + 1 < end && text.charCodeAt(pos + 1) === CharacterCodes.Slash) { return pos + 2; } pos++; } return end; } function findSingleLineCommentTriviaEnd(text: string, pos: number, end: number) { while (pos < end) { const ch = text.charCodeAt(pos); if (ch === CharacterCodes.CarriageReturn || ch === CharacterCodes.LineFeed) { return pos; } pos++; } return end; } const htmlCharacterEntities: Record<string, number> = { quot: 0x0022, amp: 0x0026, apos: 0x0027, lt: 0x003C, gt: 0x003E, nbsp: 0x00A0, iexcl: 0x00A1, cent: 0x00A2, pound: 0x00A3, curren: 0x00A4, yen: 0x00A5, brvbar: 0x00A6, sect: 0x00A7, uml: 0x00A8, copy: 0x00A9, ordf: 0x00AA, laquo: 0x00AB, not: 0x00AC, shy: 0x00AD, reg: 0x00AE, macr: 0x00AF, deg: 0x00B0, plusmn: 0x00B1, sup2: 0x00B2, sup3: 0x00B3, acute: 0x00B4, micro: 0x00B5, para: 0x00B6, middot: 0x00B7, cedil: 0x00B8, sup1: 0x00B9, ordm: 0x00BA, raquo: 0x00BB, frac14: 0x00BC, frac12: 0x00BD, frac34: 0x00BE, iquest: 0x00BF, Agrave: 0x00C0, Aacute: 0x00C1, Acirc: 0x00C2, Atilde: 0x00C3, Auml: 0x00C4, Aring: 0x00C5, AElig: 0x00C6, Ccedil: 0x00C7, Egrave: 0x00C8, Eacute: 0x00C9, Ecirc: 0x00CA, Euml: 0x00CB, Igrave: 0x00CC, Iacute: 0x00CD, Icirc: 0x00CE, Iuml: 0x00CF, ETH: 0x00D0, Ntilde: 0x00D1, Ograve: 0x00D2, Oacute: 0x00D3, Ocirc: 0x00D4, Otilde: 0x00D5, Ouml: 0x00D6, times: 0x00D7, Oslash: 0x00D8, Ugrave: 0x00D9, Uacute: 0x00DA, Ucirc: 0x00DB, Uuml: 0x00DC, Yacute: 0x00DD, THORN: 0x00DE, szlig: 0x00DF, agrave: 0x00E0, aacute: 0x00E1, acirc: 0x00E2, atilde: 0x00E3, auml: 0x00E4, aring: 0x00E5, aelig: 0x00E6, ccedil: 0x00E7, egrave: 0x00E8, eacute: 0x00E9, ecirc: 0x00EA, euml: 0x00EB, igrave: 0x00EC, iacute: 0x00ED, icirc: 0x00EE, iuml: 0x00EF, eth: 0x00F0, ntilde: 0x00F1, ograve: 0x00F2, oacute: 0x00F3, ocirc: 0x00F4, otilde: 0x00F5, ouml: 0x00F6, divide: 0x00F7, oslash: 0x00F8, ugrave: 0x00F9, uacute: 0x00FA, ucirc: 0x00FB, uuml: 0x00FC, yacute: 0x00FD, thorn: 0x00FE, yuml: 0x00FF, OElig: 0x0152, oelig: 0x0153, Scaron: 0x0160, scaron: 0x0161, Yuml: 0x0178, fnof: 0x0192, circ: 0x02C6, tilde: 0x02DC, Alpha: 0x0391, Beta: 0x0392, Gamma: 0x0393, Delta: 0x0394, Epsilon: 0x0395, Zeta: 0x0396, Eta: 0x0397, Theta: 0x0398, Iota: 0x0399, Kappa: 0x039A, Lambda: 0x039B, Mu: 0x039C, Nu: 0x039D, Xi: 0x039E, Omicron: 0x039F, Pi: 0x03A0, Rho: 0x03A1, Sigma: 0x03A3, Tau: 0x03A4, Upsilon: 0x03A5, Phi: 0x03A6, Chi: 0x03A7, Psi: 0x03A8, Omega: 0x03A9, alpha: 0x03B1, beta: 0x03B2, gamma: 0x03B3, delta: 0x03B4, epsilon: 0x03B5, zeta: 0x03B6, eta: 0x03B7, theta: 0x03B8, iota: 0x03B9, kappa: 0x03BA, lambda: 0x03BB, mu: 0x03BC, nu: 0x03BD, xi: 0x03BE, omicron: 0x03BF, pi: 0x03C0, rho: 0x03C1, sigmaf: 0x03C2, sigma: 0x03C3, tau: 0x03C4, upsilon: 0x03C5, phi: 0x03C6, chi: 0x03C7, psi: 0x03C8, omega: 0x03C9, thetasym: 0x03D1, upsih: 0x03D2, piv: 0x03D6, ensp: 0x2002, emsp: 0x2003, thinsp: 0x2009, zwnj: 0x200C, zwj: 0x200D, lrm: 0x200E, rlm: 0x200F, ndash: 0x2013, mdash: 0x2014, lsquo: 0x2018, rsquo: 0x2019, sbquo: 0x201A, ldquo: 0x201C, rdquo: 0x201D, bdquo: 0x201E, dagger: 0x2020, Dagger: 0x2021, bull: 0x2022, hellip: 0x2026, permil: 0x2030, prime: 0x2032, Prime: 0x2033, lsaquo: 0x2039, rsaquo: 0x203A, oline: 0x203E, frasl: 0x2044, euro: 0x20AC, image: 0x2111, weierp: 0x2118, real: 0x211C, trade: 0x2122, alefsym: 0x2135, larr: 0x2190, uarr: 0x2191, rarr: 0x2192, darr: 0x2193, harr: 0x2194, crarr: 0x21B5, lArr: 0x21D0, uArr: 0x21D1, rArr: 0x21D2, dArr: 0x21D3, hArr: 0x21D4, forall: 0x2200, part: 0x2202, exist: 0x2203, empty: 0x2205, nabla: 0x2207, isin: 0x2208, notin: 0x2209, ni: 0x220B, prod: 0x220F, sum: 0x2211, minus: 0x2212, lowast: 0x2217, radic: 0x221A, prop: 0x221D, infin: 0x221E, ang: 0x2220, and: 0x2227, or: 0x2228, cap: 0x2229, cup: 0x222A, int: 0x222B, there4: 0x2234, sim: 0x223C, cong: 0x2245, asymp: 0x2248, ne: 0x2260, equiv: 0x2261, le: 0x2264, ge: 0x2265, sub: 0x2282, sup: 0x2283, nsub: 0x2284, sube: 0x2286, supe: 0x2287, oplus: 0x2295, otimes: 0x2297, perp: 0x22A5, sdot: 0x22C5, lceil: 0x2308, rceil: 0x2309, lfloor: 0x230A, rfloor: 0x230B, lang: 0x2329, rang: 0x232A, loz: 0x25CA, spades: 0x2660, clubs: 0x2663, hearts: 0x2665, diams: 0x2666 };
the_stack
import {Constructor, valueof} from '../../../types/GlobalTypes'; import {Camera} from 'three/src/cameras/Camera'; import {CoreTransform} from '../../../core/Transform'; import {ObjNodeRenderOrder} from './_Base'; import {ThreejsCameraControlsController} from './utils/cameras/ControlsController'; import {LayersController, LayerParamConfig} from './utils/LayersController'; import {PostProcessController, CameraPostProcessParamConfig} from './utils/cameras/PostProcessController'; import {RenderController, CameraRenderParamConfig} from './utils/cameras/RenderController'; import {TransformedParamConfig, TransformController} from './utils/TransformController'; import {ChildrenDisplayController} from './utils/ChildrenDisplayController'; import {DisplayNodeController} from '../utils/DisplayNodeController'; import {NodeContext} from '../../poly/NodeContext'; import {ThreejsViewer, ThreejsViewerProperties} from '../../viewers/Threejs'; import {FlagsControllerD} from '../utils/FlagsController'; import {BaseParamType} from '../../params/_Base'; import {BaseNodeType} from '../_Base'; import {BaseSopNodeType} from '../sop/_Base'; import {TypedObjNode} from './_Base'; import {BaseViewerType} from '../../viewers/_Base'; import {HierarchyController} from './utils/HierarchyController'; import {GeoNodeChildrenMap} from '../../poly/registers/nodes/Sop'; import {ParamsInitData} from '../utils/io/IOController'; import {Raycaster} from 'three/src/core/Raycaster'; import {Vector2} from 'three/src/math/Vector2'; import {CoreType} from '../../../core/Type'; import {CameraHelper} from './utils/helpers/CameraHelper'; export interface OrthoOrPerspCamera extends Camera { near: number; far: number; updateProjectionMatrix: () => void; getFocalLength?: () => void; } const EVENT_CHANGE = {type: 'change'}; export const BASE_CAMERA_DEFAULT = { near: 1.0, far: 100.0, }; export enum UpdateFromControlsMode { ON_END = 'on move end', ALWAYS = 'always', NEVER = 'never', } export const UPDATE_FROM_CONTROLS_MODES: UpdateFromControlsMode[] = [ UpdateFromControlsMode.ON_END, UpdateFromControlsMode.ALWAYS, UpdateFromControlsMode.NEVER, ]; import {ParamConfig, NodeParamsConfig} from '../utils/params/ParamsConfig'; import {isBooleanTrue} from '../../../core/BooleanValue'; export function CameraMainCameraParamConfig<TBase extends Constructor>(Base: TBase) { return class Mixin extends Base { setMainCamera = ParamConfig.BUTTON(null, { callback: (node: BaseNodeType, param: BaseParamType) => { BaseCameraObjNodeClass.PARAM_CALLBACK_setMasterCamera(node as BaseCameraObjNodeType); }, }); }; } export function ThreejsCameraTransformParamConfig<TBase extends Constructor>(Base: TBase) { return class Mixin extends Base { camera = ParamConfig.FOLDER(); /** @param controls node to allow the camera to be moved by user input */ controls = ParamConfig.NODE_PATH('', { nodeSelection: { context: NodeContext.EVENT, }, }); /** @param define when the camera node transform parameters are updated after the controls have moved the internal camera object */ updateFromControlsMode = ParamConfig.INTEGER( UPDATE_FROM_CONTROLS_MODES.indexOf(UpdateFromControlsMode.ON_END), { menu: { entries: UPDATE_FROM_CONTROLS_MODES.map((name, value) => { return {name, value}; }), }, } ); // allowUpdateFromControls = ParamConfig.BOOLEAN(1); /** @param near */ near = ParamConfig.FLOAT(BASE_CAMERA_DEFAULT.near, { range: [0, 100], cook: false, computeOnDirty: true, callback: (node: BaseNodeType, param: BaseParamType) => { BaseThreejsCameraObjNodeClass.PARAM_CALLBACK_update_near_far_from_param( node as BaseThreejsCameraObjNodeType, param ); }, }); /** @param far */ far = ParamConfig.FLOAT(BASE_CAMERA_DEFAULT.far, { range: [0, 100], cook: false, computeOnDirty: true, callback: (node: BaseNodeType, param: BaseParamType) => { BaseThreejsCameraObjNodeClass.PARAM_CALLBACK_update_near_far_from_param( node as BaseThreejsCameraObjNodeType, param ); }, }); // aspect = ParamConfig.FLOAT(1); // lock_width = ParamConfig.BOOLEAN(1); // look_at = ParamConfig.OPERATOR_PATH(''); /** @param display */ display = ParamConfig.BOOLEAN(1); /** @param show helper */ showHelper = ParamConfig.BOOLEAN(0); }; } export enum FOVAdjustMode { DEFAULT = 'default', COVER = 'cover', CONTAIN = 'contain', } export const FOV_ADJUST_MODES: FOVAdjustMode[] = [FOVAdjustMode.DEFAULT, FOVAdjustMode.COVER, FOVAdjustMode.CONTAIN]; export function ThreejsCameraFOVParamConfig<TBase extends Constructor>(Base: TBase) { return class Mixin extends Base { /** @param fov adjust mode */ fovAdjustMode = ParamConfig.INTEGER(FOV_ADJUST_MODES.indexOf(FOVAdjustMode.DEFAULT), { menu: { entries: FOV_ADJUST_MODES.map((name, value) => { return {name, value}; }), }, }); /** @param expected aspect ratio */ expectedAspectRatio = ParamConfig.FLOAT('16/9', { visibleIf: [ {fovAdjustMode: FOV_ADJUST_MODES.indexOf(FOVAdjustMode.COVER)}, {fovAdjustMode: FOV_ADJUST_MODES.indexOf(FOVAdjustMode.CONTAIN)}, ], range: [0, 2], rangeLocked: [true, false], }); // vertical_fov_range = ParamConfig.VECTOR2([0, 100], {visibleIf: {lock_width: 1}}); // horizontal_fov_range = ParamConfig.VECTOR2([0, 100], {visibleIf: {lock_width: 0}}); }; } export class BaseCameraObjParamsConfig extends CameraMainCameraParamConfig(NodeParamsConfig) {} export class BaseThreejsCameraObjParamsConfig extends CameraPostProcessParamConfig( CameraRenderParamConfig( TransformedParamConfig( LayerParamConfig(ThreejsCameraTransformParamConfig(CameraMainCameraParamConfig(NodeParamsConfig))) ) ) ) {} export abstract class TypedCameraObjNode< O extends OrthoOrPerspCamera, K extends BaseCameraObjParamsConfig > extends TypedObjNode<O, K> { // public readonly flags: FlagsControllerD = new FlagsControllerD(this); public readonly renderOrder: number = ObjNodeRenderOrder.CAMERA; protected _object!: O; protected _aspect: number = -1; get object() { return this._object; } async cook() { this.updateCamera(); this._object.dispatchEvent(EVENT_CHANGE); this.cookController.endCook(); } on_create() {} on_delete() {} prepareRaycaster(mouse: Vector2, raycaster: Raycaster) {} camera() { return this._object; } updateCamera() {} static PARAM_CALLBACK_setMasterCamera(node: BaseCameraObjNodeType) { node.set_as_master_camera(); } set_as_master_camera() { this.scene().camerasController.setMainCameraNodePath(this.path()); } setupForAspectRatio(aspect: number) {} protected _updateForAspectRatio(): void {} update_transform_params_from_object() { // CoreTransform.set_params_from_matrix(this._object.matrix, this, {scale: false}) CoreTransform.set_params_from_object(this._object, this); } abstract createViewer(element: HTMLElement): BaseViewerType; static PARAM_CALLBACK_update_from_param(node: BaseCameraObjNodeType, param: BaseParamType) { (node.object as any)[param.name()] = (node.pv as any)[param.name()]; } } export class TypedThreejsCameraObjNode< O extends OrthoOrPerspCamera, K extends BaseThreejsCameraObjParamsConfig > extends TypedCameraObjNode<O, K> { public readonly flags: FlagsControllerD = new FlagsControllerD(this); readonly hierarchyController: HierarchyController = new HierarchyController(this); readonly transformController: TransformController = new TransformController(this); protected _controls_controller: ThreejsCameraControlsController | undefined; get controls_controller(): ThreejsCameraControlsController { return (this._controls_controller = this._controls_controller || new ThreejsCameraControlsController(this)); } protected _layers_controller: LayersController | undefined; get layers_controller() { return (this._layers_controller = this._layers_controller || new LayersController(this)); } protected _render_controller: RenderController | undefined; get renderController(): RenderController { return (this._render_controller = this._render_controller || new RenderController(this)); } protected _post_process_controller: PostProcessController | undefined; get postProcessController(): PostProcessController { return (this._post_process_controller = this._post_process_controller || new PostProcessController(this)); } // display_node and children_display controllers public readonly childrenDisplayController: ChildrenDisplayController = new ChildrenDisplayController(this); public readonly displayNodeController: DisplayNodeController = new DisplayNodeController( this, this.childrenDisplayController.displayNodeControllerCallbacks() ); // protected _children_controller_context = NodeContext.SOP; initializeBaseNode() { super.initializeBaseNode(); this.io.outputs.setHasOneOutput(); this.hierarchyController.initializeNode(); this.transformController.initializeNode(); this.childrenDisplayController.initializeNode(); this.initHelperHook(); } createNode<S extends keyof GeoNodeChildrenMap>( node_class: S, params_init_value_overrides?: ParamsInitData ): GeoNodeChildrenMap[S]; createNode<K extends valueof<GeoNodeChildrenMap>>( node_class: Constructor<K>, params_init_value_overrides?: ParamsInitData ): K; createNode<K extends valueof<GeoNodeChildrenMap>>( node_class: Constructor<K>, params_init_value_overrides?: ParamsInitData ): K { return super.createNode(node_class, params_init_value_overrides) as K; } children() { return super.children() as BaseSopNodeType[]; } nodesByType<K extends keyof GeoNodeChildrenMap>(type: K): GeoNodeChildrenMap[K][] { return super.nodesByType(type) as GeoNodeChildrenMap[K][]; } prepareRaycaster(mouse: Vector2, raycaster: Raycaster) { raycaster.setFromCamera(mouse, this._object); } async cook() { this.transformController.update(); this.layers_controller.update(); // await this.background_controller.update(); this.updateNearFar(); this.renderController.update(); this.updateCamera(); this._updateHelper(); this.controls_controller.update_controls(); // TODO: ideally the update transform and update camera // can both return if the camera has changed // and we can run this here instead of inside the update_transform and update_camera // this._object.dispatchEvent( EVENT_CHANGE ) this._object.dispatchEvent(EVENT_CHANGE); this.cookController.endCook(); } static PARAM_CALLBACK_update_near_far_from_param(node: BaseThreejsCameraObjNodeType, param: BaseParamType) { node.updateNearFar(); } updateNearFar() { if (this._object.near != this.pv.near || this._object.far != this.pv.far) { this._object.near = this.pv.near; this._object.far = this.pv.far; this._object.updateProjectionMatrix(); this._updateHelper(); } } setupForAspectRatio(aspect: number) { if (CoreType.isNaN(aspect)) { return; } if (aspect && this._aspect != aspect) { this._aspect = aspect; this._updateForAspectRatio(); } } createViewer(element: HTMLElement, viewer_properties?: ThreejsViewerProperties): ThreejsViewer { return new ThreejsViewer(element, this.scene(), this, viewer_properties); } static PARAM_CALLBACK_reset_effects_composer(node: BaseThreejsCameraObjNodeType) { node.postProcessController.reset(); } // // // HELPER // // private _helper: CameraHelper | undefined; initHelperHook() { this.flags.display.onUpdate(() => { this._updateHelper(); }); } helperVisible() { return this.flags.display.active() && isBooleanTrue(this.pv.showHelper); } private _createHelper(): CameraHelper { const helper = new CameraHelper(this.object); helper.update(); return helper; } _updateHelper() { if (this.helperVisible()) { if (!this._helper) { this._helper = this._createHelper(); } if (this._helper) { this.object.add(this._helper); this._helper.update(); } } else { if (this._helper) { this.object.remove(this._helper); } } } } export type BaseCameraObjNodeType = TypedCameraObjNode<OrthoOrPerspCamera, BaseCameraObjParamsConfig>; export abstract class BaseCameraObjNodeClass extends TypedCameraObjNode< OrthoOrPerspCamera, BaseCameraObjParamsConfig > {} export type BaseThreejsCameraObjNodeType = TypedThreejsCameraObjNode< OrthoOrPerspCamera, BaseThreejsCameraObjParamsConfig >; export class BaseThreejsCameraObjNodeClass extends TypedThreejsCameraObjNode< OrthoOrPerspCamera, BaseThreejsCameraObjParamsConfig > { PARAM_CALLBACK_update_effects_composer(node: BaseNodeType) {} }
the_stack
export async function createPoints(upper: int) { "use speedyjs"; const array = [ 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, 5336, 10324, 812, 6264, 14384, 20184, 11252, 15776, 9744, 3132, 10904, 3480, 7308, 14848, 16472, 16472, 10440, 14036, 10672, 13804, 1160, 18560, 10788, 13572, 15660, 11368, 15544, 12760, 5336, 18908, 6264, 19140, 11832, 17516, 10672, 14152, 10208, 15196, 12180, 14848, 11020, 10208, 7656, 17052, 16240, 8352, 10440, 14732, 9164, 15544, 8004, 11020, 5684, 11948, 9512, 16472, 13688, 17516, 11484, 8468, 3248, 14152, 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, 8584, 13108, 7772, 14732, 7540, 15080, 7424, 17516, 8352, 17052, 7540, 16820, 7888, 17168, 9744, 15196, 9164, 14964, 9744, 16240, 7888, 16936, 8236, 15428, 9512, 17400, 9164, 16008, 8700, 15312, 11716, 16008, 12992, 14964, 12412, 14964, 12296, 15312, 12528, 15196, 15312, 6612, 11716, 16124, 11600, 19720, 10324, 17516, 12412, 13340, 12876, 12180, 13688, 10904, 13688, 11716, 13688, 12528, 11484, 13224, 12296, 12760, 12064, 12528, 12644, 10556, 11832, 11252, 11368, 12296, 11136, 11020, 10556, 11948, 10324, 11716, 11484, 9512, 11484, 7540, 11020, 7424, 11484, 9744, 16936, 12180, 17052, 12064, 16936, 11832, 17052, 11600, 13804, 18792, 12064, 14964, 12180, 15544, 14152, 18908, 5104, 14616, 6496, 17168, 5684, 13224, 15660, 10788, // 4'000 9860, 14152, 9396, 14616, 11252, 14848, 11020, 13456, 9512, 15776, 10788, 13804, 10208, 14384, 11600, 13456, 11252, 14036, 10672, 15080, 11136, 14152, 9860, 13108, 10092, 14964, 9512, 13340, 10556, 13688, 9628, 14036, 10904, 13108, 11368, 12644, 11252, 13340, 10672, 13340, 11020, 13108, 11020, 13340, 11136, 13572, 11020, 13688, // 4048, js faster 8468, 11136, 8932, 12064, 9512, 12412, 7772, 11020, 8352, 10672, 9164, 12876, 9744, 12528, 8352, 10324, 8236, 11020, 8468, 12876, 8700, 14036, 8932, 13688, // 4072, js faster 9048, 13804, 8468, 12296, 8352, 12644, 8236, 13572, 9164, 13340, 8004, 12760, // 4084, js faster 8584, 13108, 7772, 14732, 7540, 15080, // 4094 js faster 7424, 17516, // 4096 js faster // 8352, 17052, // 4097 wasm faster <----- break // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // wasm faster // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, // 5336, 10324, // 812, 6264, // 14384, 20184, // 11252, 15776, // 9744, 3132, // 10904, 3480, // 7308, 14848, // 16472, 16472, // 10440, 14036, // 10672, 13804, // 1160, 18560, // 10788, 13572, // 15660, 11368, // 15544, 12760, // 5336, 18908, // 6264, 19140, // 11832, 17516, // 10672, 14152, // 10208, 15196, // 12180, 14848, // 11020, 10208, // 7656, 17052, // 16240, 8352, // 10440, 14732, // 9164, 15544, // 8004, 11020, // 5684, 11948, // 9512, 16472, // 13688, 17516, // 11484, 8468, // 3248, 14152, // 9860, 14152, // 9396, 14616, // 11252, 14848, // 11020, 13456, // 9512, 15776, // 10788, 13804, // 10208, 14384, // 11600, 13456, // 11252, 14036, // 10672, 15080, // 11136, 14152, // 9860, 13108, // 10092, 14964, // 9512, 13340, // 10556, 13688, // 9628, 14036, // 10904, 13108, // 11368, 12644, // 11252, 13340, // 10672, 13340, // 11020, 13108, // 11020, 13340, // 11136, 13572, // 11020, 13688, // 8468, 11136, // 8932, 12064, // 9512, 12412, // 7772, 11020, // 8352, 10672, // 9164, 12876, // 9744, 12528, // 8352, 10324, // 8236, 11020, // 8468, 12876, // 8700, 14036, // 8932, 13688, // 9048, 13804, // 8468, 12296, // 8352, 12644, // 8236, 13572, // 9164, 13340, // 8004, 12760, // 8584, 13108, // 7772, 14732, // 7540, 15080, // 7424, 17516, // 8352, 17052, // 7540, 16820, // 7888, 17168, // 9744, 15196, // 9164, 14964, // 9744, 16240, // 7888, 16936, // 8236, 15428, // 9512, 17400, // 9164, 16008, // 8700, 15312, // 11716, 16008, // 12992, 14964, // 12412, 14964, // 12296, 15312, // 12528, 15196, // 15312, 6612, // 11716, 16124, // 11600, 19720, // 10324, 17516, // 12412, 13340, // 12876, 12180, // 13688, 10904, // 13688, 11716, // 13688, 12528, // 11484, 13224, // 12296, 12760, // 12064, 12528, // 12644, 10556, // 11832, 11252, // 11368, 12296, // 11136, 11020, // 10556, 11948, // 10324, 11716, // 11484, 9512, // 11484, 7540, // 11020, 7424, // 11484, 9744, // 16936, 12180, // 17052, 12064, // 16936, 11832, // 17052, 11600, // 13804, 18792, // 12064, 14964, // 12180, 15544, // 14152, 18908, // 5104, 14616, // 6496, 17168, // 5684, 13224, // 15660, 10788, ]; return createPointsSync(array, upper); } function createPointsSync(array: int[], upper: int) { "use speedyjs"; array[0] = upper; let sum = 0; for (let i = 0; i < upper; ++i) { sum += array[i]; } return sum; } /// console.log(createPoints(12));
the_stack
import * as React from 'react'; import { Rule, SymbolizerKind, WellKnownName } from 'geostyler-style'; import { Data } from 'geostyler-data'; import { Radio, Form, Button, InputNumber, Tooltip } from 'antd'; import en_US from '../../locale/en_US'; import AttributeCombo from '../Filter/AttributeCombo/AttributeCombo'; import './RuleGenerator.less'; import { RadioChangeEvent } from 'antd/lib/radio'; import RuleGeneratorUtil from '../../Util/RuleGeneratorUtil'; import { KindField } from '../Symbolizer/Field/KindField/KindField'; import { WellKnownNameField } from '../Symbolizer/Field/WellKnownNameField/WellKnownNameField'; import { localize } from '../LocaleWrapper/LocaleWrapper'; import { brewer, InterpolationMode } from 'chroma-js'; import { ColorRampCombo } from './ColorRampCombo/ColorRampCombo'; import { ColorSpaceCombo } from './ColorSpaceCombo/ColorSpaceCombo'; import ColorsPreview from './ColorsPreview/ColorsPreview'; import { ClassificationMethod, ClassificationCombo } from './ClassificationCombo/ClassificationCombo'; import _get from 'lodash/get'; import { PlusSquareOutlined } from '@ant-design/icons'; export type LevelOfMeasurement = 'nominal' | 'ordinal' | 'cardinal'; interface RuleGeneratorLocale { attribute: string; generateButtonText: string; levelOfMeasurement: string; nominal: string; ordinal: string; cardinal: string; numberOfRules: string; colorRamp: string; colorRampPlaceholder: string; colorRampMinClassesWarningPre: string; colorRampMinClassesWarningPost: string; symbolizer: string; classification: string; classificationPlaceholder: string; colorSpace: string; preview: string; numberOfRulesViaKmeans: string; allDistinctValues: string; } // default props interface RuleGeneratorDefaultProps { unknownSymbolizerText?: string; /** Locale object containing translated text snippets */ locale: RuleGeneratorLocale; /** List of provided color ramps */ colorRamps: { [name: string]: string[]; }; /** List of color spaces to use */ colorSpaces: (InterpolationMode)[]; } interface RuleGeneratorState { attributeName?: string; attributeType?: string; numberOfRules?: number; distinctValues?: string[]; levelOfMeasurement?: LevelOfMeasurement; colorRamp?: string; symbolizerKind?: SymbolizerKind; wellKnownName?: WellKnownName; classificationMethod?: ClassificationMethod; colorSpace: InterpolationMode; hasError: boolean; } // non default props export interface RuleGeneratorProps extends Partial<RuleGeneratorDefaultProps> { internalDataDef: Data; onRulesChange?: (rules: Rule[]) => void; } export class RuleGenerator extends React.Component<RuleGeneratorProps, RuleGeneratorState> { static componentName: string = 'RuleGenerator'; public static defaultProps: RuleGeneratorDefaultProps = { locale: en_US.GsRuleGenerator, colorSpaces: ['hsl', 'hsv', 'hsi', 'lab', 'lch', 'hcl', 'rgb'], // rgba, cmyk and gl crash colorRamps: { GeoStyler: ['#E7000E', '#F48E00', '#FFED00', '#00943D', '#272C82', '#611E82'], GreenRed: ['#00FF00', '#FF0000'], ...brewer } }; private minNrClasses: number; constructor(props: RuleGeneratorProps) { super(props); const { internalDataDef } = this.props; const symbolizerKind = RuleGeneratorUtil.guessSymbolizerFromData(internalDataDef); this.minNrClasses = 2; this.state = { symbolizerKind, wellKnownName: 'circle', colorRamp: props.colorRamps && props.colorRamps.GeoStyler ? 'GeoStyler' : undefined, colorSpace: 'hsl', numberOfRules: 2, distinctValues: [], hasError: false }; } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { this.setState({ hasError: true }); } onAttributeChange = (attributeName: string) => { const { internalDataDef } = this.props; const attributeType = _get(internalDataDef, `schema.properties[${attributeName}].type`); let { classificationMethod } = this.state; if (attributeType === 'string' && classificationMethod === 'kmeans') { classificationMethod = undefined; } const distinctValues = RuleGeneratorUtil.getDistinctValues(internalDataDef, attributeName) || []; this.setState({ attributeName, distinctValues, attributeType, levelOfMeasurement: attributeType === 'string' ? 'nominal' : 'cardinal', classificationMethod }); }; onLevelOfMeasurementChange = (event: RadioChangeEvent) => { const levelOfMeasurement = event.target.value; this.setState({levelOfMeasurement}); }; onClassificationChange = (classificationMethod: ClassificationMethod) => { this.setState({classificationMethod}); }; onNumberChange = (numberOfRules: number) => { this.setState({ numberOfRules }); }; onAllDistinctClicked = () => { this.setState({ numberOfRules: this.state.distinctValues.length }); }; onColorRampChange = (colorRamp: string) => { this.setState({colorRamp}); }; onColorSpaceChange = (colorSpace: InterpolationMode) => { this.setState({colorSpace}); }; onSymbolizerKindChange = (symbolizerKind: SymbolizerKind) => { let { wellKnownName } = this.state; if (symbolizerKind === 'Mark' && !wellKnownName) { wellKnownName = 'circle'; } else { wellKnownName = undefined; } this.setState({ symbolizerKind, wellKnownName }); }; onWellKnownNameFieldChange = (wellKnownName: WellKnownName) => { this.setState({ wellKnownName }); }; onGenerateClick = () => { const { onRulesChange, internalDataDef, colorRamps } = this.props; const { attributeName, classificationMethod, colorRamp, levelOfMeasurement, numberOfRules, symbolizerKind, wellKnownName } = this.state; const rules = RuleGeneratorUtil.generateRules({ attributeName, classificationMethod, colors: colorRamps[colorRamp], data: internalDataDef, levelOfMeasurement, numberOfRules, symbolizerKind, wellKnownName }); if (classificationMethod === 'kmeans') { this.setState({ numberOfRules: rules.length }); } if (onRulesChange) { onRulesChange(rules); } }; render() { if (this.state.hasError) { return <h1>An error occured in the RuleGenerator UI.</h1>; } const { colorRamps, colorSpaces, internalDataDef, locale } = this.props; const { attributeName, attributeType, classificationMethod, colorRamp, colorSpace, levelOfMeasurement, numberOfRules, symbolizerKind, wellKnownName, distinctValues } = this.state; const previewColors = RuleGeneratorUtil.generateColors(colorRamps[colorRamp], numberOfRules, colorSpace); return ( <div className="gs-rule-generator" > <Form layout="horizontal"> <AttributeCombo value={attributeName} internalDataDef={internalDataDef} onAttributeChange={this.onAttributeChange} validateStatus={attributeName ? 'success' : 'warning'} /> <Form.Item label={locale.levelOfMeasurement} > <Radio.Group onChange={this.onLevelOfMeasurementChange} value={levelOfMeasurement} buttonStyle="solid" > <Radio.Button value="nominal" > {locale.nominal} </Radio.Button> <Radio.Button value="cardinal" disabled={attributeType === 'string'} > {locale.cardinal} </Radio.Button> </Radio.Group> </Form.Item> { levelOfMeasurement !== 'cardinal' ? null : <Form.Item label={locale.classification} > <ClassificationCombo classification={classificationMethod} onChange={this.onClassificationChange} /> </Form.Item> } <Form.Item label={locale.numberOfRules} validateStatus={ classificationMethod === 'kmeans' ? 'warning' : numberOfRules < this.minNrClasses ? 'error' : undefined } help={classificationMethod === 'kmeans' ? locale.numberOfRulesViaKmeans : numberOfRules < this.minNrClasses // eslint-disable-next-line max-len ? `${locale.colorRampMinClassesWarningPre} ${this.minNrClasses} ${locale.colorRampMinClassesWarningPost}` : undefined } > <div> <InputNumber min={this.minNrClasses} max={100} value={numberOfRules} onChange={this.onNumberChange} /> { levelOfMeasurement === 'nominal' && distinctValues.length > 0 && <Tooltip title={locale.allDistinctValues}> <Button className="all-distinct-values-button" icon={<PlusSquareOutlined />} onClick={this.onAllDistinctClicked} /> </Tooltip> } </div> </Form.Item> <fieldset> <legend>{locale.symbolizer}</legend> <Form.Item> <KindField kind={symbolizerKind} symbolizerKinds={[ 'Fill', 'Mark', 'Line' ]} onChange={this.onSymbolizerKindChange} /> </Form.Item> { symbolizerKind !== 'Mark' ? null : <Form.Item> <WellKnownNameField wellKnownName={wellKnownName} onChange={this.onWellKnownNameFieldChange} /> </Form.Item> } <Form.Item label={locale.colorRamp} help={numberOfRules < this.minNrClasses ? `${locale.colorRampMinClassesWarningPre} ${this.minNrClasses} ${locale.colorRampMinClassesWarningPost}` : undefined} > <ColorRampCombo colorRamps={colorRamps} colorRamp={colorRamp} onChange={this.onColorRampChange} /> </Form.Item> {colorSpaces.length > 0 ? <Form.Item label={locale.colorSpace} > <ColorSpaceCombo colorSpace={colorSpace} colorSpaces={colorSpaces} onChange={this.onColorSpaceChange} /> </Form.Item> : null} <Form.Item label={locale.preview} > <ColorsPreview colors={previewColors} /> </Form.Item> </fieldset> <Form.Item> <Button className="gs-rule-generator-submit-button" type="primary" onClick={this.onGenerateClick} disabled={numberOfRules < this.minNrClasses || !attributeName} > {locale.generateButtonText} </Button> </Form.Item> </Form> </div> ); } } export default localize(RuleGenerator, RuleGenerator.componentName);
the_stack
(function beautify_script_init():void { "use strict"; const script = function beautify_script(options:any):string { let scolon:number = 0, news:number = 0; const data:data = options.parsed, lexer:string = "script", scopes:scriptScopes = prettydiff.scopes, b:number = (prettydiff.end < 1 || prettydiff.end > data.token.length) ? data.token.length : prettydiff.end + 1, externalIndex:externalIndex = {}, // levels sets the white space value between the current token and the next token // * -20 value means no white space // * -10 means to separate with a space // * 0 and above is the number of indentation to insert levels:number[] = (function beautify_script_level():number[] { let a = prettydiff.start, //will store the current level of indentation indent:number = (isNaN(options.indent_level) === true) ? 0 : Number(options.indent_level), notcomment:boolean = false, // if in comments before any code lastlist:boolean = false, //remembers the list status of the most recently closed block ctype:string = "", //ctype stands for "current type" ctoke:string = "", //ctoke standa for "current token" ltype:string = data.types[0], //ltype stands for "last type" ltoke:string = data.token[0]; //ltype stands for "last token" const varindex:number[] = [-1], //index in current scope of last var, let, or const keyword list:boolean[] = [], //stores comma status of current block level:number[] = (prettydiff.start > 0) ? Array(prettydiff.start).fill(0, 0, prettydiff.start) : [], ternary:number[] = [], //used to identify ternary statments extraindent = [ [] ], //stores token indexes where extra indentation occurs from ternaries and broken method chains arrbreak:boolean[] = [], //array where a method break has occurred destruct:boolean[] = [], //attempt to identify object destructuring itemcount:number[] = [], //counts items in destructured lists assignlist:boolean[] = [false], //are you in a list right now? wordlist:boolean[] = [], count:number[] = [], comment = function beautify_script_level_comment():void { destructfix(false, false); let ind:number = (options.comments === true) ? 0 : indent; if (notcomment === false && (/\/\u002a\s*global\s/).test(data.token[a]) === true) { let globallist:string[] = data.token[a].replace(/\/\u002a\s*global\s+/, "").replace(/\s*\u002a\/$/, "").split(","), aa:number = globallist.length; do { aa = aa - 1; globallist[aa] = globallist[aa].replace(/\s+/g, ""); if (globallist[aa] !== "") { scopes.push([globallist[aa], -1]); } } while (aa > 0); } if (data.types[a - 1] === "comment" || data.types[a + 1] === "comment") { level[a - 1] = ind; } else if (data.lines[a] < 2) { let aa:number = a + 1; if (data.types[aa] === "comment") { do { aa = aa + 1; } while (aa < b && data.types[aa] === "comment"); } if (a < b - 1 && data.stack[aa] !== "block" && (data.token[aa] === "{" || data.token[aa] === "x{")) { let bb:number = scopes.length; data.begin.splice(a, 0, data.begin[aa]); data.ender.splice(a, 0, data.ender[aa]); data.lexer.splice(a, 0, data.lexer[aa]); data.lines.splice(a, 0, data.lines[aa]); data.stack.splice(a, 0, data.stack[aa]); data.token.splice(a, 0, data.token[aa]); data.types.splice(a, 0, data.types[aa]); if (bb > 0) { do { bb = bb - 1; if (scopes[bb][1] === aa) { scopes[bb][1] = a; } else if (scopes[bb][1] < a) { break; } } while (bb > 0); } aa = aa + 1; data.begin.splice(aa, 1); data.ender.splice(aa, 1); data.lexer.splice(aa, 1); data.lines.splice(aa, 1); data.stack.splice(aa, 1); data.token.splice(aa, 1); data.types.splice(aa, 1); bb = a + 1; do { data.begin[bb] = a; data.stack[bb] = data.stack[aa]; bb = bb + 1; } while (bb < aa); bb = bb + 1; do { if (data.begin[bb] === data.begin[aa]) { data.begin[bb] = a; if (data.types[bb] === "end") { break; } } bb = bb + 1; } while (bb < b - 1); data.begin[aa] = a; a = a - 1; } else { level[a - 1] = -10; if (data.stack[a] === "paren" || data.stack[a] === "method") { level.push(indent + 2); } else { level.push(indent); } if (options.comment_line === true && level[a] > -1 && data.lines[a] < 3) { data.lines[a] = 3; } } if (data.types[a + 1] !== "comment") { notcomment = true; } return; } else if (data.token[a - 1] === ",") { level[a - 1] = ind; } else if (ltoke === "=" && data.types[a - 1] !== "comment" && (/^(\/\*\*\s*@[a-z_]+\s)/).test(ctoke) === true) { level[a - 1] = -10; } else if (ltoke === "{" && data.types[a - 1] !== "comment" && data.lines[0] < 2) { level[a - 1] = -10; } else { level[a - 1] = ind; } if (data.types[a + 1] !== "comment") { notcomment = true; } if (data.token[data.begin[a]] === "(") { level.push(indent + 1); } else { level.push(indent); } if (options.comment_line === true && level[a] > -1 && data.lines[a] < 3) { data.lines[a] = 3; } }, destructfix = function beautify_script_level_destructFix(listFix:boolean, override:boolean):void { // listfix - at the end of a list correct the containing list override - to // break arrays with more than 4 items into a vertical list let c:number = a - 1, d:number = (listFix === true) ? 0 : 1; const ei:number[] = (extraindent[extraindent.length - 1] === undefined) ? [] : extraindent[extraindent.length - 1], arrayCheck:boolean = ( override === false && data.stack[a] === "array" && listFix === true && ctoke !== "[" ); if (destruct[destruct.length - 1] === false || (data.stack[a] === "array" && options.formatArray === "inline") || (data.stack[a] === "object" && options.format_object === "inline")) { return; } destruct[destruct.length - 1] = false; do { if (data.types[c] === "end") { d = d + 1; } else if (data.types[c] === "start") { d = d - 1; } if (data.stack[c] === "global") { break; } if (d === 0) { if (data.stack[a] === "class" || data.stack[a] === "map" || (arrayCheck === false && ((listFix === false && data.token[c] !== "(" && data.token[c] !== "x(") || (listFix === true && data.token[c] === ",")))) { if (data.types[c + 1] === "template_start") { if (data.lines[c] < 1) { level[c] = -20; } else { level[c] = indent - 1; } } else if (ei.length > 0 && ei[ei.length - 1] > -1) { level[c] = indent - 1; } else { level[c] = indent; } } else if (data.stack[a] === "array" && data.types[a] === "operator") { if (data.token[c] === ",") { level[c] = indent; } if (c === data.begin[a]) { break; } } if (listFix === false) { break; } } if (d < 0) { if (data.types[c + 1] === "template_start" || data.types[c + 1] === "template_string_start") { if (data.lines[c] < 1) { level[c] = -20; } else { level[c] = indent - 1; } } else if (ei.length > 0 && ei[ei.length - 1] > -1) { level[c] = indent - 1; } else { level[c] = indent; } break; } c = c - 1; } while (c > -1); }, end = function beautify_script_level_end():void { const ei:number[] = (extraindent[extraindent.length - 1] === undefined) ? [] : extraindent[extraindent.length - 1], markupList = function beautify_script_level_end_markupList():void { let aa:number = a, markup:boolean = false; const begin:number = data.begin[aa]; do { aa = aa - 1; if (data.lexer[aa] === "markup") { markup = true; break; } if (data.begin[aa] !== begin) { aa = data.begin[aa]; } } while (aa > begin); if (markup === true) { aa = a; do { aa = aa - 1; if (data.begin[aa] !== begin) { aa = data.begin[aa]; } else if (data.token[aa] === ",") { level[aa] = indent + 1; } } while (aa > begin); level[begin] = indent + 1; level[a - 1] = indent; } else { level[a - 1] = -20; } }; if (ctoke === ")" && data.token[a + 1] === "." && ei[ei.length - 1] > -1 && data.token[ei[0]] !== ":") { let c:number = data.begin[a], d:boolean = false, e:boolean = false; do { c = c - 1; } while (c > 0 && level[c] < -9); d = (level[c] === indent); c = a + 1; do { c = c + 1; if (data.token[c] === "{") { e = true; break; } if (data.begin[c] === data.begin[a + 1] && (data.types[c] === "separator" || data.types[c] === "end")) { break; } } while (c < b); if (d === false && e === true && extraindent.length > 1) { extraindent[extraindent.length - 2].push(data.begin[a]); indent = indent + 1; } } if (ltype !== "separator") { fixchain(); } if (data.token[a + 1] === "," && (data.stack[a] === "object" || data.stack[a] === "array")) { destructfix(true, false); } if ((data.token[a + 1] === "}" || data.token[a + 1] === "]") && (data.stack[a] === "object" || data.stack[a] === "array") && data.token[data.begin[a] - 1] === ",") { destructfix(true, false); } if (data.stack[a] !== "attribute") { if (ctoke !== ")" && ctoke !== "x)" && (data.lexer[a - 1] !== "markup" || (data.lexer[a - 1] === "markup" && data.token[a - 2] !== "return"))) { indent = indent - 1; } if (ctoke === "}" && data.stack[a] === "switch" && options.no_case_indent === false) { indent = indent - 1; } } if (ctoke === "}" || ctoke === "x}") { if ( data.types[a - 1] !== "comment" && ltoke !== "{" && ltoke !== "x{" && ltype !== "end" && ltype !== "string" && ltype !== "number" && ltype !== "separator" && ltoke !== "++" && ltoke !== "--" && (a < 2 || data.token[a - 2] !== ";" || data.token[a - 2] !== "x;" || ltoke === "break" || ltoke === "return") ) { let c:number = a - 1, begin:number = data.begin[a], assign:boolean = false, listlen:number = list.length; do { if (data.begin[c] === begin) { if (data.token[c] === "=" || data.token[c] === ";" || data.token[c] === "x;") { assign = true; } if (data.token[c] === "." && level[c - 1] > -1) { // setting destruct is necessary to prevent a rule below destruct[destruct.length - 1] = false; level[begin] = indent + 1; level[a - 1] = indent; break; } if (c > 0 && data.token[c] === "return" && (data.token[c - 1] === ")" || data.token[c - 1] === "x)" || data.token[c - 1] === "{" || data.token[c - 1] === "x{" || data.token[c - 1] === "}" || data.token[c - 1] === "x}" || data.token[c - 1] === ";" || data.token[c - 1] === "x;")) { indent = indent - 1; level[a - 1] = indent; break; } if ( (data.token[c] === ":" && ternary.length === 0) || (data.token[c] === "," && assign === false) ) { break; } if ((c === 0 || data.token[c - 1] === "{" || data.token[c - 1] === "x{") || data.token[c] === "for" || data.token[c] === "if" || data.token[c] === "do" || data.token[c] === "function" || data.token[c] === "while" || data.token[c] === "var" || data.token[c] === "let" || data.token[c] === "const" || data.token[c] === "with") { if (list[listlen - 1] === false && listlen > 1 && (a === b - 1 || (data.token[a + 1] !== ")" && data.token[a + 1] !== "x)")) && data.stack[a] !== "object") { indent = indent - 1; } break; } } else { c = data.begin[c]; } c = c - 1; } while (c > begin); } varindex.pop(); } if (options.brace_padding === false && ctoke !== "}" && ltype !== "markup") { level[a - 1] = -20; } if (options.brace_padding === true && ltype !== "start" && ltoke !== ";" && (level[data.begin[a]] < -9 || destruct[destruct.length - 1] === true)) { level[data.begin[a]] = -10; level[a - 1] = -10; level.push(-20); } else if (options.language === "qml") { if (ltype === "start" || ctoke === ")" || ctoke === "x)") { level[a - 1] = -20; } else { level[a - 1] = indent; } level.push(indent); } else if (data.stack[a] === "attribute") { level[a - 1] = -20; level.push(indent); } else if (data.stack[a] === "array" && (ei.length > 0 || arrbreak[arrbreak.length - 1] === true)) { endExtraInd(); destruct[destruct.length - 1] = false; level[data.begin[a]] = indent + 1; level[a - 1] = indent; level.push(-20); } else if ((data.stack[a] === "object" || (data.begin[a] === 0 && ctoke === "}")) && ei.length > 0) { endExtraInd(); destruct[destruct.length - 1] = false; level[data.begin[a]] = indent + 1; level[a - 1] = indent; level.push(-20); } else if (ctoke === ")" || ctoke === "x)") { const countx:number = (ctoke === ")" && ltoke !== "(" && count.length > 0) ? count.pop() + 1 : 0, countIf:number = (data.token[data.begin[a] - 1] === "if") ? (function beautify_script_level_end_countIf():number { let bb = a; do { bb = bb - 1; if (data.token[bb] === ")" && level[bb - 1] > -1) { return countx; } } while (bb > data.begin[a]); return countx + 5; }()) : countx; if (countx > 0 && (options.language !== "jsx" || (options.language === "jsx" && data.token[data.begin[a] - 1] !== "render"))) { const wrap:number = options.wrap, begin:number = data.begin[a], len:number = count.length; let aa:number = a - 2; if (countIf > wrap) { level[data.begin[a]] = indent + 1; level[a - 1] = indent; do { if (data.begin[aa] === begin) { if (data.token[aa] === "&&" || data.token[aa] === "||") { level[aa] = indent + 1; } else if (level[aa] > -1 && data.types[aa] !== "comment" && data.token[aa + 1] !== ".") { level[aa] = level[aa] + 1; } } else if (level[aa] > -1 && data.token[aa + 1] !== ".") { level[aa] = level[aa] + 1; } aa = aa - 1; } while (aa > begin); } else if (len > 0) { count[len - 1] = count[len - 1] + countx; } } else if (ctoke === ")" && a > data.begin[a] + 2 && data.lexer[data.begin[a] + 1] === lexer && data.token[data.begin[a] + 1] !== "function") { const open:number = (data.begin[a] < 0) ? 0 : data.begin[a]; let len = 0, aa = 0, short = 0, first = 0, inc = 0, comma = false, array = false, wrap = options.wrap, ind = (indent + 1), exl = ei.length, ready = false, mark = false, tern = false; if (level[open] < -9) { aa = open; do { aa = aa + 1; } while (aa < a && level[aa] < -9); first = aa; do { len = len + data.token[aa].length; if (level[aa] === -10) { len = len + 1; } if (data.token[aa] === "(" && short > 0 && short < wrap - 1 && first === a) { short = -1; } if (data.token[aa] === ")") { inc = inc - 1; } else if (data.token[aa] === "(") { inc = inc + 1; } if (aa === open && inc > 0) { short = len; } aa = aa - 1; } while (aa > open && level[aa] < -9); if (data.token[aa + 1] === ".") { ind = level[aa] + 1; } if (len > wrap - 1 && wrap > 0 && ltoke !== "(" && short !== -1 && destruct[destruct.length - 2] === false) { if ((data.token[open - 1] === "if" && list[list.length - 1] === true) || data.token[open - 1] !== "if") { level[open] = ind; if (data.token[open - 1] === "for") { aa = open; do { aa = aa + 1; if (data.token[aa] === ";" && data.begin[aa] === open) { level[aa] = ind; } } while (aa < a); } } } } aa = a; len = 0; do { aa = aa - 1; if (data.stack[aa] === "function") { aa = data.begin[aa]; } else if (data.begin[aa] === open) { if (data.token[aa] === "?") { tern = true; } else if (data.token[aa] === "," && comma === false) { comma = true; if (len >= wrap && wrap > 0) { ready = true; } } else if (data.types[aa] === "markup" && mark === false) { mark = true; } if (level[aa] > -9 && data.token[aa] !== "," && data.types[aa] !== "markup") { len = 0; } else { if (level[aa] === -10) { len = len + 1; } len = len + data.token[aa].length; if (len >= wrap && wrap > 0 && (comma === true || mark === true)) { ready = true; } } } else { if (level[aa] > -9) { len = 0; } else { len = len + data.token[aa].length; if (len >= wrap && wrap > 0 && (comma === true || mark === true)) { ready = true; } } } } while (aa > open && ready === false); if (comma === false && data.token[data.begin[a] + 1].charAt(0) === "`") { level[data.begin[a]] = -20; level[a - 1] = -20; } else if (((comma === true || mark === true) && len >= wrap && wrap > 0) || level[open] > -9) { if (tern === true) { ind = level[open]; if (data.token[open - 1] === "[") { aa = a; do { aa = aa + 1; if (data.types[aa] === "end" || data.token[aa] === "," || data.token[aa] === ";") { break; } } while (aa < b); if (data.token[aa] === "]") { ind = ind - 1; array = true; } } } else if (exl > 0 && ei[exl - 1] > aa) { ind = ind - exl; } destruct[destruct.length - 1] = false; aa = a; do { aa = aa - 1; if (data.begin[aa] === open) { if (data.token[aa].indexOf("=") > -1 && data.types[aa] === "operator" && data.token[aa].indexOf("!") < 0 && data.token[aa].indexOf("==") < 0 && data.token[aa] !== "<=" && data.token[aa].indexOf(">") < 0) { len = aa; do { len = len - 1; if (data.begin[len] === open && (data.token[len] === ";" || data.token[len] === "," || len === open)) { break; } } while (len > open); } else if (data.token[aa] === ",") { level[aa] = ind; } else if (level[aa] > -9 && array === false && (data.token[open - 1] !== "for" || data.token[aa + 1] === "?" || data.token[aa + 1] === ":") && (data.token[data.begin[a]] !== "(" || data.token[aa] !== "+")) { level[aa] = level[aa] + 1; } } else if (level[aa] > -9 && array === false) { level[aa] = level[aa] + 1; } } while (aa > open); level[open] = ind; level[a - 1] = ind - 1; } else { level[a - 1] = -20; } if (data.token[data.begin[a] - 1] === "+" && level[data.begin[a]] > -9) { level[data.begin[a] - 1] = -10; } } else if (options.language === "jsx") { markupList(); } else { level[a - 1] = -20; } level.push(-20); } else if (destruct[destruct.length - 1] === true) { if (ctoke === "]" && data.begin[a] - 1 > 0 && data.token[data.begin[data.begin[a] - 1]] === "[") { destruct[destruct.length - 2] = false; } if (data.begin[a] < level.length) { level[data.begin[a]] = -20; } if (options.language === "jsx") { markupList(); } else if (ctoke === "]" && level[data.begin[a]] > -1) { level[a - 1] = level[data.begin[a]] - 1; } else { level[a - 1] = -20; } level.push(-20); } else if (data.types[a - 1] === "comment" && data.token[a - 1].substr(0, 2) === "//") { if (data.token[a - 2] === "x}") { level[a - 3] = indent + 1; } level[a - 1] = indent; level.push(-20); } else if (data.types[a - 1] !== "comment" && ((ltoke === "{" && ctoke === "}") || (ltoke === "[" && ctoke === "]"))) { level[a - 1] = -20; if (ctoke === "}" && options.language === "titanium") { level.push(indent); } else { level.push(-20); } } else if (ctoke === "]") { if ((list[list.length - 1] === true && destruct[destruct.length - 1] === false && options.format_array !== "inline") || (ltoke === "]" && level[a - 2] === indent + 1)) { level[a - 1] = indent; level[data.begin[a]] = indent + 1; } else if (level[a - 1] === -10) { level[a - 1] = -20; } if (data.token[data.begin[a] + 1] === "function") { level[a - 1] = indent; } else if (list[list.length - 1] === false) { if (ltoke === "}" || ltoke === "x}") { level[a - 1] = indent; } let c:number = a - 1, d:number = 1; do { if (data.token[c] === "]") { d = d + 1; } if (data.token[c] === "[") { d = d - 1; if (d === 0) { if (c > 0 && (data.token[c + 1] === "{" || data.token[c + 1] === "x{" || data.token[c + 1] === "[")) { level[c] = indent + 1; break; } if (data.token[c + 1] !== "[" || lastlist === false) { level[c] = -20; break; } break; } } if (d === 1 && data.token[c] === "+" && level[c] > 1) { level[c] = level[c] - 1; } c = c - 1; } while (c > -1); } else if (options.language === "jsx") { markupList(); } if (options.format_array === "inline") { let c:number = a, begin:number = data.begin[a]; do { c = c - 1; if (data.types[c] === "end") { break; } } while (c > begin); if (c > begin) { level[data.begin[a]] = indent + 1; level[a - 1] = indent; } else { level[data.begin[a]] = -20; level[a - 1] = -20; } } else if (level[data.begin[a]] > -1) { level[a - 1] = level[data.begin[a]] - 1; } level.push(-20); } else if (ctoke === "}" || ctoke === "x}" || list[list.length - 1] === true) { if (ctoke === "}" && ltoke === "x}" && data.token[a + 1] === "else") { level[a - 2] = indent + 2; level.push(-20); } else { level.push(indent); } level[a - 1] = indent; } else { level.push(-20); } if (data.types[a - 1] === "comment") { level[a - 1] = indent; } endExtraInd(); lastlist = list[list.length - 1]; list.pop(); extraindent.pop(); arrbreak.pop(); itemcount.pop(); wordlist.pop(); destruct.pop(); assignlist.pop(); }, endExtraInd = function beautify_script_level_endExtraInd():void { const ei:number[] = extraindent[extraindent.length - 1]; let c:number = 0; if (ei === undefined) { return; } c = ei.length - 1; if (c < 1 && ei[c] < 0 && (ctoke === ";" || ctoke === "x;" || ctoke === ")" || ctoke === "x)" || ctoke === "}" || ctoke === "x}")) { ei.pop(); return; } if (c < 0 || ei[c] < 0) { return; } if (ctoke === ":") { if (data.token[ei[c]] !== "?") { do { ei.pop(); c = c - 1; indent = indent - 1; } while (c > -1 && ei[c] > -1 && data.token[ei[c]] !== "?"); } ei[c] = a; level[a - 1] = indent; } else { do { ei.pop(); c = c - 1; indent = indent - 1; } while (c > -1 && ei[c] > -1); } if ((data.stack[a] === "array" || ctoke === ",") && ei.length < 1) { ei.push(-1); } }, external = function beautify_script_level_external():void { let skip = a; do { if (data.lexer[a + 1] === lexer && data.begin[a + 1] < skip) { break; } if (data.token[skip - 1] === "return" && data.types[a] === "end" && data.begin[a] === skip) { break; } level.push(0); a = a + 1; } while (a < b); externalIndex[skip] = a; level.push(indent - 1); }, fixchain = function beautify_script_level_fixchain():void { let bb:number = a - 1, cc:number = data.begin[a]; if (indent < 1) { return; } do { if (cc !== data.begin[bb]) { bb = data.begin[bb]; } else { if (data.types[bb] === "separator" || data.types[bb] === "operator") { if (data.token[bb] === "." && level[bb - 1] > 0) { if (data.token[cc - 1] === "if") { indent = indent - 2; } else { indent = indent - 1; } } break; } } bb = bb - 1; } while (bb > 0 && bb > cc); }, markup = function beautify_script_level_markup():void { if ((data.token[a + 1] !== "," && ctoke.indexOf("/>") !== ctoke.length - 2) || (data.token[a + 1] === "," && data.token[data.begin[a] - 3] !== "React")) { destructfix(false, false); } if (ltoke === "return" || ltoke === "?" || ltoke === ":") { level[a - 1] = -10; level.push(-20); } else if (ltype === "start" || (data.token[a - 2] === "return" && data.stack[a - 1] === "method")) { level.push(indent); } else { level.push(-20); } }, operator = function beautify_script_level_operator():void { const ei:number[] = (extraindent[extraindent.length - 1] === undefined) ? [] : extraindent[extraindent.length - 1], opWrap = function beautify_script_level_operator_opWrap():void { const aa:string = data.token[a + 1]; let line:number = 0, next:number = 0, c:number = a, ind:number = (ctoke === "+") ? indent + 2 : indent, meth:number = 0; if (options.wrap < 1) { level.push(-10); return; } do { c = c - 1; if (data.token[data.begin[a]] === "(") { if (c === data.begin[a]) { meth = line; } if (data.token[c] === "," && data.begin[c] === data.begin[a] && list[list.length - 1] === true) { break; } } if (line > options.wrap - 1) { break; } if (level[c] > -9) { break; } if (data.types[c] === "operator" && data.token[c] !== "=" && data.token[c] !== "+" && data.begin[c] === data.begin[a]) { break; } line = line + data.token[c].length; if (c === data.begin[a] && data.token[c] === "[" && line < options.wrap - 1) { break; } if (data.token[c] === "." && level[c] > -9) { break; } if (level[c] === -10) { line = line + 1; } } while (c > 0); if (meth > 0) { meth = meth + aa.length; } line = line + aa.length; next = c; if (line > options.wrap - 1 && level[c] < -9) { do { next = next - 1; } while (next > 0 && level[next] < -9); } if (data.token[next + 1] === "." && data.begin[a] <= data.begin[next]) { ind = ind + 1; } else if (data.types[next] === "operator") { ind = level[next]; } next = aa.length; if (line + next < options.wrap) { level.push(-10); return; } if (data.token[data.begin[a]] === "(" && (data.token[ei[0]] === ":" || data.token[ei[0]] === "?")) { ind = indent + 3; } else if (data.stack[a] === "method") { level[data.begin[a]] = indent; if (list[list.length - 1] === true) { ind = indent + 3; } else { ind = indent + 1; } } else if (data.stack[a] === "object" || data.stack[a] === "array") { destructfix(true, false); } if (data.token[c] === "var" || data.token[c] === "let" || data.token[c] === "const") { line = line - (options.indent_size * options.indent_char.length * 2); } if (meth > 0) { c = options.wrap - meth; } else { c = options.wrap - line; } if (c > 0 && c < 5) { level.push(ind); if (data.token[a].charAt(0) === "\"" || data.token[a].charAt(0) === "'") { a = a + 1; level.push(-10); } return; } if (data.token[data.begin[a]] !== "(" || meth > options.wrap - 1 || meth === 0) { if (meth > 0) { line = meth; } if (line - aa.length < options.wrap - 1 && (aa.charAt(0) === "\"" || aa.charAt(0) === "'")) { a = a + 1; line = line + 3; if (line - aa.length > options.wrap - 4) { level.push(ind); return; } level.push(-10); return; } level.push(ind); return; } level.push(-10); }; fixchain(); if (ei.length > 0 && ei[ei.length - 1] > -1 && data.stack[a] === "array") { arrbreak[arrbreak.length - 1] = true; } if (ctoke !== ":") { if (data.token[data.begin[a]] !== "(" && data.token[data.begin[a]] !== "x(" && destruct.length > 0) { destructfix(true, false); } if (ctoke !== "?" && data.token[ei[ei.length - 1]] === ".") { let c:number = a, d:number = data.begin[c], e:number = 0; do { if (data.begin[c] === d) { if (data.token[c + 1] === "{" || data.token[c + 1] === "[" || data.token[c] === "function") { break; } if (data.token[c] === "," || data.token[c] === ";" || data.types[c] === "end" || data.token[c] === ":") { ei.pop(); indent = indent - 1; break; } if (data.token[c] === "?" || data.token[c] === ":") { if (data.token[ei[ei.length - 1]] === "." && e < 2) { ei[ei.length - 1] = d + 1; } break; } if (data.token[c] === ".") { e = e + 1; } } c = c + 1; } while (c < b); } } if (ctoke === "!" || ctoke === "...") { if (ltoke === "}" || ltoke === "x}") { level[a - 1] = indent; } level.push(-20); return; } if (ltoke === ";" || ltoke === "x;") { if (data.token[data.begin[a] - 1] !== "for") { level[a - 1] = indent; } level.push(-20); return; } if (ctoke === "*") { if (ltoke === "function" || ltoke === "yield") { level[a - 1] = -20; } else { level[a - 1] = -10; } level.push(-10); return; } if (ctoke === "?") { if (data.lines[a] === 0 && data.types[a - 2] === "word" && data.token[a - 2] !== "return" && data.token[a - 2] !== "in" && data.token[a - 2] !== "instanceof" && data.token[a - 2] !== "typeof" && (ltype === "reference" || ltype === "word")) { if (data.types[a + 1] === "word" || data.types[a + 1] === "reference" || ((data.token[a + 1] === "(" || data.token[a + 1] === "x(") && data.token[a - 2] === "new")) { level[a - 1] = -20; if (data.types[a + 1] === "word" || data.types[a + 1] === "reference") { level.push(-10); return; } level.push(-20); return; } } if (data.token[a + 1] === ":") { level[a - 1] = -20; level.push(-20); return; } ternary.push(a); if (options.ternary_line === true) { level[a - 1] = -10; } else { let c = a - 1; do { c = c - 1; } while (c > -1 && level[c] < -9); ei.push(a); indent = indent + 1; if (level[c] === indent && data.token[c + 1] !== ":") { indent = indent + 1; ei.push(a); } level[a - 1] = indent; if (data.token[data.begin[a]] === "(" && (ei.length < 2 || ei[0] === ei[1])) { destruct[destruct.length - 1] = false; if (a - 2 === data.begin[a]) { level[data.begin[a]] = indent - 1; } else { level[data.begin[a]] = indent; } c = a - 2; do { if (data.types[c] === "end" && level[c - 1] > -1) { break; } if (level[c] > -1) { level[c] = level[c] + 1; } c = c - 1; } while (c > data.begin[a]); } } level.push(-10); return; } if (ctoke === ":") { if (data.stack[a] === "map" || data.types[a + 1] === "type" || data.types[a + 1] === "type_start") { level[a - 1] = -20; level.push(-10); return; } if (ternary.length > 0 && data.begin[ternary[ternary.length - 1]] === data.begin[a]) { let c:number = a, d:number = data.begin[a]; do { c = c - 1; if (data.begin[c] === d) { if (data.token[c] === "," || data.token[c] === ";") { level[a - 1] = -20; break; } if (data.token[c] === "?") { ternary.pop(); endExtraInd(); if (options.ternary_line === true) { level[a - 1] = -10; } level.push(-10); return; } } else if (data.types[c] === "end") { c = data.begin[c]; } } while (c > d); } if (data.token[a - 2] === "where" && data.stack[a - 2] === data.stack[a]) { level[a - 1] = -10; level.push(-10); return; } if (ltype === "reference" && data.token[data.begin[a]] !== "(" && data.token[data.begin[a]] !== "x(") { level[a - 1] = -20; level.push(-10); return; } if ((ltoke === ")" || ltoke === "x)") && data.token[data.begin[a - 1] - 2] === "function") { level[a - 1] = -20; level.push(-10); return; } if (data.stack[a] === "attribute") { level[a - 1] = -20; level.push(-10); return; } if ( data.token[data.begin[a]] !== "(" && data.token[data.begin[a]] !== "x(" && (ltype === "reference" || ltoke === ")" || ltoke === "]" || ltoke === "?") && (data.stack[a] === "map" || data.stack[a] === "class" || data.types[a + 1] === "reference") && (ternary.length === 0 || ternary[ternary.length - 1] < data.begin[a]) && ("mapclassexpressionmethodglobalparen".indexOf(data.stack[a]) > -1 || (data.types[a - 2] === "word" && data.stack[a] !== "switch")) ) { level[a - 1] = -20; level.push(-10); return; } if (data.stack[a] === "switch" && (ternary.length < 1 || ternary[ternary.length - 1] < data.begin[a])) { level[a - 1] = -20; if (options.case_space === true) { level.push(-10); } else { level.push(indent); } return; } if (data.stack[a] === "object") { level[a - 1] = -20; } else if (ternary.length > 0) { level[a - 1] = indent; } else { level[a - 1] = -10; } level.push(-10); return; } if (ctoke === "++" || ctoke === "--") { if (ltype === "number" || ltype === "reference") { level[a - 1] = -20; level.push(-10); } else if (a < b - 1 && (data.types[a + 1] === "number" || data.types[a + 1] === "reference")) { level.push(-20); } else { level.push(-10); } return; } if (ctoke === "+") { if (ltype === "start") { level[a - 1] = -20; } else { level[a - 1] = -10; } if (options.wrap < 1 || data.token[data.begin[a]] === "x(") { level.push(-10); return; } let aa:string = data.token[a + 1]; if (aa === undefined) { level.push(-10); return; } if (data.types[a - 1] === "operator" || data.types[a - 1] === "start") { if (data.types[a + 1] === "reference" || aa === "(" || aa === "[") { level.push(-20); return; } if (Number(aa.slice(1, -1)) > -1 && ((/\d/).test(aa.charAt(1)) === true || aa.charAt(1) === "." || aa.charAt(1) === "-" || aa.charAt(1) === "+")) { level.push(-20); return; } } return opWrap(); } if (data.types[a - 1] !== "comment") { if (ltoke === "(") { level[a - 1] = -20; } else if (ctoke === "*" && data.stack[a] === "object" && data.types[a + 1] === "reference" && (ltoke === "{" || ltoke === ",")) { level[a - 1] = indent; } else if (ctoke !== "?" || ternary.length === 0) { level[a - 1] = -10; } } if (ctoke.indexOf("=") > -1 && ctoke !== "==" && ctoke !== "===" && ctoke !== "!=" && ctoke !== "!==" && ctoke !== ">=" && ctoke !== "<=" && ctoke !== "=>" && data.stack[a] !== "method" && data.stack[a] !== "object") { let c:number = a + 1, d:number = 0, e:boolean = false, f:string = ""; if ((data.token[data.begin[a]] === "(" || data.token[data.begin[a]] === "x(") && data.token[a + 1] !== "function") { return; } do { if (data.types[c] === "start") { if (e === true && data.token[c] !== "[") { if (assignlist[assignlist.length - 1] === true) { assignlist[assignlist.length - 1] = false; } break; } d = d + 1; } if (data.types[c] === "end") { d = d - 1; } if (d < 0) { if (assignlist[assignlist.length - 1] === true) { assignlist[assignlist.length - 1] = false; } break; } if (d === 0) { f = data.token[c]; if (e === true) { if (data.types[c] === "operator" || data.token[c] === ";" || data.token[c] === "x;" || data.token[c] === "?" || data.token[c] === "var" || data.token[c] === "let" || data.token[c] === "const") { if (f !== undefined && (f === "?" || (f.indexOf("=") > -1 && f !== "==" && f !== "===" && f !== "!=" && f !== "!==" && f !== ">=" && f !== "<="))) { if (assignlist[assignlist.length - 1] === false) { assignlist[assignlist.length - 1] = true; } } if ((f === ";" || f === "x;" || f === "var" || f === "let" || f === "const") && assignlist[assignlist.length - 1] === true) { assignlist[assignlist.length - 1] = false; } break; } if (assignlist[assignlist.length - 1] === true && (f === "return" || f === "break" || f === "continue" || f === "throw")) { assignlist[assignlist.length - 1] = false; } } if (f === ";" || f === "x;" || f === ",") { e = true; } } c = c + 1; } while (c < b); level.push(-10); return; } if ((ctoke === "-" && ltoke === "return") || ltoke === "=") { level.push(-20); return; } if (ltype === "operator" && data.types[a + 1] === "reference" && ltoke !== "--" && ltoke !== "++" && ctoke !== "&&" && ctoke !== "||") { level.push(-20); return; } return opWrap(); }, reference = function beautify_script_level_reference():void { const hoist = function beautify_script_level_reference_hoist():void { let func:number = data.begin[a]; if (func < 0) { scopes.push([data.token[a], -1]); } else { if (data.stack[func + 1] !== "function") { do { func = data.begin[func]; } while (func > -1 && data.stack[func + 1] !== "function"); } scopes.push([data.token[a], func]); } }; if (data.types[a - 1] === "comment") { level[a - 1] = indent; } else if (ltype === "end" && ltoke !== ")" && data.token[data.begin[a - 1] - 1] !== ")") { level[a - 1] = -10; } else if (ltype !== "separator" && ltype !== "start" && ltype !== "end" && ltype.indexOf("template_string") < 0) { if (ltype === "word" || ltype === "operator" || ltype === "property" || ltype === "type" || ltype === "reference") { level[a - 1] = -10; } else { level[a - 1] = -20; } } if (ltoke === "var" && data.lexer[a - 1] === lexer) { // hoisted references following declaration keyword hoist(); } else if (ltoke === "function") { scopes.push([data.token[a], a]); } else if (ltoke === "let" || ltoke === "const") { // not hoisted references following declaration keyword scopes.push([data.token[a], a]); } else if (data.stack[a] === "arguments") { scopes.push([data.token[a], a]); } else if (ltoke === ",") { // references following a comma, must be tested to see if a declaration list let index:number = a; do { index = index - 1; } while (index > data.begin[a] && data.token[index] !== "var" && data.token[index] !== "let" && data.token[index] !== "const"); if (data.token[index] === "var") { hoist(); } else if (data.token[index] === "let" || data.token[index] === "const") { scopes.push([data.token[a], a]); } } level.push(-10); }, separator = function beautify_script_level_separator():void { const ei:number[] = (extraindent[extraindent.length - 1] === undefined) ? [] : extraindent[extraindent.length - 1], propertybreak = function beautify_script_level_separator_propertybreak():void { if (options.method_chain > 0) { let x:number = a, y:number = data.begin[a], z:number[] = [a], ify:boolean = (data.token[y - 1] === "if"); do { x = x - 1; if (data.types[x] === "end") { x = data.begin[x]; } if (data.begin[x] === y) { if (data.types[x] === "string" && data.token[x].indexOf("${") === data.token[x].length - 2) { break; } if (data.token[x] === ".") { if (level[x - 1] > 0) { level[a - 1] = (ify === true) ? indent + 1 : indent; return; } z.push(x); } else if ( data.token[x] === ";" || data.token[x] === "," || data.types[x] === "operator" || ( (data.types[x] === "word" || data.types[x] === "reference") && (data.types[x - 1] === "word" || data.types[x - 1] === "reference") ) ) { break; } } } while (x > y); if (z.length < options.method_chain) { level[a - 1] = -20; return; } x = 0; y = z.length; do { level[z[x] - 1] = (ify === true) ? indent + 1 : indent; x = x + 1; } while (x < y); x = z[z.length - 1] - 1; do { if (level[x] > -1) { level[x] = level[x] + 1; } x = x + 1; } while (x < a); indent = (ify === true) ? indent + 2 : indent + 1; } level[a - 1] = indent; }; if (ctoke === "::") { level[a - 1] = -20; level.push(-20); return; } if (ctoke === ".") { if (data.token[data.begin[a]] !== "(" && data.token[data.begin[a]] !== "x(" && ei.length > 0) { if (data.stack[a] === "object" || data.stack[a] === "array") { destructfix(true, false); } else { destructfix(false, false); } } if (options.method_chain === 0) { // methodchain is 0 so methods and properties should be chained together level[a - 1] = -20; } else if (options.method_chain < 0) { if (data.lines[a] > 0) { propertybreak(); } else { level[a - 1] = -20; } } else { // methodchain is greater than 0 and should break methods if the chain reaches this value propertybreak(); } level.push(-20); return; } if (ctoke === ",") { fixchain(); if (list[list.length - 1] === false && (data.stack[a] === "object" || data.stack[a] === "array" || data.stack[a] === "paren" || data.stack[a] === "expression" || data.stack[a] === "method")) { list[list.length - 1] = true; if (data.token[data.begin[a]] === "(") { let aa:number = a; do { aa = aa - 1; if (data.begin[aa] === data.begin[a] && data.token[aa] === "+" && level[aa] > -9) { level[aa] = level[aa] + 2; } } while (aa > data.begin[a]); } } if (data.stack[a] === "array" && options.format_array === "indent") { level[a - 1] = -20; level.push(indent); return; } if (data.stack[a] === "array" && options.format_array === "inline") { level[a - 1] = -20; level.push(-10); return; } if (data.stack[a] === "object" && options.format_object === "indent") { level[a - 1] = -20; level.push(indent); return; } if (data.stack[a] === "object" && options.format_object === "inline") { level[a - 1] = -20; level.push(-10); return; } if (ei.length > 0) { if (ei[ei.length - 1] > -1) { endExtraInd(); } level[a - 1] = -20; level.push(indent); return; } if (data.token[a - 2] === ":" && data.token[a - 4] === "where") { level[a - 1] = -20; level.push(-10); return; } level[a - 1] = -20; if (data.types[a + 1] !== "end") { itemcount[itemcount.length - 1] = itemcount[itemcount.length - 1] + 1; } if ((data.token[data.begin[a]] === "(" || data.token[data.begin[a]] === "x(") && options.language !== "jsx" && data.stack[a] !== "global" && ((data.types[a - 1] !== "string" && data.types[a - 1] !== "number") || data.token[a - 2] !== "+" || (data.types[a - 1] === "string" && data.types[a - 1] !== "number" && data.token[a - 2] === "+" && data.types[a - 3] !== "string" && data.types[a - 3] !== "number"))) { level.push(-10); return; } if (ltype === "reference" && data.types[a - 2] === "word" && "var-let-const-from".indexOf(data.token[a - 2]) < 0 && (data.types[a - 3] === "end" || data.token[a - 3] === ";")) { wordlist[wordlist.length - 1] = true; level.push(-10); return; } if (wordlist[wordlist.length - 1] === true || data.stack[a] === "notation") { level.push(-10); return; } if (itemcount[itemcount.length - 1] > 3 && (data.stack[a] === "array" || data.stack[a] === "object")) { if (destruct[destruct.length - 1] === true) { destructfix(true, true); } level[a - 1] = -20; if (arrbreak[arrbreak.length - 1] === true) { level.push(indent); return; } let begin:number = data.begin[a], c:number = a; do { if (data.types[c] === "end") { c = data.begin[c]; } else { if (data.token[c] === "," && data.types[c + 1] !== "comment") { level[c] = indent; } } c = c - 1; } while (c > begin); level[begin] = indent; arrbreak[arrbreak.length - 1] = true; return; } if (data.stack[a] === "object") { if (destruct[destruct.length - 1] === true && data.types[data.begin[a] - 1] !== "word" && data.types[data.begin[a] - 1] !== "reference" && data.token[data.begin[a] - 1] !== "(" && data.token[data.begin[a] - 1] !== "x(") { const bb:number = data.begin[a]; let aa:number = a - 1; do { if (data.begin[aa] === bb) { if (data.token[aa] === ",") { break; } if (data.token[aa] === ":") { destructfix(true, false); break; } } aa = aa - 1; } while (aa > bb); } } if ((data.types[a - 1] === "word" || data.types[a - 1] === "reference") && data.token[a - 2] === "for") { //This is for Volt templates level.push(-10); return; } if (destruct[destruct.length - 1] === false || (data.token[a - 2] === "+" && (ltype === "string" || ltype === "number") && level[a - 2] > 0 && (ltoke.charAt(0) === "\"" || ltoke.charAt(0) === "'"))) { if (data.stack[a] === "method") { if (data.token[a - 2] === "+" && (ltoke.charAt(0) === "\"" || ltoke.charAt(0) === "'") && (data.token[a - 3].charAt(0) === "\"" || data.token[a - 3].charAt(0) === "'")) { level.push(indent + 2); return; } if (data.token[a - 2] !== "+") { level.push(-10); return; } } level.push(indent); return; } if (destruct[destruct.length - 1] === true && data.stack[a] !== "object") { level.push(-10); return; } if (itemcount[itemcount.length - 1] < 4 && (data.stack[a] === "array" || data.stack[a] === "object")) { level.push(-10); return; } level.push(indent); return; } if (ctoke === ";" || ctoke === "x;") { fixchain(); if (data.token[a + 1] !== undefined && data.types[a + 1].indexOf("attribute") > 0 && data.types[a + 1].indexOf("end") > 0) { level[a - 1] = -20; level.push(indent - 1); return; } if (varindex[varindex.length - 1] > -1 && data.stack[varindex[varindex.length - 1]] !== "expression") { let aa:number = a; do { aa = aa - 1; if (data.token[aa] === ";") { break; } if (data.token[aa] === ",") { indent = indent - 1; break; } if (data.types[aa] === "end") { aa = data.begin[aa]; } } while (aa > 0 && aa > data.begin[a]); } varindex[varindex.length - 1] = -1; endExtraInd(); if (data.token[data.begin[a] - 1] !== "for") { destructfix(false, false); } if (ctoke === "x;") { scolon = scolon + 1; } wordlist[wordlist.length - 1] = false; level[a - 1] = -20; if (data.begin[a] > 0 && data.token[data.begin[a] - 1] === "for" && data.stack[a] !== "for") { level.push(-10); return; } level.push(indent); return; } level.push(-20); }, start = function beautify_script_level_start():void { const deep:string = data.stack[a + 1], deeper:string = (a === 0) ? data.stack[a] : data.stack[a - 1]; if (ltoke === ")" || ((deeper === "object" || deeper === "array") && ltoke !== "]")) { if (deep !== "method" || (deep === "method" && data.token[a + 1] !== ")" && data.token[a + 2] !== ")")) { if (ltoke === ")" && (deep !== "function" || data.token[data.begin[data.begin[a - 1] - 1]] === "(" || data.token[data.begin[data.begin[a - 1] - 1]] === "x(")) { destructfix(false, false); } else if (data.types[a + 1] !== "end" && data.types[a + 2] !== "end") { destructfix(true, false); } } } list.push(false); extraindent.push([]); assignlist.push(false); arrbreak.push(false); wordlist.push(false); itemcount.push(0); if (options.never_flatten === true || (deep === "array" && options.format_array === "indent") || options.language === "qml" || deep === "attribute" || ltype === "generic" || (deep === "class" && ltoke !== "(" && ltoke !== "x(") || (ctoke === "[" && data.token[a + 1] === "function")) { destruct.push(false); } else { if (deep === "expression" || deep === "method") { destruct.push(true); } else if ((deep === "object" || deep === "class") && (ltoke === "(" || ltoke === "x(" || ltype === "word" || ltype === "reference")) { //array or object literal following `return` or `(` destruct.push(true); } else if (deep === "array" || ctoke === "(" || ctoke === "x(") { //array, method, paren destruct.push(true); } else if (ctoke === "{" && deep === "object" && ltype !== "operator" && ltype !== "start" && ltype !== "string" && ltype !== "number" && deeper !== "object" && deeper !== "array" && a > 0) { //curly brace not in a list and not assigned destruct.push(true); } else { //not destructured (multiline) destruct.push(false); } } if (ctoke !== "(" && ctoke !== "x(" && data.stack[a + 1] !== "attribute") { indent = indent + 1; } if (ctoke === "{" || ctoke === "x{") { varindex.push(-1); if (data.types[a - 1] !== "comment") { if (ltype === "markup") { level[a - 1] = indent; } else if (options.braces === true && ltype !== "operator" && ltoke !== "return") { level[a - 1] = indent - 1; } else if (data.stack[a + 1] !== "block" && (deep === "function" || ltoke === ")" || ltoke === "x)" || ltoke === "," || ltoke === "}" || ltype === "markup")) { level[a - 1] = -10; } else if (ltoke === "{" || ltoke === "x{" || ltoke === "[" || ltoke === "}" || ltoke === "x}") { level[a - 1] = indent - 1; } } if (deep === "object") { if (options.format_object === "indent") { destruct[destruct.length - 1] = false; level.push(indent); return; } if (options.format_object === "inline") { destruct[destruct.length - 1] = true; level.push(-20); return; } } if (deep === "switch") { if (options.no_case_indent === true) { level.push(indent - 1); return; } indent = indent + 1; level.push(indent); return; } if (destruct[destruct.length - 1] === true) { if (ltype !== "word" && ltype !== "reference") { level.push(-20); return; } } level.push(indent); return; } if (ctoke === "(" || ctoke === "x(") { if (options.wrap > 0 && ctoke === "(" && data.token[a + 1] !== ")") { count.push(1); } if (ltoke === "-" && (data.token[a - 2] === "(" || data.token[a - 2] === "x(")) { level[a - 2] = -20; } if (ltype === "end" && deeper !== "if" && deeper !== "for" && deeper !== "catch" && deeper !== "else" && deeper !== "do" && deeper !== "try" && deeper !== "finally" && deeper !== "catch") { if (data.types[a - 1] === "comment") { level[a - 1] = indent; } else { level[a - 1] = -20; } } if (ltoke === "async") { level[a - 1] = -10; } else if (deep === "method" || (data.token[a - 2] === "function" && ltype === "reference")) { if (ltoke === "import" || ltoke === "in" || options.function_name === true) { level[a - 1] = -10; } else if ((ltoke === "}" && data.stack[a - 1] === "function") || ltype === "word" || ltype === "reference" || ltype === "property") { level[a - 1] = -20; } else if (deeper !== "method" && deep !== "method") { level[a - 1] = indent; } } if (ltoke === "+" && (data.token[a - 2].charAt(0) === "\"" || data.token[a - 2].charAt(0) === "'")) { level.push(indent); return; } if (ltoke === "}" || ltoke === "x}") { level.push(-20); return; } if ((ltoke === "-" && (a < 2 || (data.token[a - 2] !== ")" && data.token[a - 2] !== "x)" && data.token[a - 2] !== "]" && data.types[a - 2] !== "reference" && data.types[a - 2] !== "string" && data.types[a - 2] !== "number"))) || (options.space === false && ltoke === "function")) { level[a - 1] = -20; } level.push(-20); return; } if (ctoke === "[") { if (ltoke === "[") { list[list.length - 2] = true; } if (ltoke === "return" || ltoke === "var" || ltoke === "let" || ltoke === "const") { level[a - 1] = -10; } else if (data.types[a - 1] !== "comment" && data.stack[a - 1] !== "attribute" && (ltype === "end" || ltype === "word" || ltype === "reference")) { level[a - 1] = -20; } else if (ltoke === "[" || ltoke === "{" || ltoke === "x{") { level[a - 1] = indent - 1; } if (data.stack[a] === "attribute") { level.push(-20); return; } if (options.format_array === "indent") { destruct[destruct.length - 1] = false; level.push(indent); return; } if (options.format_array === "inline") { destruct[destruct.length - 1] = true; level.push(-20); return; } if (deep === "method" || destruct[destruct.length - 1] === true) { level.push(-20); return; } let c:number = a + 1; do { if (data.token[c] === "]") { level.push(-20); return; } if (data.token[c] === ",") { level.push(indent); return; } c = c + 1; } while (c < b); level.push(-20); return; } }, string = function beautify_script_level_string():void { if (ctoke.length === 1) { level.push(-20); if (data.lines[a] === 0) { level[a - 1] = -20; } } else if (ctoke.indexOf("#!/") === 0) { level.push(indent); } else { level.push(-10); } if ((ltoke === "," || ltype === "start") && (data.stack[a] === "object" || data.stack[a] === "array") && destruct[destruct.length - 1] === false && a > 0) { level[a - 1] = indent; } }, template = function beautify_script_level_template():void { if (ctype === "template_else") { level[a - 1] = indent - 1; level.push(indent); } else if (ctype === "template_start") { indent = indent + 1; if (data.lines[a - 1] < 1) { level[a - 1] = -20; } if (data.lines[a] > 0 || ltoke.length === 1 && ltype === "string") { level.push(indent); } else { level.push(-20); } } else if (ctype === "template_end") { indent = indent - 1; if (ltype === "template_start" || data.lines[a - 1] < 1) { level[a - 1] = -20; } else { level[a - 1] = indent; } if (data.lines[a] > 0) { level.push(indent); } else { level.push(-20); } } else if (ctype === "template") { if (data.lines[a] > 0) { level.push(indent); } else { level.push(-20); } } }, templateString = function beautify_script_level_templateString():void { if (ctype === "template_string_start") { indent = indent + 1; level.push(indent); } else if (ctype === "template_string_else") { fixchain(); level[a - 1] = indent - 1; level.push(indent); } else { fixchain(); indent = indent - 1; level[a - 1] = indent; level.push(-10); } if (a > 2 && (data.types[a - 2] === "template_string_else" || data.types[a - 2] === "template_string_start")) { if (options.brace_padding === true) { level[a - 2] = -10; level[a - 1] = -10; } else { level[a - 2] = -20; level[a - 1] = -20; } } }, types = function beautify_script_level_types():void { if (data.token[a - 1] === "," || (data.token[a - 1] === ":" && data.stack[a - 1] !== "data_type")) { level[a - 1] = -10; } else { level[a - 1] = -20; } if (data.types[a] === "type" || data.types[a] === "type_end") { level.push(-10); } if (data.types[a] === "type_start") { level.push(-20); } }, word = function beautify_script_level_word():void { if ((ltoke === ")" || ltoke === "x)") && data.stack[a] === "class" && (data.token[data.begin[a - 1] - 1] === "static" || data.token[data.begin[a - 1] - 1] === "final" || data.token[data.begin[a - 1] - 1] === "void")) { level[a - 1] = -10; level[data.begin[a - 1] - 1] = -10; } if (ltoke === "]") { level[a - 1] = -10; } if (ltoke === "}" || ltoke === "x}") { level[a - 1] = indent; } if (ctoke === "else" && ltoke === "}") { if (data.token[a - 2] === "x}") { level[a - 3] = level[a - 3] - 1; } if (options.braces === true) { level[a - 1] = indent; } } if (ctoke === "new") { let apiword:string[] = [ "ActiveXObject", "ArrayBuffer", "AudioContext", "Canvas", "CustomAnimation", "DOMParser", "DataView", "Date", "Error", "EvalError", "FadeAnimation", "FileReader", "Flash", "Float32Array", "Float64Array", "FormField", "Frame", "Generator", "HotKey", "Image", "Iterator", "Intl", "Int16Array", "Int32Array", "Int8Array", "InternalError", "Loader", "Map", "MenuItem", "MoveAnimation", "Notification", "ParallelArray", "Point", "Promise", "Proxy", "RangeError", "Rectangle", "ReferenceError", "Reflect", "RegExp", "ResizeAnimation", "RotateAnimation", "Set", "SQLite", "ScrollBar", "Set", "Shadow", "StopIteration", "Symbol", "SyntaxError", "Text", "TextArea", "Timer", "TypeError", "URL", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray", "URIError", "WeakMap", "WeakSet", "Web", "Window", "XMLHttpRequest" ]; if (apiword.indexOf(data.token[a + 1]) < 0) { news = news + 1; } if (options.jsscope !== "none") { data.token[a] = "<strong class='new'>new</strong>"; } } if (ctoke === "from" && ltype === "end" && a > 0 && (data.token[data.begin[a - 1] - 1] === "import" || data.token[data.begin[a - 1] - 1] === ",")) { level[a - 1] = -10; } if (ctoke === "this" && options.jsscope !== "none") { data.token[a] = "<strong class=\"new\">this</strong>"; } if (ctoke === "function") { if (options.space === false && a < b - 1 && (data.token[a + 1] === "(" || data.token[a + 1] === "x(")) { level.push(-20); return; } level.push(-10); return; } if (ltoke === "-" && a > 1) { if (data.types[a - 2] === "operator" || data.token[a - 2] === ",") { level[a - 1] = -20; } else if (data.types[a - 2] === "start") { level[a - 2] = -20; level[a - 1] = -20; } } else if (ctoke === "while" && (ltoke === "}" || ltoke === "x}")) { //verify if this is a do/while block let c = a - 1, d = 0; do { if (data.token[c] === "}" || data.token[c] === "x}") { d = d + 1; } if (data.token[c] === "{" || data.token[c] === "x{") { d = d - 1; } if (d === 0) { if (data.token[c - 1] === "do") { level[a - 1] = -10; break; } level[a - 1] = indent; break; } c = c - 1; } while (c > -1); } else if (ctoke === "in" || (((ctoke === "else" && options.else_line === false && options.braces === false) || ctoke === "catch") && (ltoke === "}" || ltoke === "x}"))) { level[a - 1] = -10; } else if (ctoke === "var" || ctoke === "let" || ctoke === "const") { varindex[varindex.length - 1] = a; if (ltype === "end") { level[a - 1] = indent; } if (data.token[data.begin[a] - 1] !== "for") { let c:number = a + 1, d:number = 0; do { if (data.types[c] === "end") { d = d - 1; } if (data.types[c] === "start") { d = d + 1; } if (d < 0 || (d === 0 && (data.token[c] === ";" || data.token[c] === ","))) { break; } c = c + 1; } while (c < b); if (data.token[c] === ",") { indent = indent + 1; } } level.push(-10); return; } if ((ctoke === "default" || ctoke === "case") && ltype !== "word" && data.stack[a] === "switch") { level[a - 1] = indent - 1; level.push(-10); return; } if (ctoke === "catch" && ltoke === ".") { level[a - 1] = -20; level.push(-20); return; } if (ctoke === "catch" || ctoke === "finally") { level[a - 1] = -10; level.push(-10); return; } if (options.brace_padding === false && a < b - 1 && data.token[a + 1].charAt(0) === "}") { level.push(-20); return; } if (data.stack[a] === "object" && (ltoke === "{" || ltoke === ",") && (data.token[a + 1] === "(" || data.token[a + 1] === "x(")) { level.push(-20); return; } if (data.types[a - 1] === "comment" && data.token[data.begin[a]] === "(") { level[a - 1] = indent + 1; } level.push(-10); }; if (options.language === "titanium") { indent = indent - 1; } do { if (data.lexer[a] === lexer) { ctype = data.types[a]; ctoke = data.token[a]; if (ctype === "comment") { comment(); } else if (ctype === "regex") { level.push(-20); } else if (ctype === "string") { string(); } else if (ctype.indexOf("template_string") === 0) { templateString(); } else if (ctype === "separator") { separator(); } else if (ctype === "start") { start(); } else if (ctype === "end") { end(); } else if (ctype === "type" || ctype === "type_start" || ctype === "type_end") { types(); } else if (ctype === "operator") { operator(); } else if (ctype === "word") { word(); } else if (ctype === "reference") { reference(); } else if (ctype === "markup") { markup(); } else if (ctype.indexOf("template") === 0) { template(); } else if (ctype === "generic") { if (ltoke !== "return" && ltoke.charAt(0) !== "#" && ltype !== "operator" && ltoke !== "public" && ltoke !== "private" && ltoke !== "static" && ltoke !== "final" && ltoke !== "implements" && ltoke !== "class" && ltoke !== "void") { level[a - 1] = -20; } if (data.token[a + 1] === "(" || data.token[a + 1] === "x(") { level.push(-20); } else { level.push(-10); } } else { level.push(-10); } if (ctype !== "comment") { ltype = ctype; ltoke = ctoke; } if (count.length > 0 && data.token[a] !== ")") { if (data.types[a] === "comment" && count[count.length - 1] > -1) { count[count.length - 1] = options.wrap + 1; } else if (level[a] > -1 || (data.token[a].charAt(0) === "`" && data.token[a].indexOf("\n") > 0)) { count[count.length - 1] = -1; } else if (count[count.length - 1] > -1) { count[count.length - 1] = count[count.length - 1] + data.token[a].length; if (level[a] === -10) { count[count.length - 1] = count[count.length - 1] + 1; } } } } else { external(); } a = a + 1; } while (a < b); return level; }()), output:string = (function beautify_script_output():string { const build:string[] = [], tab:string = (function beautify_script_output_tab():string { const ch:string = options.indent_char, tabby:string[] = []; let index:number = options.indent_size; if (typeof index !== "number" || index < 1) { return ""; } do { tabby.push(ch); index = index - 1; } while (index > 0); return tabby.join(""); }()), lf:"\r\n"|"\n" = (options.crlf === true) ? "\r\n" : "\n", pres:number = options.preserve + 1, nl = function beautify_script_output_outnl(tabs:number):string { const linesout:string[] = [], total:number = (function beautify_script_output_outnl_total():number { if (a === b - 1) { return 1; } if (data.lines[a + 1] - 1 > pres) { return pres; } if (data.lines[a + 1] > 1) { return data.lines[a + 1] - 1; } return 1; }()); let index = 0; if (tabs < 0) { tabs = 0; } do { linesout.push(lf); index = index + 1; } while (index < total); if (tabs > 0) { index = 0; do { linesout.push(tab); index = index + 1; } while (index < tabs); } return linesout.join(""); }, reference = function beautify_script_output_reference():void { let s:number = scopes.length, t:number = 0; const applyScope = function beautify_script_output_reference_applyScope():void { // applyScope function exists to prevent presenting spaces as part of reference names if option 'vertical' is set to true let token:string = data.token[a], space:string = ""; const spaceIndex:number = token.indexOf(" "), scopeValue:string = (function beautify_script_output_reference_applyScope_scopeValue():string { let begin:number = data.begin[scopes[s][1]], value:string = ""; if (scopes[s][1] < 0 || begin < 0) { return "0"; } if (data.token[scopes[s][1]] !== undefined && data.token[scopes[s][1]].indexOf("<em") === 0) { begin = scopes[s][1]; } else if (data.token[begin] === undefined || data.token[begin].indexOf("<em") !== 0) { do { begin = data.begin[begin]; } while (begin > 0 && data.token[begin].indexOf("<em") !== 0); } if (begin < 0) { value = "0"; } else { value = data.token[begin]; value = value.slice(value.indexOf("class=") + 8); value = value.slice(0, value.indexOf(">") - 1); } if (data.stack[a] === "arguments" || data.stack[scopes[s][1]] === "arguments") { return String(Number(value) + 1); } return value; }()); if (spaceIndex > 0) { space = token.slice(spaceIndex); token = token.slice(0, spaceIndex); } data.token[a] = `prettydiffltem class="s${scopeValue}"prettydiffgt${token}prettydifflt/emprettydiffgt${space}`; build.push(data.token[a]); }; if (scopes.length < 1) { return; } do { s = s - 1; if (data.token[a].replace(/\s+/, "") === scopes[s][0]) { if (scopes[s][1] <= a) { t = scopes[s][1]; if (t < 0 || data.stack[a] === "arguments" || t === a) { applyScope(); return; } do { t = t + 1; if (data.types[t] === "end" && data.begin[t] === scopes[s][1]) { break; } } while (t < a); if (t === a) { applyScope(); return; } } else if (data.begin[scopes[s][1]] < data.begin[a]){ applyScope(); return; } } } while (s > 0); build.push(data.token[a]); }, invisibles:string[] = ["x;", "x}", "x{", "x(", "x)"]; let a:number = prettydiff.start, external:string = "", lastLevel:number = options.indent_level; if (options.vertical === true) { const vertical = function beautify_script_output_vertical(end:number):void { let longest:number = 0, complex:number = 0, aa:number = end - 1, bb:number = 0, cc:number = 0; const begin:number = data.begin[a], list:[number, number][] = []; do { if ((data.begin[aa] === begin || data.token[aa] === "]" || data.token[aa] === ")") && ((data.token[aa + 1] === ":" && data.stack[aa] === "object") || data.token[aa + 1] === "=")) { bb = aa; complex = 0; do { if (data.begin[bb] === begin) { if (data.token[bb] === "," || data.token[bb] === ";" || data.token[bb] === "x;" || (levels[bb] > -1 && data.types[bb] !== "comment")) { if (data.token[bb + 1] === ".") { complex = complex + (options.indent_size * options.indent_char.length); } break; } } else if (levels[bb] > -1) { break; } if (data.types[bb] !== "comment") { if (levels[bb - 1] === -10) { complex = complex + 1; } complex = data.token[bb].length + complex; } bb = bb - 1; } while (bb > begin); cc = bb; if (data.token[cc] === "," && data.token[aa + 1] === "=") { do { if (data.types[cc] === "end") { cc = data.begin[cc]; } if (data.begin[cc] === begin) { if (data.token[cc] === ";" || data.token[cc] === "x;") { break; } if (data.token[cc] === "var" || data.token[cc] === "const" || data.token[cc] === "let") { complex = complex + (options.indent_size * options.indent_char.length); break; } } cc = cc - 1; } while (cc > begin); } if (complex > longest) { longest = complex; } list.push([aa, complex]); aa = bb; } else if (data.types[aa] === "end") { aa = data.begin[aa]; } aa = aa - 1; } while (aa > begin); aa = list.length; if (aa > 0) { do { aa = aa - 1; bb = list[aa][1]; if (bb < longest) { do { data.token[list[aa][0]] = data.token[list[aa][0]] + " "; bb = bb + 1; } while (bb < longest); } } while (aa > 0); } }; a = b; do { a = a - 1; if (data.lexer[a] === "script") { if (data.token[a] === "}" && data.token[a - 1] !== "{" && levels[data.begin[a]] > 0) { vertical(a); } } else { a = data.begin[a]; } } while (a > 0); } if (options.jsscope !== "none" && options.jsscope !== "interim") { let linecount:number = 1, last:string = "", scope:number = 0, scoped:boolean[] = [], indent:number = options.indent_level, foldindex:[number, number][] = [], start:number = prettydiff.start, exlines:string[] = [], exlevel:number = 0, exline:RegExp; const code:string[] = [], optionValue:string = options.jsscope, foldstart = function beautify_script_output_scope_foldstart():void { let index:number = code.length; do { index = index - 1; } while (index > 0 && code[index] !== "<li>"); if (code[index] === "<li>") { code[index] = `<li class="fold" title="folds from line ${linecount} to line xxx">`; code[index + 1] = `-${code[index + 1]}`; foldindex.push([index, a]); } }, foldend = function beautify_script_output_scope_foldend():void { const lastfold:[number, number] = foldindex[foldindex.length - 1]; if (data.types[a] === "end" && lastfold[1] === data.begin[a]) { code[lastfold[0]] = code[lastfold[0]].replace("xxx", String(linecount)); foldindex.pop(); } else if (data.types[a - 1] === "comment") { let endfold:number = (a === b - 1) ? linecount : linecount - 1; code[lastfold[0]] = code[lastfold[0]].replace("xxx", String(endfold)); foldindex.pop(); } }, // splits block comments, which are single tokens, into multiple lines of output blockline = function beautify_script_output_scope_blockline(x:string):void { const commentLines:string[] = x.split(lf), ii:number = commentLines.length; let hh:number = 0; if (levels[a] > 0) { do { commentLines[0] = tab + commentLines[0]; hh = hh + 1; } while (hh < levels[a]); } hh = 1; build.push(commentLines[0]); if (hh < ii) { do { linecount = linecount + 1; code.push("<li>"); code.push(String(linecount)); code.push("</li>"); build.push(`<em class="line">&#xA;</em></li><li class="c0">${commentLines[hh]}`); hh = hh + 1; } while (hh < ii); } }, //a function for calculating indentation after each new line nlscope = function beautify_script_output_scope_nlscope(x:number):void { let dd = 0; const total:number = (function beautify_script_output_scope_nlscope_total():number { if (a === b - 1) { return 0; } if (data.lines[a + 1] - 1 > pres) { return pres - 1; } if (data.lines[a + 1] > 1) { return data.lines[a + 1] - 2; } return 0; }()), scopepush = function beautify_script_output_scope_nlscope_scopepush():void { let aa:number = 0, bb:number = 0; if (x > 0) { do { build.push(`<span class="l${bb}">${tab}</span>`); if (scoped[aa] === true) { bb = bb + 1; } aa = aa + 1; } while (aa < x); } }; if (data.token[a] !== "x}" || (data.token[a] === "x}" && data.token[a + 1] !== "}")) { let index:number = 0; if (total > 0) { do { linecount = linecount + 1; code.push("<li>"); code.push(String(linecount)); code.push("</li>"); build.push(`<em class="line">&#xA;</em></li><li class="s0">`); index = index + 1; } while (index < total); } linecount = linecount + 1; code.push("<li>"); code.push(String(linecount)); code.push("</li>"); if (a < b - 1 && data.types[a + 1] === "comment") { build.push(`<em class="line">&#xA;</em></li><li class="c0">`); do { build.push(tab); dd = dd + 1; } while (dd < levels[a]); } else { if (data.token[a + 1] === "}" && data.stack[a + 1] !== "object" && data.stack[a + 1] !== "class") { build.push(`<em class="line">&#xA;</em></li><li class="l${scope - 1}">`); } else { build.push(`<em class="line">&#xA;</em></li><li class="l${scope}">`); } scopepush(); } } else { scopepush(); } }, multiline = function beautify_script_output_scope_multiline(x:string):void { const temparray:string[] = x.split(lf), d:number = temparray.length; let c:number = 1; build.push(temparray[0]); do { nlscope(indent); build.push(temparray[c]); c = c + 1; } while (c < d); }; options.jsscope = "interim"; code.push("<div class=\"beautify\" data-prettydiff-ignore=\"true\"><ol class=\"count\">"); code.push("<li>"); code.push("1"); code.push("</li>"); if (data.types[a] === "comment" && data.token[a].indexOf("/*") === 0) { build.push(`<ol class="data"><li class="c0">${tab}`); } else { build.push("<ol class=\"data\"><li>"); } a = 0; if (indent > 0) { do { build.push(tab); a = a + 1; } while (a < indent); } scope = 0; // this loops combines the white space as determined from the algorithm with the // tokens to create the output a = prettydiff.start; do { if (data.lexer[a] === lexer || prettydiff.beautify[data.lexer[a]] === undefined) { if (levels[a] > -1 && a < b - 1) { if (levels[a] < scoped.length) { do { scoped.pop(); } while (levels[a] < scoped.length); } } if (data.types[a] === "comment" && data.token[a].indexOf("/*") === 0) { blockline(data.token[a]); } else if (invisibles.indexOf(data.token[a]) < 0) { if (data.types[a] === "start" && (levels[a] > -1 || data.types[a + 1] === "comment")) { foldstart(); } else if (data.token[a].indexOf("//") === 0 && a < b - 1 && data.token[a + 1].indexOf("//") === 0 && data.token[a - 1].indexOf("//") !== 0 && levels[a - 1] > -1) { foldstart(); } else if (foldindex.length > 0) { if (data.types[a] === "end") { foldend(); } else if ((data.token[a].indexOf("//") !== 0 || a === b - 1) && data.token[foldindex[foldindex.length - 1][1]].indexOf("//") === 0) { foldend(); } } if (data.types[a] === "reference") { reference(); } else if (data.token[a] === "{") { if (data.stack[a + 1] === "object" || data.stack[a + 1] === "class") { scoped.push(false); build.push("{"); } else { if (scoped.length === levels[a]) { if (scoped[scoped.length - 1] === false) { scoped[scoped.length - 1] = true; scope = scope + 1; } } else { scoped.push(true); scope = scope + 1; } data.token[a] = `<em class="s${scope}">{</em>`; build.push(data.token[a]); } if (levels[a] > scoped.length) { do { scoped.push(false); } while (levels[a] > scoped.length); } } else if (data.token[a] === "}") { if (data.stack[a] === "object" || data.stack[a] === "class") { build.push("}"); } else { build.push(`<em class="s${scope}">}</em>`); scope = scope - 1; } } else { if (data.types[a].indexOf("string") > -1 && data.token[a].indexOf("\n") > 0) { multiline(data.token[a].replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")); } else if (data.types[a] === "operator" || data.types[a] === "comment" || data.types[a].indexOf("string") > -1 || data.types[a] === "regex") { build.push(data.token[a].replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")); } else { if (data.types[a] === "start" && levels[a] > -1) { scoped.push(false); } if (data.token[a] !== ";" || options.no_semicolon === false) { build.push(data.token[a]); } else if (levels[a] < 0 && data.types[a + 1] !== "comment") { build.push(";"); } } } } if (a < b - 1 && data.lexer[a + 1] !== lexer && data.begin[a] === data.begin[a + 1] && data.types[a + 1].indexOf("end") < 0 && data.token[a] !== ",") { build.push(" "); } else if (levels[a] > -1 && a < b - 1) { lastLevel = levels[a]; nlscope(levels[a]); } else if (levels[a] === -10) { build.push(" "); if (data.lexer[a + 1] !== lexer) { lastLevel = lastLevel + 1; } } } else { if (externalIndex[a] === a) { build.push(data.token[a] .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/&lt;strong class="new"&gt;this&lt;\/strong&gt;/g, "<strong class=\"new\">this</strong>") .replace(/&lt;strong class="new"&gt;new&lt;\/strong&gt;/g, "<strong class=\"new\">new</strong>")); } else { prettydiff.end = externalIndex[a]; options.indent_level = lastLevel; prettydiff.start = a; external = prettydiff.beautify[data.lexer[a]](options) .replace(/\s+$/, "") .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/&lt;strong class="new"&gt;this&lt;\/strong&gt;/g, "<strong class=\"new\">this</strong>") .replace(/&lt;strong class="new"&gt;new&lt;\/strong&gt;/g, "<strong class=\"new\">new</strong>"); if (external.indexOf(lf) > -1) { if (start === 0) { exline = new RegExp(`\\r?\\n(${tab}){${lastLevel}}`, "g"); external = external.replace(exline, lf); } exlines = external.split(lf); exlevel = 0; if (exlines.length > 1) { do { build.push(exlines[exlevel]); nlscope(lastLevel); exlevel = exlevel + 1; } while (exlevel < exlines.length - 1); build.push(exlines[exlevel]); } } else { build.push(external); } a = prettydiff.iterator; if (levels[a] === -10) { build.push(" "); } else if (levels[a] > -1) { nlscope(levels[a]); } } } a = a + 1; } while (a < b); a = build.length - 1; do { if (build[a] === tab) { build.pop(); } else { break; } a = a - 1; } while (a > -1); //this logic is necessary to some line counting corrections to the HTML output last = build[build.length - 1]; if (last.indexOf("<li") > 0) { build[build.length - 1] = "<em class=\"line\">&#xA;</em></li>"; } else if (last.indexOf("</li>") < 0) { build.push("<em class=\"line\">&#xA;</em></li>"); } build.push("</ol></div>"); last = build.join("").replace(/prettydifflt/g, "<").replace(/prettydiffgt/g, ">"); if (last.match(/<li/g) !== null) { scope = last .match(/<li/g) .length; if (linecount - 1 > scope) { linecount = linecount - 1; do { code.pop(); code.pop(); code.pop(); linecount = linecount - 1; } while (linecount > scope); } } code.push("</ol>"); code.push(lf); code.push(last); if (options.new_line === true) { code.push(lf); } options.jsscope = optionValue; return [ "<p>Scope analysis does not provide support for undeclared variables.</p>", "<p><em>", scolon, "</em> instances of <strong>missing semicolons</strong> counted.</p>", "<p><em>", news, "</em> unnecessary instances of the keyword <strong>new</strong> counted.</p>", code.join("") ].join("").replace(/(\s+)$/, "").replace(options.binary_check, ""); } a = prettydiff.start; do { if (data.lexer[a] === lexer || prettydiff.beautify[data.lexer[a]] === undefined) { if (invisibles.indexOf(data.token[a]) < 0) { if (data.types[a] === "reference" && options.jsscope === "interim") { reference(); } else { if (data.token[a] !== ";" || options.no_semicolon === false) { build.push(data.token[a]); } else if (levels[a] < 0 && data.types[a + 1] !== "comment") { build.push(";"); } } } if (a < b - 1 && data.lexer[a + 1] !== lexer && data.begin[a] === data.begin[a + 1] && data.types[a + 1].indexOf("end") < 0 && data.token[a] !== ",") { build.push(" "); } else if (levels[a] > -1) { if (((levels[a] > -1 && data.token[a] === "{") || (levels[a] > -1 && data.token[a + 1] === "}")) && data.lines[a] < 3 && options.brace_line === true) { build.push(nl(0)); } lastLevel = levels[a]; build.push(nl(levels[a])); } else if (levels[a] === -10) { build.push(" "); if (data.lexer[a + 1] !== lexer) { lastLevel = lastLevel + 1; } } } else { if (externalIndex[a] === a) { build.push(data.token[a]); } else { prettydiff.end = externalIndex[a]; options.indent_level = lastLevel; prettydiff.start = a; external = prettydiff.beautify[data.lexer[a]](options).replace(/\s+$/, ""); build.push(external); a = prettydiff.iterator; if (levels[a] === -10) { build.push(" "); } else if (levels[a] > -1) { build.push(nl(levels[a])); } } } a = a + 1; } while (a < b); prettydiff.iterator = b - 1; return build.join(""); }()); return output; }; global.prettydiff.beautify.script = script; }());
the_stack
export default function kaboom(conf?: KaboomConf): KaboomCtx; export type KaboomCtx = { // assets loadRoot(path?: string): string, loadSprite( id: string, src: SpriteLoadSrc, conf?: SpriteLoadConf, ): Promise<SpriteData>, loadSound( id: string, src: string, ): Promise<SoundData>, loadFont( id: string, src: string, gw: number, gh: number, chars?: string, ): Promise<FontData>, loadShader( name: string, vert?: string, frag?: string, isUrl?: boolean, ): Promise<ShaderData>, addLoader<T>(l: Promise<T>): void, // game start(scene: string, ...args): void, scene(name: string, cb: (...args) => void): void, go(name: string, ...args): void, width(): number, height(): number, dt(): number, time(): number, screenshot(): string, // scene / obj add(comps: Comp[]): GameObj, readd(obj: GameObj): GameObj, destroy(obj: GameObj): void, destroyAll(tag: string): void, get(tag?: string): GameObj[], every(t: string, f: (obj: GameObj) => void): void, every(f: (obj: GameObj) => void): void, revery(t: string, f: (obj: GameObj) => void): void, revery(f: (obj: GameObj) => void): void, layers(list: string[], def?: string): void, on(event: string, tag: string, cb: (obj: GameObj) => void): void, action(tag: string, cb: (obj: GameObj) => void): void, action(cb: () => void): void, render(tag: string, cb: (obj: GameObj) => void): void, render(cb: () => void): void, collides( t1: string, t2: string, f: (a: GameObj, b: GameObj) => void, ): void, overlaps( t1: string, t2: string, f: (a: GameObj, b: GameObj) => void, ): void, clicks( tag: string, f: (a: GameObj) => void, ): void, camPos(p: Vec2): Vec2, camScale(p: Vec2): Vec2, camRot(a: number): number, camShake(n: number): void, camIgnore(layers: string[]): void, gravity(g: number): number, sceneData(): any, // net recv(type: string, handler: MsgHandler): void, send(type: string, data: any): void, // comps pos(x: number, y: number): PosComp, pos(xy: number): PosComp, pos(p: Vec2): PosComp, pos(): PosComp, scale(x: number, y: number): ScaleComp, scale(xy: number): ScaleComp, scale(p: Vec2): ScaleComp, scale(): ScaleComp, rotate(a: number): RotateComp, color(r: number, g: number, b: number, a?: number): ColorComp, color(c: Color): ColorComp, color(): ColorComp, origin(o: Origin | Vec2): OriginComp, layer(l: string): LayerComp, area(p1: Vec2, p2: Vec2): AreaComp, sprite(id: string, conf?: SpriteCompConf): SpriteComp, text(t: string, size?: number, conf?: TextCompConf): TextComp, rect(w: number, h: number, conf?: RectCompConf): RectComp, solid(): SolidComp, body(conf?: BodyCompConf): BodyComp, shader(id: string): ShaderComp, // inputs cursor(c?: string): void, mousePos(layer?: string): Vec2, keyDown(k: string, f: () => void): void, keyPress(k: string, f: () => void): void, keyPressRep(k: string, f: () => void): void, keyRelease(k: string, f: () => void): void, charInput(f: (ch: string) => void): void, mouseDown(f: () => void): void, mouseClick(f: () => void): void, mouseRelease(f: () => void): void, keyIsDown(k: string): boolean, keyIsPressed(k: string): boolean, keyIsPressedRep(k: string): boolean, keyIsReleased(k: string): boolean, mouseIsDown(): boolean, mouseIsClicked(): boolean, mouseIsReleased(): boolean, loop(t: number, f: () => void): void, wait(t: number, f?: () => void): Promise<void>, // audio play(id: string, conf?: AudioPlayConf): AudioPlay, volume(v?: number): number, // math makeRng(seed: number): RNG, rand(): number, rand<T extends RNGValue>(n: T): T, rand<T extends RNGValue>(a: T, b: T): T, randSeed(seed: number): void, vec2(x: number, y: number): Vec2, vec2(p: Vec2): Vec2, vec2(xy: number): Vec2, vec2(): Vec2, rgb(r: number, g: number, b: number): Color, rgba(r: number, g: number, b: number, a: number): Color, quad(x: number, y: number, w: number, h: number): Quad, choose<T>(lst: T[]): T, chance(p: number): boolean, lerp(from: number, to: number, t: number): number, map( v: number, l1: number, h1: number, l2: number, h2: number, ): number, mapc( v: number, l1: number, h1: number, l2: number, h2: number, ): number, wave(lo: number, hi: number, t: number): number, deg2rad(deg: number): number, rad2deg(rad: number): number, // draw drawSprite(id: string | SpriteData, conf?: DrawSpriteConf): void, // TODO: conf type drawText(txt: string, conf?: {}): void, drawRect(pos: Vec2, w: number, h: number, conf?: DrawRectConf): void, drawRectStroke(pos: Vec2, w: number, h: number, conf?: DrawRectStrokeConf): void, drawLine(p1: Vec2, p2: Vec2, conf?: DrawLineConf): void, // dbg debug: Debug, // helpers addLevel(map: string[], conf: LevelConf): Level, }; export type KaboomConf = { width?: number, height?: number, scale?: number, fullscreen?: boolean, debug?: boolean, crisp?: boolean, canvas?: HTMLCanvasElement, root?: HTMLElement, clearColor?: number[], inspectColor?: number[], texFilter?: TexFilter, logMax?: number, connect?: string, global?: boolean, plugins?: KaboomPlugin[], }; export type GameObj = { hidden: boolean, paused: boolean, exists(): boolean, is(tag: string | string[]): boolean, use(comp: Comp): void, action(cb: () => void): void, on(ev: string, cb: () => void): void, trigger(ev: string, ...args): void, rmTag(t: string): void, _id: GameObjID | null, _tags: string[], _events: { add: (() => void)[], update: (() => void)[], draw: (() => void)[], destroy: (() => void)[], inspect: (() => {})[], }, [custom: string]: any, }; export type SpriteAnim = { from: number, to: number, }; export type KaboomPlugin = (k: KaboomCtx) => Record<string, any>; export type SpriteLoadConf = { sliceX?: number, sliceY?: number, gridWidth?: number, gridHeight?: number, anims?: Record<string, SpriteAnim>, }; export type SpriteLoadSrc = string | GfxTextureData; export type SpriteData = { tex: GfxTexture, frames: Quad[], anims: Record<string, SpriteAnim>, }; export type SoundData = AudioBuffer; export type FontData = GfxFont; export type ShaderData = GfxProgram; export type AudioPlayConf = { loop?: boolean, volume?: number, speed?: number, detune?: number, seek?: number, }; export type AudioPlay = { play(seek?: number): void, stop(): void, pause(): void, paused(): boolean, stopped(): boolean, speed(s?: number): number, detune(d?: number): number, volume(v?: number): number, time(): number, duration(): number, loop(): void, unloop(): void, }; export type GfxProgram = { bind(): void, unbind(): void, bindAttribs(): void, send(uniform: Uniform): void, } export type GfxTexture = { width: number, height: number, bind(): void, unbind(): void, }; export type GfxTextureData = HTMLImageElement | HTMLCanvasElement | ImageData | ImageBitmap ; export type GfxFont = { tex: GfxTexture, map: Record<string, Vec2>, qw: number, qh: number, }; export type Vertex = { pos: Vec3, uv: Vec2, color: Color, }; export type TexFilter = "nearest" | "linear"; export type DrawQuadConf = { pos?: Vec2, width?: number, height?: number, scale?: Vec2 | number, rot?: number, color?: Color, origin?: Origin | Vec2, z?: number, tex?: GfxTexture, quad?: Quad, prog?: GfxProgram, uniform?: Uniform, }; export type DrawTextureConf = { pos?: Vec2, scale?: Vec2 | number, rot?: number, color?: Color, origin?: Origin | Vec2, quad?: Quad, z?: number, prog?: GfxProgram, uniform?: Uniform, }; export type DrawRectStrokeConf = { width?: number, scale?: Vec2 | number, rot?: number, color?: Color, origin?: Origin | Vec2, z?: number, prog?: GfxProgram, }; export type DrawRectConf = { scale?: Vec2 | number, rot?: number, color?: Color, origin?: Origin | Vec2, z?: number, prog?: GfxProgram, uniform?: Uniform, }; export type DrawLineConf = { width?: number, color?: Color, z?: number, prog?: GfxProgram, }; export type DrawTextConf = { size?: number, pos?: Vec2, scale?: Vec2 | number, rot?: number, color?: Color, origin?: Origin | Vec2, width?: number, z?: number, prog?: GfxProgram, }; export type FormattedChar = { tex: GfxTexture, quad: Quad, ch: string, pos: Vec2, scale: Vec2, color: Color, origin: string, z: number, }; export type FormattedText = { width: number, height: number, chars: FormattedChar[], }; export type Origin = "topleft" | "top" | "topright" | "left" | "center" | "right" | "botleft" | "bot" | "botright" ; export type DrawSpriteConf = { frame?: number, pos?: Vec2, scale?: Vec2 | number, rot?: number, color?: Color, origin?: Origin, quad?: Quad, prog?: ShaderData, uniform?: Uniform, z?: number, }; export type Vec2 = { x: number, y: number, clone(): Vec2, add(p: Vec2): Vec2, sub(p: Vec2): Vec2, scale(s: number): Vec2, dot(p: Vec2): Vec2, dist(p: Vec2): number, len(): number, unit(): Vec2, normal(): Vec2, angle(p: Vec2): number, lerp(p: Vec2, t: number): Vec2, eq(p: Vec2): boolean, str(): string, }; export type Vec3 = { x: number, y: number, z: number, xy(): Vec2, }; export type Vec4 = { x: number, y: number, z: number, w: number, }; export type Mat4 = { m: number[], clone(): Mat4, mult(m: Mat4): Mat4, multVec4(m: Vec4): Vec4, multVec3(m: Vec3): Vec3, multVec2(m: Vec2): Vec2, scale(s: Vec2): Mat4, translate(p: Vec2): Mat4, rotateX(a: number): Mat4, rotateY(a: number): Mat4, rotateZ(a: number): Mat4, invert(): Mat4, }; export type Color = { r: number, g: number, b: number, a: number, clone(): Color, lighten(n: number): Color, darken(n: number): Color, invert(): Color, isDark(p?: number): boolean, isLight(p?: number): boolean, eq(c: Color): boolean, }; export type Quad = { x: number, y: number, w: number, h: number, clone(): Quad, eq(q: Quad): boolean, }; export type RNGValue = number | Vec2 | Color ; export type RNG = { seed: number, gen(): number, gen<T extends RNGValue>(n: T): T, gen<T extends RNGValue>(a: T, b: T): T, }; export type Rect = { p1: Vec2, p2: Vec2, }; export type Line = { p1: Vec2, p2: Vec2, }; export type MsgHandler = (data: any, id: number) => void; export type Comp = any; export type GameObjID = number; export type AddEvent = () => void; export type DrawEvent = () => void; export type UpdateEvent = () => void; export type DestroyEvent = () => void; export type PosCompInspect = { pos: string, }; export type PosComp = { pos: Vec2, move(x: number, y: number): void, move(p: Vec2): void, inspect(): PosCompInspect, }; export type ScaleComp = { scale: Vec2, flipX(s: number): void, flipY(s: number): void, }; export type RotateComp = { angle: number, }; export type ColorComp = { color: Color, }; export type OriginComp = { origin: Origin | Vec2, }; export type LayerCompInspect = { layer: string, }; export type LayerComp = { layer: string, inspect(): LayerCompInspect, }; export type RectSide = "top" | "bottom" | "left" | "right" ; export type CollisionResolve = { obj: GameObj, side: RectSide, } export type AreaComp = { area: Rect, areaWidth(): number, areaHeight(): number, isClicked(): boolean, isHovered(): boolean, isCollided(o: GameObj): boolean, isOverlapped(o: GameObj): boolean, clicks(f: () => void): void, hovers(f: () => void): void, collides(tag: string, f: (o: GameObj) => void): void, overlaps(tag: string, f: (o: GameObj) => void): void, hasPt(p: Vec2): boolean, resolve(): void, _worldArea(): Rect; _checkCollisions(tag: string, f: (obj: GameObj) => void): void; _checkOverlaps(tag: string, f: (obj: GameObj) => void): void; }; export type SpriteCompConf = { noArea?: boolean, quad?: Quad, frame?: number, animSpeed?: number, }; export type SpriteCompCurAnim = { name: string, loop: boolean, timer: number, }; export type SpriteComp = { add: AddEvent, draw: DrawEvent, update: UpdateEvent, width: number, height: number, animSpeed: number, frame: number, quad: Quad, play(anim: string, loop?: boolean): void, stop(): void, changeSprite(id: string): void, numFrames(): number, curAnim(): string, inspect(): SpriteCompInspect, }; export type SpriteCompInspect = { curAnim?: string, }; export type TextComp = { add: AddEvent, draw: DrawEvent, text: string, textSize: number, font: string, width: number, height: number, }; export type TextCompConf = { noArea?: boolean, font?: string, width?: number, }; export type RectComp = { add: AddEvent, draw: DrawEvent, width: number, height: number, }; export type RectCompConf = { noArea?: boolean, }; export type LevelConf = { width: number, height: number, pos?: Vec2, any(s: string): Comp[] | undefined, [sym: string]: any, // [sym: string]: Comp[] | (() => Comp[]), }; export type Level = { getPos(p: Vec2): Vec2, spawn(sym: string, p: Vec2): GameObj, width(): number, height(): number, destroy(): void, }; export type Debug = { paused: boolean, inspect: boolean, timeScale: number, showLog: boolean, fps(): number, objCount(): number, drawCalls(): number, stepFrame(): void, clearLog(): void, log(msg: string): void, error(msg: string): void, }; export type UniformValue = Vec2 | Vec3 | Color | Mat4 ; export type Uniform = Record<string, UniformValue>; export type ShaderComp = { uniform: Uniform, shader: string, }; export type BodyComp = { update: UpdateEvent, jumpForce: number, curPlatform(): GameObj | null, grounded(): boolean, falling(): boolean, jump(f: number): void, }; export type BodyCompConf = { jumpForce?: number, maxVel?: number, }; export type SolidComp = { solid: boolean, }; export type LoopHandle = { stop(): void, };
the_stack
import { axios } from '../axios-instance'; import { Firewall, FirewallInboundRule, FirewallOutboundRule } from '../models/firewall'; export class FirewallService { constructor() {} /** * Create a new Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const newFirewall = { * "name": "firewall", * "inbound_rules": [ * { * "protocol": "tcp", * "ports": "80", * "sources": { * "load_balancer_uids": [ * "4de7ac8b-495b-4884-9a69-1050c6793cd6" * ] * } * }, * { * "protocol": "tcp", * "ports": 22, * "sources": { * "tags": [ * "gateway" * ], * "addresses": [ * "18.0.0.0/8" * ] * } * } * ], * "outbound_rules": [ * { * "protocol": "tcp", * "ports": "80", * "destinations": { * "addresses": [ * "0.0.0.0/0", * "::/0" * ] * } * } * ], * "droplet_ids": [ * 8043964 * ], * "tags": null * }; * const firewall = await client.firewalls.createFirewall(newFirewall); * ``` */ public createFirewall(firewall: Firewall): Promise<Firewall> { return new Promise((resolve, reject) => { axios .post(`/firewalls`, firewall) .then(response => { // Return actual firewall instead of wrapped firewall resolve(response.data.firewall); }) .catch(error => { reject(error); }); }); } /** * Show information about an existing Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const firewall = await client.firewalls.getExistingFirewall('firewall-id'); * ``` */ public getExistingFirewall(firewallId: string): Promise<Firewall> { return new Promise((resolve, reject) => { axios .get(`/firewalls/${firewallId}`) .then(response => { // Return actual firewall instead of wrapped firewall resolve(response.data.firewall); }) .catch(error => { reject(error); }); }); } /** * List all of the Cloud Firewalls available on your account * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const firewall = await client.firewalls.getAllFirewalls(); * ``` */ public getAllFirewalls(): Promise<Firewall[]> { return new Promise((resolve, reject) => { axios .get(`/firewalls`) .then(response => { // Return actual firewalls instead of wrapped firewalls resolve(response.data.firewalls); }) .catch(error => { reject(error); }); }); } /** * Update the configuration of an existing Cloud Firewall * * **NOTE: Any attributes that are not provided will be reset to their default values.** * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const updatedFirewall = { * "name": "firewall", * "inbound_rules": [ * { * "protocol": "tcp", * "ports": "8080", * "sources": { * "load_balancer_uids": [ * "4de7ac8b-495b-4884-9a69-1050c6793cd6" * ] * } * }, * { * "protocol": "tcp", * "ports": 22, * "sources": { * "tags": [ * "gateway" * ], * "addresses": [ * "18.0.0.0/8" * ] * } * } * ], * "outbound_rules": [ * { * "protocol": "tcp", * "ports": "8080", * "destinations": { * "addresses": [ * "0.0.0.0/0", * "::/0" * ] * } * } * ], * "droplet_ids": [ * 8043964 * ], * "tags": [ * "frontend" * ] * }; * const firewall = await client.firewalls.updateFirewall(updatedFirewall); * ``` */ public updateFirewall(firewall: Firewall): Promise<Firewall> { return new Promise((resolve, reject) => { axios .put(`/firewalls/${firewall.id}`, firewall) .then(response => { // Return actual firewall instead of wrapped firewall resolve(response.data.firewall); }) .catch(error => { reject(error); }); }); } /** * Delete a Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * await client.firewalls.deleteFirewall('firewall-id'); * ``` */ public deleteFirewall(firewallId: string): Promise<void> { return new Promise((resolve, reject) => { axios .delete(`/firewalls/${firewallId}`) .then(() => { resolve(); }) .catch(error => { reject(error); }); }); } /** * Assign Droplets to a Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const dropletIds = [ * 'droplet-id-1', * 'droplet-id-2' * ]; * await client.firewalls.addDropletsToFirewall('firewall-id', dropletIds); * ``` */ public addDropletsToFirewall( firewallId: string, dropletIds: number[] ): Promise<void> { return new Promise((resolve, reject) => { const request = { droplet_ids: dropletIds }; axios .post(`/firewalls/${firewallId}/droplets`, request) .then(() => { resolve(); }) .catch(error => { reject(error); }); }); } /** * Remove Droplets from a Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const dropletIds = [ * 'droplet-id-1', * 'droplet-id-2' * ]; * await client.firewalls.removeDropletsFromFirewall('firewall-id', dropletIds); * ``` */ public removeDropletsFromFirewall( firewallId: string, dropletIds: number[] ): Promise<void> { return new Promise((resolve, reject) => { const request = { droplet_ids: dropletIds }; axios .delete(`/firewalls/${firewallId}/droplets`, { data: request }) .then(() => { resolve(); }) .catch(error => { reject(error); }); }); } /** * Assign a Tag representing a group of Droplets to a Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const tags = [ * 'my-tag-1', * 'my-tag-2' * ]; * await client.firewalls.addTagsToFirewall('firewall-id', tags); * ``` */ public addTagsToFirewall(firewallId: string, tags: string[]): Promise<void> { return new Promise((resolve, reject) => { const request = { tags }; axios .post(`/firewalls/${firewallId}/tags`, request) .then(() => { resolve(); }) .catch(error => { reject(error); }); }); } /** * Remove a Tag representing a group of Droplets from a Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const tags = [ * 'my-tag-1', * 'my-tag-2' * ]; * await client.firewalls.removeTagsFromFirewall('firewall-id', tags); * ``` */ public removeTagsFromFirewall( firewallId: string, tags: string[] ): Promise<void> { return new Promise((resolve, reject) => { const request = { tags }; axios .delete(`/firewalls/${firewallId}/tags`, { data: request }) .then(() => { resolve(); }) .catch(error => { reject(error); }); }); } /** * Add additional access rules to a Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const inboundRules = [ * { * "protocol": "tcp", * "ports": "3306", * "sources": { * "droplet_ids": [ * 49696269 * ] * } * } * ]; * outboundRules = [ * { * "protocol": "tcp", * "ports": "3306", * "destinations": { * "droplet_ids": [ * 49696269 * ] * } * } * ]; * await client.firewalls.addRulesToFirewall('firewall-id', inboundRules, outboundRules); * ``` */ public addRulesToFirewall( firewallId: string, inboundRules: FirewallInboundRule[], outboundRules: FirewallOutboundRule[] ): Promise<void> { return new Promise((resolve, reject) => { const request = { inbound_rules: inboundRules, outbound_rules: outboundRules }; axios .post(`/firewalls/${firewallId}/rules`, request) .then(() => { resolve(); }) .catch(error => { reject(error); }); }); } /** * Remove access rules from a Cloud Firewall * * ### Example * ```js * import { DigitalOcean } from 'digitalocean-js'; * * const client = new DigitalOcean('your-api-key'); * const inboundRules = [ * { * "protocol": "tcp", * "ports": "3306", * "sources": { * "droplet_ids": [ * 49696269 * ] * } * } * ]; * outboundRules = [ * { * "protocol": "tcp", * "ports": "3306", * "destinations": { * "droplet_ids": [ * 49696269 * ] * } * } * ]; * await client.firewalls.removeRulesFromFirewall('firewall-id', inboundRules, outboundRules); * ``` */ public removeRulesFromFirewall( firewallId: string, inboundRules: FirewallInboundRule[], outboundRules: FirewallOutboundRule[] ): Promise<void> { return new Promise((resolve, reject) => { const request = { inbound_rules: inboundRules, outbound_rules: outboundRules }; axios .delete(`/firewalls/${firewallId}/rules`, { data: request }) .then(() => { resolve(); }) .catch(error => { reject(error); }); }); } }
the_stack
import { abortAbleAll, IAbortAblePromise } from 'lineupengine'; import { ANOTHER_ROUND } from '../internal/scheduler'; import { IForEachAble, lazySeq, boxplotBuilder, categoricalStatsBuilder, categoricalValueCacheBuilder, dateStatsBuilder, dateValueCacheBuilder, IAdvancedBoxPlotData, ICategoricalStatistics, IDateStatistics, IStatistics, numberStatsBuilder, dateValueCache2Value, categoricalValueCache2Value, joinIndexArrays, IBuilder, ISequence, IStringStatistics, stringStatsBuilder, } from '../internal'; import { CategoricalColumn, Column, ICompareValue, DateColumn, ICategoricalLikeColumn, IDataRow, IDateColumn, IGroup, ImpositionCompositeColumn, IndicesArray, INumberColumn, NumberColumn, OrdinalColumn, Ranking, UIntTypedArray, ICategory, StringColumn, isMapAbleColumn, } from '../model'; import type { IRenderTask, IRenderTasks } from '../renderer'; import type { CompareLookup } from './sort'; /** * a render task that is already resolved */ export class TaskNow<T> implements IRenderTask<T> { constructor(public readonly v: T) {} then<U = void>(onfullfilled: (value: T) => U) { return onfullfilled(this.v); } } /** * factory function for */ export function taskNow<T>(v: T) { return new TaskNow(v); } /** * a render task based on an abortable promise */ export class TaskLater<T> implements IRenderTask<T> { constructor(public readonly v: IAbortAblePromise<T>) {} then<U = void>(onfullfilled: (value: T | symbol) => U): IAbortAblePromise<U> { return this.v.then(onfullfilled); } } export function taskLater<T>(v: IAbortAblePromise<T>) { return new TaskLater(v); } /** * similar to Promise.all */ export function tasksAll<T>(tasks: IRenderTask<T>[]): IRenderTask<T[]> { if (tasks.every((t) => t instanceof TaskNow)) { return taskNow(tasks.map((d) => (d as TaskNow<T>).v)); } return taskLater(abortAbleAll((tasks as (TaskNow<T> | TaskLater<T>)[]).map((d) => d.v))); } export interface IRenderTaskExecutor extends IRenderTasks { setData(data: IDataRow[]): void; dirtyColumn(col: Column, type: 'data' | 'summary' | 'group'): void; dirtyRanking(ranking: Ranking, type: 'data' | 'summary' | 'group'): void; groupCompare(ranking: Ranking, group: IGroup, rows: IndicesArray): IRenderTask<ICompareValue[]>; preCompute(ranking: Ranking, groups: { rows: IndicesArray; group: IGroup }[], maxDataIndex: number): void; preComputeCol(col: Column): void; preComputeData(ranking: Ranking): void; copyData2Summary(ranking: Ranking): void; copyCache(col: Column, from: Column): void; sort( ranking: Ranking, group: IGroup, indices: IndicesArray, singleCall: boolean, maxDataIndex: number, lookups?: CompareLookup ): Promise<IndicesArray>; terminate(): void; valueCache(col: Column): undefined | ((dataIndex: number) => any); } export class MultiIndices { private _joined: IndicesArray | null = null; constructor(public readonly indices: IndicesArray[], private readonly maxDataIndex: number) {} get joined() { if (this.indices.length === 1) { return this.indices[0]; } if (this.indices.length === 0) { return new Uint8Array(0); } if (this._joined) { return this._joined; } return (this._joined = joinIndexArrays(this.indices, this.maxDataIndex)); } } /** * number of data points to build per iteration / chunk */ const CHUNK_SIZE = 100; export interface ARenderTaskOptions { stringTopNCount: number | readonly string[]; } export class ARenderTasks { protected readonly valueCacheData = new Map< string, Float32Array | UIntTypedArray | Int32Array | Float64Array | readonly string[] >(); protected readonly byIndex = (i: number) => this.data[i]; protected readonly options: ARenderTaskOptions; protected data: IDataRow[] = []; constructor(options: Partial<ARenderTaskOptions> = {}) { this.options = Object.assign( { stringTopNCount: 10, }, options ); } protected byOrder(indices: IndicesArray): ISequence<IDataRow> { return lazySeq(indices).map(this.byIndex); } protected byOrderAcc<T>(indices: IndicesArray, acc: (row: IDataRow) => T) { return lazySeq(indices).map((i) => acc(this.data[i])); } /** * builder factory to create an iterator that can be used to schedule * @param builder the builder to use * @param order the order to iterate over * @param acc the accessor to get the value out of the data * @param build optional build mapper */ private builder<T, BR, B extends { push: (v: T) => void; build: () => BR }, R = BR>( builder: B, order: IndicesArray | null | MultiIndices, acc: (dataIndex: number) => T, build?: (r: BR) => R ): Iterator<R | null> { let i = 0; // no indices given over the whole data const nextData = (currentChunkSize: number = CHUNK_SIZE) => { let chunkCounter = currentChunkSize; const data = this.data; for (; i < data.length && chunkCounter > 0; ++i, --chunkCounter) { builder.push(acc(i)); } if (i < data.length) { // need another round return ANOTHER_ROUND; } // done return { done: true, value: build ? build(builder.build()) : (builder.build() as unknown as R), }; }; let o = 0; const orders = order instanceof MultiIndices ? order.indices : [order]; const nextOrder = (currentChunkSize: number = CHUNK_SIZE) => { let chunkCounter = currentChunkSize; while (o < orders.length) { const actOrder = orders[o]!; for (; i < actOrder.length && chunkCounter > 0; ++i, --chunkCounter) { builder.push(acc(actOrder[i])); } if (i < actOrder.length) { // need another round return ANOTHER_ROUND; } // done with this order o++; i = 0; } return { done: true, value: build ? build(builder.build()) : (builder.build() as unknown as R), }; }; return { next: order == null ? nextData : nextOrder }; } private builderForEach<T, BR, B extends { pushAll: (v: IForEachAble<T>) => void; build: () => BR }, R = BR>( builder: B, order: IndicesArray | null | MultiIndices, acc: (dataIndex: number) => IForEachAble<T>, build?: (r: BR) => R ): Iterator<R | null> { return this.builder( { push: builder.pushAll, build: builder.build, }, order, acc, build ); } protected boxplotBuilder<R = IAdvancedBoxPlotData>( order: IndicesArray | null | MultiIndices, col: INumberColumn, raw?: boolean, build?: (stat: IAdvancedBoxPlotData) => R ) { const b = boxplotBuilder(); return this.numberStatsBuilder(b, order, col, raw, build); } protected resolveDomain(col: INumberColumn, raw: boolean): [number, number] { const domain = raw && isMapAbleColumn(col) ? col.getMapping().domain : [0, 1]; return [domain[0], domain[domain.length - 1]]; } protected statsBuilder<R = IStatistics>( order: IndicesArray | null | MultiIndices, col: INumberColumn, numberOfBins: number, raw?: boolean, build?: (stat: IStatistics) => R ) { const b = numberStatsBuilder(this.resolveDomain(col, raw ?? false), numberOfBins); return this.numberStatsBuilder(b, order, col, raw, build); } private numberStatsBuilder<R, B extends IBuilder<number, BR>, BR>( b: B, order: IndicesArray | null | MultiIndices, col: INumberColumn, raw?: boolean, build?: (stat: BR) => R ) { if (col instanceof NumberColumn || col instanceof OrdinalColumn || col instanceof ImpositionCompositeColumn) { const key = raw ? `${col.id}:r` : col.id; const dacc: (i: number) => number = raw ? (i) => col.getRawNumber(this.data[i]) : (i) => col.getNumber(this.data[i]); if (order == null && !this.valueCacheData.has(key)) { // build and valueCache const vs = new Float32Array(this.data.length); let i = 0; return this.builder( { push: (v) => { b.push(v); vs[i++] = v; }, build: () => { this.setValueCacheData(key, vs); return b.build(); }, }, null, dacc, build ); } const cache = this.valueCacheData.get(key) as UIntTypedArray; const acc: (i: number) => number = cache ? (i) => cache[i] : dacc; return this.builder(b, order, acc, build); } const acc: (i: number) => IForEachAble<number> = raw ? (i) => col.iterRawNumber(this.data[i]) : (i) => col.iterNumber(this.data[i]); return this.builderForEach(b, order, acc, build); } protected dateStatsBuilder<R = IDateStatistics>( order: IndicesArray | null | MultiIndices, col: IDateColumn, template?: IDateStatistics, build?: (stat: IDateStatistics) => R ) { const b = dateStatsBuilder(template); if (col instanceof DateColumn) { if (order == null) { // build and valueCache const vs = dateValueCacheBuilder(this.data.length); return this.builder( { push: (v) => { b.push(v); vs.push(v); }, build: () => { this.setValueCacheData(col.id, vs.cache); return b.build(); }, }, null, (i: number) => col.getDate(this.data[i]), build ); } const cache = this.valueCacheData.get(col.id) as UIntTypedArray; const acc: (i: number) => Date | null = cache ? (i) => dateValueCache2Value(cache[i]) : (i) => col.getDate(this.data[i]); return this.builder(b, order, acc, build); } return this.builderForEach(b, order, (i: number) => col.iterDate(this.data[i]), build); } protected categoricalStatsBuilder<R = ICategoricalStatistics>( order: IndicesArray | null | MultiIndices, col: ICategoricalLikeColumn, build?: (stat: ICategoricalStatistics) => R ) { const b = categoricalStatsBuilder(col.categories); if (col instanceof CategoricalColumn || col instanceof OrdinalColumn) { if (order == null) { // build and valueCache const vs = categoricalValueCacheBuilder(this.data.length, col.categories); return this.builder( { push: (v) => { b.push(v); vs.push(v); }, build: () => { this.setValueCacheData(col.id, vs.cache); return b.build(); }, }, null, (i: number) => col.getCategory(this.data[i]), build ); } const cache = this.valueCacheData.get(col.id) as UIntTypedArray; const acc: (i: number) => ICategory | null = cache ? (i) => categoricalValueCache2Value(cache[i], col.categories) : (i) => col.getCategory(this.data[i]); return this.builder(b, order, acc, build); } return this.builderForEach(b, order, (i: number) => col.iterCategory(this.data[i]), build); } protected stringStatsBuilder<R = IStringStatistics>( order: IndicesArray | null | MultiIndices, col: StringColumn, topN?: number | readonly string[], build?: (stat: IStringStatistics) => R ) { const b = stringStatsBuilder(topN ?? this.options.stringTopNCount); if (order == null) { // build and valueCache let i = 0; const vs: string[] = Array(this.data.length).fill(null); return this.builder( { push: (v) => { b.push(v); vs[i++] = v; }, build: () => { this.setValueCacheData(col.id, vs); return b.build(); }, }, null, (i: number) => col.getValue(this.data[i]), build ); } return this.builder(b, order, (i: number) => col.getValue(this.data[i]), build); } dirtyColumn(col: Column, type: 'data' | 'summary' | 'group') { if (type !== 'data') { return; } this.valueCacheData.delete(col.id); this.valueCacheData.delete(`${col.id}:r`); } protected setValueCacheData( key: string, value: Float32Array | UIntTypedArray | Int32Array | Float64Array | readonly string[] | null ) { if (value == null) { this.valueCacheData.delete(key); } else { this.valueCacheData.set(key, value); } } valueCache(col: Column) { const v = this.valueCacheData.get(col.id); if (!v) { return undefined; } if (col instanceof DateColumn) { return (dataIndex: number) => dateValueCache2Value(v[dataIndex] as number); } if (col instanceof CategoricalColumn || col instanceof OrdinalColumn) { return (dataIndex: number) => categoricalValueCache2Value(v[dataIndex] as number, col.categories); } return (dataIndex: number) => v[dataIndex]; } }
the_stack
import * as long from "long"; import * as microtime from "microtime"; import { Device as HidDevice, devices as hidDevices, HID } from "node-hid"; import { Subject } from "rxjs"; import * as usbDetect from "usb-detection"; import { privateData } from "../../../shared/lib"; import { MotionData, MotionDataWithTimestamp } from "../../../shared/models"; import { DualshockBattery, DualshockConnection, DualshockMeta, DualshockModel, DualshockReport, DualshockState, GenericSteamDevice, SteamDeviceRatios, SteamDeviceReport, SteamDeviceScales, SteamDeviceState, SteamHidId, } from "../../models"; import { emptySteamDeviceReport } from "./empty-report"; import { HidFeatureArray } from "./hid-feature-array"; /** * Shorthand function for converting number to boolean. * @param value Value to convert to. * @returns Boolean representation of a given value. */ function bool(value: number) { return value !== 0; } /** * Hid event types. */ const enum HidEvent { DataUpdate = 0x3c01, ConnectionUpdate = 0x0103, BatteryUpdate = 0x0b04, } /** * Possible HID device types. */ type DeviceType = "dongle" | "wired"; /** * Interface for storing HID devices. */ interface Item { info: HidDevice; type: DeviceType; active: boolean; device: SteamHidDevice | null; } /** * Internal class data interface. */ interface InternalData { errorSubject: Subject<Error>; infoString: string | null; motionDataSubject: Subject<MotionDataWithTimestamp>; openCloseSubject: Subject<{ info: string, status: boolean }>; reportSubject: Subject<SteamDeviceReport>; } /** * Event handler for list change events. */ const listChangeSubject = new Subject<void>(); /** * Private data getter. */ const getInternals = privateData() as (self: SteamHidDevice, init: InternalData | void) => InternalData; /** * Class for handling HID based steam devices. */ export class SteamHidDevice extends GenericSteamDevice { /** * Array containing all supported device types. */ public static allTypes: DeviceType[] = ["wired", "dongle"]; /** * Returns list change event observable. */ public static get onListChange() { return listChangeSubject.asObservable(); } /** * Starts monitoring for new HID devices. */ public static startMonitoring() { if (this.motoringCallCount++ === 0) { this.updateDeviceList(0, ...this.allTypes); // Dongle devices can be connected using usb events usbDetect.on( `change:${SteamHidId.Vendor}:${SteamHidId.DongleProduct}`, () => this.updateDeviceList(1000, "dongle"), ); usbDetect.on( `change:${SteamHidId.Vendor}:${SteamHidId.WiredProduct}`, () => this.updateDeviceList(1000, "wired"), ); usbDetect.startMonitoring(); } } /** * Stops monitoring for new HID devices. */ public static stopMonitoring() { if (--this.motoringCallCount === 0) { usbDetect.stopMonitoring(); } } /** * Enumerate currently available devices. * @param activeOnly Exclude inactive devices. * @returns Array of device system paths. */ public static enumerateDevices(activeOnly: boolean = false) { const devices: string[] = []; if (activeOnly) { this.updateDongleStatus(); } for (const [path, item] of this.itemList) { if (item.device === null) { if (((activeOnly && item.active) || !activeOnly) && !this.blacklistedDevices.has(path)) { devices.push(path); } } } return devices; } /** * Stored item list. */ private static itemList = new Map<string, Item>(); /** * Temporary blacklisted devices in case they might have been disconnected. */ private static blacklistedDevices = new Set<string>(); /** * Stored device array. */ private static deviceList: HidDevice[] | null = null; /** * Call count tracker to prevent running multiple trackers. */ private static motoringCallCount: number = 0; /** * Update device list. * @param delay Delay interval before updating. * @param types Types to be include in updated list. */ private static updateDeviceList(delay: number, ...types: DeviceType[]) { const refresh = () => { this.deviceList = hidDevices(); this.refreshItemList(...types); }; if (delay > 0) { setTimeout(refresh, delay); } else { refresh(); } } /** * Shorthand function for filtering and sorting device array. * @param options Options for this method. * @return Device array after filtering and sorting. */ private static getDevices(options?: { devices?: HidDevice[], filter?: (device: HidDevice) => boolean, sort?: (a: HidDevice, b: HidDevice) => number, }) { let { devices = this.deviceList || [] } = options || {}; if (options) { if (devices.length > 0 && options.filter) { devices = devices.filter(options.filter); } if (devices.length > 0 && options.sort) { devices = devices.sort(options.sort); } } return devices; } /** * Refresh item list. * @param types Types to keep in refreshed list. */ private static refreshItemList(...types: DeviceType[]) { const allDevices = this.getDevices(); let listChanged = false; const osSpecificFilter = (device: HidDevice, type: DeviceType) => { if (process.platform === "win32") { return device.usagePage === 0xFF00; } else { return type === "wired" ? device.interface === 1 : true; } }; const filterDevices = (devices: HidDevice[], type: DeviceType) => { for (const device of devices) { if (device.path) { if (!this.itemList.has(device.path)) { this.itemList.set(device.path, { active: type !== "dongle", device: null, info: device, type, }); listChanged = true; } } } for (const [path, item] of this.itemList) { if (item.type === type) { const hasDevice = devices.findIndex((device) => device.path === path) !== -1; if (!hasDevice) { if (item.device) { item.device.close(); } this.itemList.delete(path); listChanged = true; } } } return listChanged; }; for (const type of types) { let devices: HidDevice[] | null = null; switch (type) { case "dongle": devices = this.getDevices({ devices: allDevices, filter: (device) => { return device.productId === SteamHidId.DongleProduct && device.vendorId === SteamHidId.Vendor && device.interface > 0 && device.interface < 5 && osSpecificFilter(device, type); }, sort: (a, b) => { return a.interface > b.interface ? 1 : 0; }, }); break; case "wired": devices = this.getDevices({ devices: allDevices, filter: (device) => { return device.productId === SteamHidId.WiredProduct && device.vendorId === SteamHidId.Vendor && device.interface > 0 && device.interface < 5 && osSpecificFilter(device, type); }, sort: (a, b) => { return a.interface > b.interface ? 1 : 0; }, }); break; } if (devices !== null) { filterDevices(devices, type); if (type === "dongle") { this.updateDongleStatus(); } } } if (listChanged) { listChangeSubject.next(); } } private static updateDongleStatus() { const wirelessStateCheck = new HidFeatureArray(0xB4).array; for (const [path, item] of this.itemList) { try { if (item.type === "dongle") { const device = (item.device !== null ? item.device.hidDevice : null) || new HID(path); device.sendFeatureReport(wirelessStateCheck); const data = device.getFeatureReport(wirelessStateCheck[0], wirelessStateCheck.length); item.active = data[2] > 0 && data[3] === 2; } // tslint:disable-next-line:no-empty } catch (everything) { } // In case HID devices are disconnected } } /** * Current steam device report. */ private currentReport = emptySteamDeviceReport(); /** * Motion data. */ private currentMotionData: MotionDataWithTimestamp = { accelerometer: { range: [-SteamDeviceScales.Accelerometer, SteamDeviceScales.Accelerometer], x: 0, y: 0, z: 0, }, gyro: { range: [-SteamDeviceScales.Gyro, SteamDeviceScales.Gyro], x: 0, y: 0, z: 0, }, timestamp: 0, }; /** * Last active connection timestamp. */ private connectionTimestamp: number = 0; /** * Holds last packet number with valid motion data. */ private lastValidSensorPacket: number = 0; /** * Current HID device. */ private hidDevice: HID | null = null; constructor() { super(); getInternals(this, { errorSubject: new Subject(), infoString: null, motionDataSubject: new Subject(), openCloseSubject: new Subject(), reportSubject: new Subject(), }); } public get onReport() { return getInternals(this).reportSubject.asObservable(); } public get onMotionsData() { return getInternals(this).motionDataSubject.asObservable(); } public get onError() { return getInternals(this).errorSubject.asObservable(); } public get onOpenClose() { return getInternals(this).openCloseSubject.asObservable(); } public get infoString() { return getInternals(this).infoString; } public get report() { return this.currentReport; } public get motionData() { return this.currentMotionData; } public open() { this.close(); const devices = SteamHidDevice.enumerateDevices(true); if (devices.length > 0) { const pd = getInternals(this); const devicePath = devices[0]; if (SteamHidDevice.itemList.has(devicePath)) { const item = SteamHidDevice.itemList.get(devicePath) as Item; if (item.device === null) { this.hidDevice = new HID(devicePath); this.hidDevice.on("data", (data: Buffer) => { if (this.parseRawData(data)) { pd.reportSubject.next(this.currentReport); pd.motionDataSubject.next(this.motionData); } }); this.hidDevice.on("error", (error: Error) => { if (error.message === "could not read from HID device") { // It is possible that device has been physically disconnected, we should // try to handle this gracefully SteamHidDevice.blacklistedDevices.add(devicePath); setTimeout(() => { SteamHidDevice.blacklistedDevices.delete(devicePath); }, 3000); this.close(); } else { pd.errorSubject.next(error); } }); item.device = this; pd.infoString = JSON.stringify(item.info, undefined, " "); this.connectionTimestamp = microtime.now(); pd.openCloseSubject.next({ info: pd.infoString, status: true }); } } } return this; } public close() { if (this.isOpen()) { const pd = getInternals(this); const info = pd.infoString!; this.hidDevice!.close(); this.hidDevice = null; pd.infoString = null; for (const [path, item] of SteamHidDevice.itemList) { if (item.device === this) { item.device = null; break; } } pd.openCloseSubject.next({ info, status: false }); } return this; } public isOpen() { return this.hidDevice !== null; } public reportToDualshockReport(report: SteamDeviceReport): DualshockReport { // tslint:disable:object-literal-sort-keys return { packetCounter: report.packetCounter, motionTimestamp: long.fromNumber(report.timestamp, true), button: { R1: report.button.RS, L1: report.button.LS, R2: report.button.RT, L2: report.button.LT, R3: report.button.rightPad, L3: report.button.stick, PS: report.button.steam, SQUARE: report.button.X, CROSS: report.button.A, CIRCLE: report.button.B, TRIANGLE: report.button.Y, options: report.button.next, share: report.button.previous, dPad: { UP: report.button.dPad.UP, RIGHT: report.button.dPad.RIGHT, LEFT: report.button.dPad.LEFT, DOWN: report.button.dPad.DOWN, }, touch: false, }, position: { left: { x: this.toDualshockPosition(report.position.stick.x), y: this.toDualshockPosition(report.position.stick.y), }, right: { x: this.toDualshockPosition(report.position.rightPad.x), y: this.toDualshockPosition(report.position.rightPad.y), }, }, trigger: { R2: report.trigger.LEFT, L2: report.trigger.RIGHT, }, accelerometer: { range: [-SteamDeviceScales.Accelerometer, SteamDeviceScales.Accelerometer], x: -report.accelerometer.x, y: -report.accelerometer.z, z: report.accelerometer.y, }, gyro: { range: [-SteamDeviceScales.Gyro, SteamDeviceScales.Gyro], x: report.gyro.x, y: -report.gyro.z, z: -report.gyro.y, }, trackPad: { first: { isActive: false, id: 0, x: 0, y: 0, }, second: { isActive: false, id: 0, x: 0, y: 0, }, }, }; // tslint:enable:object-literal-sort-keys } public reportToDualshockMeta(report: SteamDeviceReport, padId: number): DualshockMeta { return { batteryStatus: DualshockBattery.None, connectionType: DualshockConnection.Usb, isActive: microtime.now() - report.timestamp < 1000000, macAddress: report.macAddress, model: DualshockModel.DS4, padId, state: report.state === SteamDeviceState.Connected ? DualshockState.Connected : DualshockState.Disconnected, }; } /** * Convert Steam Controller's position to Dualshock compatible position. * @param int16Value Value to convert. * @returns Dualshock compatible position value. */ private toDualshockPosition(int16Value: number) { return Math.floor((int16Value + 32768) * 255 / 65535); } /** * Parses raw HID input and updates current report. * @param data Data to parser. */ private parseRawData(data: Buffer) { const time = microtime.now(); const report = this.currentReport; let event: number; let index = 0; index += 2; // skip reading id (or something else) event = data.readUInt16LE(index); index += 2; if (event === HidEvent.DataUpdate) { let leftPadReading: boolean; let preserveData: boolean; let buttonData: number; report.state = SteamDeviceState.Connected; report.timestamp = time - this.connectionTimestamp; if (report.timestamp < 0) { this.connectionTimestamp = time; report.timestamp = 0; } report.packetCounter = data.readUInt32LE(index); index += 4; buttonData = data[index++]; report.button.RT = bool(buttonData & 0x01); report.button.LT = bool(buttonData & 0x02); report.button.RS = bool(buttonData & 0x04); report.button.LS = bool(buttonData & 0x08); report.button.Y = bool(buttonData & 0x10); report.button.B = bool(buttonData & 0x20); report.button.X = bool(buttonData & 0x40); report.button.A = bool(buttonData & 0x80); buttonData = data[index++]; report.button.dPad.UP = bool(buttonData & 0x01); report.button.dPad.RIGHT = bool(buttonData & 0x02); report.button.dPad.LEFT = bool(buttonData & 0x04); report.button.dPad.DOWN = bool(buttonData & 0x08); report.button.previous = bool(buttonData & 0x10); report.button.steam = bool(buttonData & 0x20); report.button.next = bool(buttonData & 0x40); report.button.grip.LEFT = bool(buttonData & 0x80); buttonData = data[index++]; preserveData = bool(buttonData & 0x80); leftPadReading = bool(buttonData & 0x08); report.button.grip.RIGHT = bool(buttonData & 0x01); report.button.rightPad = bool(buttonData & 0x04); report.button.stick = bool(buttonData & 0x40) || (preserveData ? report.button.stick : false); report.touch.leftPad = leftPadReading || (preserveData ? report.touch.leftPad : false); report.touch.rightPad = bool(buttonData & 0x10); report.trigger.LEFT = data[index++]; report.trigger.RIGHT = data[index++]; index += 3; // padding? if (leftPadReading) { report.position.leftPad.x = data.readInt16LE(index); index += 2; report.position.leftPad.y = data.readInt16LE(index); if (!preserveData) { report.position.stick.x = 0; report.position.stick.y = 0; } } else { report.position.stick.x = data.readInt16LE(index); index += 2; report.position.stick.y = data.readInt16LE(index); if (!preserveData) { report.position.leftPad.x = 0; report.position.leftPad.y = 0; } } index += 2; report.position.rightPad.x = data.readInt16LE(index); index += 2; report.position.rightPad.y = data.readInt16LE(index); index += 2; index += 4; // padding? report.accelerometer.x = data.readInt16LE(index) * SteamDeviceRatios.Accelerometer; index += 2; report.accelerometer.y = data.readInt16LE(index) * SteamDeviceRatios.Accelerometer; index += 2; report.accelerometer.z = data.readInt16LE(index) * SteamDeviceRatios.Accelerometer; index += 2; report.gyro.x = data.readInt16LE(index) * SteamDeviceRatios.Gyro; index += 2; report.gyro.y = data.readInt16LE(index) * SteamDeviceRatios.Gyro; index += 2; report.gyro.z = data.readInt16LE(index) * SteamDeviceRatios.Gyro; index += 2; report.quaternion.x = data.readInt16LE(index) * SteamDeviceRatios.Quaternion; index += 2; report.quaternion.y = data.readInt16LE(index) * SteamDeviceRatios.Quaternion; index += 2; report.quaternion.z = data.readInt16LE(index) * SteamDeviceRatios.Quaternion; index += 2; report.quaternion.w = data.readInt16LE(index) * SteamDeviceRatios.Quaternion; if (this.isSensorDataStuck(this.currentMotionData, report, report.packetCounter)) { this.enableSensors(); } this.currentMotionData.accelerometer = report.accelerometer; this.currentMotionData.gyro = report.gyro; this.currentMotionData.timestamp = report.timestamp; } else if (event === HidEvent.ConnectionUpdate) { const connection = data[index]; if (connection === 0x01) { report.state = SteamDeviceState.Disconnected; setImmediate(() => this.close()); } else if (connection === 0x02) { report.state = SteamDeviceState.Connected; } else if (connection === 0x03) { report.state = SteamDeviceState.Pairing; } } else if (event === HidEvent.BatteryUpdate) { report.state = SteamDeviceState.Connected; index += 8; report.battery = data.readInt16LE(index); } else { // unknown event return false; } return true; } /** * Determine whether sensor data is stuck. * @param previousData Previous motion data. * @param currentData Current motion data. * @param packetCounter Current packet count. * @returns `true` if sensor is stuck. */ private isSensorDataStuck(previousData: MotionData, currentData: MotionData, packetCounter: number) { const probablyStuck = ( ( previousData.accelerometer.x === currentData.accelerometer.x && previousData.accelerometer.y === currentData.accelerometer.y && previousData.accelerometer.z === currentData.accelerometer.z ) || ( previousData.gyro.x === currentData.gyro.x && previousData.gyro.y === currentData.gyro.y && previousData.gyro.z === currentData.gyro.z ) ); if (probablyStuck) { if (packetCounter - this.lastValidSensorPacket > 200) { this.lastValidSensorPacket = packetCounter; return true; } } else { this.lastValidSensorPacket = packetCounter; } return false; } /** * Try to enable motion sensors. */ private enableSensors() { if (this.isOpen()) { try { const gyro = 0x10; const accelerometer = 0x08; const quaternion = 0x04; const featureArray = new HidFeatureArray(); featureArray.appendUint16(0x30, gyro | accelerometer | quaternion); this.hidDevice!.sendFeatureReport(featureArray.array); // tslint:disable-next-line:no-empty } catch (everything) { } } } }
the_stack
import { ReactiveElement, PropertyValues, ReactiveControllerHost, } from '@lit/reactive-element'; import { MutationController, MutationControllerConfig, } from '../mutation_controller.js'; import {generateElementName, nextFrame} from './test-helpers.js'; 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'); } // Run tests if MutationObserver and ShadowRoot is present. ShadowRoot test // prevents consistent ie11 failures. const canTest = window.MutationObserver && window.ShadowRoot && // eslint-disable-next-line @typescript-eslint/no-explicit-any !(window as any).ShadyDOM?.inUse; (canTest ? suite : suite.skip)('MutationController', () => { let container: HTMLElement; interface TestElement extends ReactiveElement { observer: MutationController; observerValue: unknown; resetObserverValue: () => void; changeDuringUpdate?: () => void; } const defineTestElement = ( getControllerConfig: ( host: ReactiveControllerHost ) => MutationControllerConfig ) => { class A extends ReactiveElement { observer: MutationController; observerValue: unknown; changeDuringUpdate?: () => void; constructor() { super(); const config = getControllerConfig(this); this.observer = new MutationController(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; }; const getTestElement = async ( getControllerConfig: ( host: ReactiveControllerHost ) => MutationControllerConfig ) => { 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(() => ({ config: {attributes: true}, })); // Reports initial change by default assert.isTrue(el.observerValue); // Reports attribute change el.resetObserverValue(); el.setAttribute('hi', 'hi'); await nextFrame(); assert.isTrue(el.observerValue); // Reports another attribute change el.resetObserverValue(); el.requestUpdate(); await nextFrame(); assert.isUndefined(el.observerValue); el.setAttribute('bye', 'bye'); await nextFrame(); assert.isTrue(el.observerValue); }); test('can observe changes during update', async () => { const el = await getTestElement(() => ({ config: {attributes: true}, })); el.resetObserverValue(); el.changeDuringUpdate = () => el.setAttribute('hi', 'hi'); el.requestUpdate(); await nextFrame(); assert.isTrue(el.observerValue); }); test('skips initial changes when `skipInitial` is `true`', async () => { const el = await getTestElement((host: ReactiveControllerHost) => ({ target: host as unknown as HTMLElement, config: {attributes: true}, 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(); el.setAttribute('hi', 'hi'); await nextFrame(); assert.isTrue(el.observerValue); // Reports another attribute change el.resetObserverValue(); el.requestUpdate(); await nextFrame(); assert.isUndefined(el.observerValue); el.setAttribute('bye', 'bye'); await nextFrame(); assert.isTrue(el.observerValue); }); test('observation managed via connection', async () => { const el = await getTestElement(() => ({ config: {attributes: true}, skipInitial: true, })); assert.isUndefined(el.observerValue); // Does not report change after element removed. el.remove(); el.setAttribute('hi', 'hi'); // Reports no change after element re-connected. container.appendChild(el); await nextFrame(); assert.isUndefined(el.observerValue); // Reports change on mutation when element is connected el.setAttribute('hi', 'hi'); await nextFrame(); assert.isTrue(el.observerValue); }); test('can observe external element', async () => { const el = await getTestElement(() => ({ target: document.body, config: {childList: true}, skipInitial: true, })); assert.equal(el.observerValue, undefined); const d = document.createElement('div'); document.body.appendChild(d); await nextFrame(); assert.isTrue(el.observerValue); el.resetObserverValue(); d.remove(); await nextFrame(); assert.isTrue(el.observerValue); }); test('can manage value via `callback`', async () => { const el = await getTestElement(() => ({ config: {childList: true}, callback: (records: MutationRecord[]) => { return records .map((r: MutationRecord) => Array.from(r.addedNodes).map((n: Node) => (n as Element).localName) ) .flat(Infinity); }, })); el.appendChild(document.createElement('div')); await nextFrame(); assert.sameMembers(el.observerValue as string[], ['div']); el.appendChild(document.createElement('span')); await nextFrame(); assert.sameMembers(el.observerValue as string[], ['span']); }); test('can call `observe` to observe element', async () => { const el = await getTestElement(() => ({ config: {attributes: true}, })); el.resetObserverValue(); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.appendChild(d1); await nextFrame(); assert.isTrue(el.observerValue); // Reports change to observed target. el.resetObserverValue(); d1.setAttribute('a', 'a'); await nextFrame(); assert.isTrue(el.observerValue); // Reports change to configured target. el.resetObserverValue(); el.setAttribute('a', 'a'); await nextFrame(); assert.isTrue(el.observerValue); // Can observe another target el.resetObserverValue(); const d2 = document.createElement('div'); el.observer.observe(d2); el.appendChild(d2); await nextFrame(); assert.isTrue(el.observerValue); // Reports change to new observed target. el.resetObserverValue(); d2.setAttribute('a', 'a'); await nextFrame(); assert.isTrue(el.observerValue); // Reports change to configured target. el.resetObserverValue(); el.setAttribute('a', 'a'); await nextFrame(); assert.isTrue(el.observerValue); // Reports change to first observed target. el.resetObserverValue(); d1.setAttribute('a', 'a'); await nextFrame(); assert.isTrue(el.observerValue); }); test('can specifying target as `null` and call `observe` to observe element', async () => { const el = await getTestElement(() => ({ target: null, config: {attributes: true}, })); el.resetObserverValue(); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.appendChild(d1); await nextFrame(); assert.isTrue(el.observerValue); // Reports change to observed target. el.resetObserverValue(); d1.setAttribute('a', 'a'); await nextFrame(); assert.isTrue(el.observerValue); // Can observe another target el.resetObserverValue(); const d2 = document.createElement('div'); el.observer.observe(d2); el.appendChild(d2); await nextFrame(); assert.isTrue(el.observerValue); // Reports change to new observed target. el.resetObserverValue(); d2.setAttribute('a', 'a'); await nextFrame(); assert.isTrue(el.observerValue); // Reports change to first observed target. el.resetObserverValue(); d1.setAttribute('a', 'a1'); await nextFrame(); assert.isTrue(el.observerValue); }); test('observed target respects `skipInitial`', async () => { const el = await getTestElement(() => ({ target: null, config: {attributes: true}, skipInitial: true, })); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.appendChild(d1); await nextFrame(); assert.isUndefined(el.observerValue); // Reports change to observed target. d1.setAttribute('a', 'a'); await nextFrame(); assert.isTrue(el.observerValue); }); test('observed target not re-observed on connection', async () => { const el = await getTestElement(() => ({ target: null, config: {attributes: true}, })); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.appendChild(d1); await nextFrame(); assert.isTrue(el.observerValue); el.resetObserverValue(); await nextFrame(); el.remove(); // Does not reports change when disconnected. d1.setAttribute('a', 'a'); await nextFrame(); assert.isUndefined(el.observerValue); // Does not report change when re-connected container.appendChild(el); d1.setAttribute('a', 'a1'); await nextFrame(); assert.isUndefined(el.observerValue); // Can re-observe after connection. el.observer.observe(d1); d1.setAttribute('a', 'a2'); await nextFrame(); assert.isTrue(el.observerValue); }); });
the_stack
import { CPU } from "./cpu"; import { Memory } from "./memory"; import { Cartridge, Mirroring } from "./cartridge"; import { PPU } from "./ppu"; import { FPSController } from "./fps_controller"; import { VideoScreen } from "./video"; import { InputController } from "./input_controller"; import { BitHelper } from "./bithelper"; import { APU, Note } from "./apu"; import { SaveState } from "./savestate"; declare var $,toastr; export class Nes { SCREEN_MAIN: VideoScreen; SCREEN_WIDTH = 256; SCREEN_HEIGHT = 240; SCREEN_DEBUG: VideoScreen; SCREEN_DEBUG_WIDTH = 400; SCREEN_DEBUG_HEIGHT = 300; canvas_ctx: CanvasRenderingContext2D; canvas: HTMLCanvasElement; canvasImage: ImageData; canvasDebug_ctx: CanvasRenderingContext2D; canvasDebug: HTMLCanvasElement; canvasDebug_Image: ImageData; cpu: CPU; ppu: PPU; memory: Memory; cartridge: Cartridge; apu: APU; fps_controller: FPSController; rom_name: string = ''; //debug DEBUGMODE: boolean = false; PAUSED: boolean = true; SAMPLEPROGRAM: boolean = false; error_message: string = ''; inputController: InputController; reverseSpriteOrder = false; //if we should read oam backwards for priority debug_view_chr = false; debug_view_nametable = true; debugNametable = 1; //which nametable is viewed on debug screen debugDisableSprites = false; debugProgram: string = ''; //view stats via rivets debugMemory: string = ''; //view stats via rivets debugStats: string = ''; //view stats via rivets debugMemPage = 0; //which page of memory map to view debugSoundMode = false; debugSquare1Visual = ''; debugSquare2Visual = ''; debugTriangleVisual = ''; debugSquare1Note = ''; debugSquare2Note = ''; debugTriangleNote = ''; debugSoundStats = ''; //view sound stats //nestest rom nestestlog: string[] = []; nestestlogstatus: string[] = []; nestestcounter = 0; nestestlogmode: boolean = false; //ALSO GO TO CPU UNCOMMENT CYCLES nestestframecounter = 0; //SHOULD REACH LINE 5003 TO PASS //ALSO GO TO frame() AND UNCOMMENT nestestlogmode CHECK //performance tuning timeDiff = 0; timeCalc = 0; //hacks isSmb3 = false; constructor() { this.memory = new Memory(this); this.cpu = new CPU(this); this.ppu = new PPU(this); this.cartridge = new Cartridge(this); this.apu = new APU(this); this.fps_controller = new FPSController(60); if (this.nestestlogmode) { this.btnReadLog(); } } initCanvases() { //init canvases this.canvas = $('#canvas')[0]; this.canvas_ctx = this.canvas.getContext("2d"); this.canvasImage = this.canvas_ctx.getImageData(0, 0, this.SCREEN_WIDTH, this.SCREEN_HEIGHT); this.canvas_ctx.fillStyle = "black"; this.canvas_ctx.fillRect(0, 0, this.SCREEN_WIDTH, this.SCREEN_HEIGHT); if (this.DEBUGMODE) { this.enableDebugCanvas(); } //initialize pixelData this.SCREEN_MAIN = new VideoScreen(this.SCREEN_WIDTH, this.SCREEN_HEIGHT, this.canvas_ctx, this); } enableDebugMode(){ this.DEBUGMODE=true; setTimeout(() => { this.enableDebugCanvas(); document.getElementById('divMonOuter').classList.replace("col-sm-8","col-sm-12") document.getElementById('divEmuOuter').classList.replace("col-sm-4","col-sm-12") }, 1000); } enableDebugCanvas(){ this.canvasDebug = $('#canvasDebug')[0]; this.canvasDebug_ctx = this.canvasDebug.getContext("2d"); this.canvasDebug_Image = this.canvasDebug_ctx.getImageData(0, 0, this.SCREEN_DEBUG_WIDTH, this.SCREEN_DEBUG_HEIGHT); this.canvasDebug_ctx.fillStyle = "black"; this.canvasDebug_ctx.fillRect(0, 0, this.SCREEN_DEBUG_WIDTH, this.SCREEN_DEBUG_HEIGHT); this.SCREEN_DEBUG = new VideoScreen(this.SCREEN_DEBUG_WIDTH, this.SCREEN_DEBUG_HEIGHT, this.canvasDebug_ctx, this); } btnReadLog() { $.get('nestest.log.txt').then((data) => { console.log('data read'); var lines: string[] = data.split('\r\n'); lines.forEach(line => { var address = line.substr(0, 4); this.nestestlog.push(address); var status = line.substr(line.indexOf('P:')).substr(2, 2); this.nestestlogstatus.push(status); }); }); } loadROM(rom_data: string, rom_name: string) { console.log('rom length', rom_data.length); this.rom_name = rom_name; if (this.SAMPLEPROGRAM) { //for testing this.loadSampleProgram(); } else { this.cartridge.load(rom_data); } //call the reset function on the cpu this.cpu.reset(); if (this.nestestlogmode) { this.cpu.PC = 0xC000; if (this.DEBUGMODE) this.cpu.getNextInstructionForDebug(); } } /* SAMPLE PROGRAM TO MULTIPLY 10x3 and using a loop then store the result in 0x8040 *=$8000 LDX #10 STX $8020 LDX #3 STX $8030 LDY $8020 LDA #0 CLC loop ADC $8030 DEY BNE loop STA $8040 NOP NOP NOP */ //online emulator here for testing //Note: set start address and program counter //to 8000 before pasting code //https://www.masswerk.at/6502/index.html loadSampleProgram() { //all tests assume program counter starts at location 0x8000 //test program 1 - multiple 3x10 // var program = "A2 0A 8E 20 80 A2 03 8E 30 80 AC 20 80 A9 00 18 6D 30 80 88 D0 FA 8D 40 80 EA EA EA"; //test program 2 - subtraction test 10-5 = 5 // var program = "A9 0A 38 E9 05 8D 20 80 EA"; //test program 3 - subtraction test going negative 5-10 = 251 or 0xFB // var program = "A9 05 38 E9 0A 8D 20 80 EA"; //test program 4 - test ASL arithmetic shift left // var program = "A9 40 8D 20 80 0E 20 80 0E 20 80 0E 20 80 0E 20 80 EA"; //test program 5 - test jump to subroutine, return, adds 5+7 and copies to x and y registers var program = "A9 05 20 09 80 AA 4C 0C 80 69 07 60 A8 EA"; //test program 6 - rotate left and rotate right the value 5. test that carry bit is set on last ROR // var program = "A9 05 2A 6A 6A EA"; //test program 7 - rotate left and right number 129 (10000001) - observe carry bit // var program = "A9 81 2A 6A 6A EA"; //test program 8 - ROL and ROR with absolute addressing, at the end copies result to accumulator // var program = "A2 81 8E 20 80 2E 20 80 6E 20 80 6E 20 80 AD 20 80 EA"; var codes = program.split(" "); var counter = 0x8000; for (let i = 0; i < codes.length; i++) { let code = parseInt(codes[i], 16); this.memory.write(counter, code); counter++; } //set reset vector this.memory.write(0xFFFC, 0x00); this.memory.write(0xFFFD, 0x80); this.debugMemPage = 0x8000; } SEIJumpMode=false; SEIJump(){ this.SEIJumpMode = true; } frame() { let perfCheck = window.performance.now(); if (this.fps_controller.frame_limiter_enabled) { if (this.fps_controller.IsFrameReady()==false) return; } this.fps_controller.countFPS(); // let cycle_counter = 0; //for debugging if (!this.PAUSED) { while (this.ppu.frame_complete == false) { //EXPENSIVE // if (this.nestestlogmode) // this.compareNesTestLog(); this.cpu.clock(); //ppu is clocked at 3 times the speed of the cpu this.ppu.clock(); // this.ppu.clock(); // this.ppu.clock(); // cycle_counter++; } this.ppu.frame_complete = false; //audio - every half frame this.apu.halfFrame(); this.apu.halfFrame(); //set volumes after all's said and done //to avoid crackling sound this.apu.adjustVolumes(); } else { //so i can easily step through without waiting on cycles this.cpu.cycles = 0; } if (this.SEIJumpMode){ let seifound = false; while (seifound == false) { //EXPENSIVE // if (this.nestestlogmode) // this.compareNesTestLog(); this.cpu.clock(); //ppu is clocked at 3 times the speed of the cpu this.ppu.clock(); // this.ppu.clock(); // this.ppu.clock(); // cycle_counter++; this.cpu.getNextInstructionForDebug(); if (this.cpu.next_op=="SEI") { seifound=true; } } this.SEIJumpMode = false; this.PAUSED=true; } //for running 10x3 sample asm if (this.SAMPLEPROGRAM) { this.cpu.getNextInstructionForDebug(); this.cpu.updateHexDebugValues(); this.drawDebugInfo(); return; } //if recording music mode is on this.processRecordMusic(); // this.render(); if (this.DEBUGMODE) { this.cpu.getNextInstructionForDebug(); this.cpu.updateHexDebugValues(); this.drawDebugInfo(); this.drawDebugScreen(); } //page swap the image buffers onto the canvases this.applyScreenBuffers(); //for calculating how many milliseconds to run each frame() this.timeCalc++; if (this.timeCalc % 60 == 0) this.timeDiff = window.performance.now() - perfCheck; //process load/save states this.load_state_process(); this.drawFPS(); } saveStateRequested = false; loadStateRequested = false; reloadStateRequested = false; loadStateData:SaveState = null; reload_rom_data:any; saveState(){ this.saveStateRequested = true; } loadState(){ this.loadStateRequested = true; } reloadState(){ this.reloadStateRequested = true; } load_state_process(){ if (this.saveStateRequested){ SaveState.save(this,this.rom_name); this.saveStateRequested = false; toastr.info("State Saved"); } if (this.loadStateRequested){ SaveState.load(this,this.rom_name); this.loadStateRequested = false; } if (this.reloadStateRequested){ SaveState.reset(this); this.cartridge.load(this.reload_rom_data); this.cpu.reset(); this.reloadStateRequested = false; } if (this.loadStateData!=null){ //reset it back to null so it only does it once //at the end of a frame if there is any data //to load after the indexedDB async call returns SaveState.parseLoad(this,this.loadStateData); this.loadStateData = null; } } drawFPS() { let x = 195; let y = 220; let w = 50; let h = 15; this.SCREEN_MAIN.drawBox(x, y, w, h, "white"); this.SCREEN_MAIN.drawText("FPS: " + this.fps_controller.currentfps, x + 2, y + 12, "red"); this.SCREEN_MAIN.drawBox(x, y - 34, w, h, "white"); this.SCREEN_MAIN.drawText("" + this.timeDiff.toFixed(3), x + 2, y - 22, "red"); } render(){ this.drawBackground(0); this.drawBackground(1); if (this.debugDisableSprites == false) this.drawSprites(); } drawSprites() { let startingSprite = 0; let counter = 0; if (this.reverseSpriteOrder) counter = 63*4; //hack for super mario to not draw sprite 0 if (this.rom_name == "smb.nes") { startingSprite = 1; counter = 4; } for (let i = startingSprite; i < 64; i++) { //byte 0 - y position //byte 1 - tile number (0-255) //byte 2 - attributes //bute 3 - x position //Y POSITION LOOKS LIKE ITS 1 DOWN let y_position = this.ppu.oam[counter] + 1; let tile_number = this.ppu.oam[counter + 1]; let attributes = this.ppu.oam[counter + 2]; let x_position = this.ppu.oam[counter + 3]; if (x_position < 0 || x_position >= this.SCREEN_MAIN.SCREEN_WIDTH || y_position < 0 || y_position >= this.SCREEN_MAIN.SCREEN_HEIGHT) { //don't render it's off screen } else { //8x8 Tiles Mode if (this.ppu.sprite_size == 0) { let offset = 0; //hack if (this.rom_name != 'ducktales.nes') { if (this.ppu.pattern_sprite == 1) offset = 256 * 16; } this.ppu.renderTile((tile_number * 16) + offset, x_position, y_position, this.SCREEN_MAIN, 0, 0, null, null, attributes); } //8x16 Tiles Mode else { //https://wiki.nesdev.com/w/index.php/PPU_OAM let tile_byte = this.ppu.oam[counter + 1]; tile_number = tile_byte & 254; //left 7 bits let chr_table = BitHelper.getBit(tile_byte, 0); if (chr_table == 1) tile_number += 256; let tile1 = tile_number; let tile2 = tile_number+1; let flip_v = BitHelper.getBit(attributes,7); if (flip_v) { tile1 = tile_number + 1; tile2 = tile_number } //top tile this.ppu.renderTile(tile1 * 16, x_position, y_position, this.SCREEN_MAIN, 0, 0, null, null, attributes); //bottom tile this.ppu.renderTile(tile2 * 16, x_position, y_position + 8, this.SCREEN_MAIN, 0, 0, null, null, attributes); } } if (this.reverseSpriteOrder) counter -= 4 else counter += 4; } } drawBackground(nameTable: number) { //TODO move these to the ppu class //SCROLLING //precalculate this before calling render tile //greatly improves performance //figure out where the pixel will ultimately be, //taking into account scrolling let scrolladjust_y = 0; let scrolladjust_x = 0; if (this.cartridge.mirroring == Mirroring.HORIZONTAL) //ice climber style up_down { if (nameTable == 0 && this.ppu.nametable_y == 0) scrolladjust_y = 0; if (nameTable == 0 && this.ppu.nametable_y == 1) scrolladjust_y = 240; if (nameTable == 1 && this.ppu.nametable_y == 0) scrolladjust_y = 240; if (nameTable == 1 && this.ppu.nametable_y == 1) scrolladjust_y = 0; } if (this.cartridge.mirroring == Mirroring.VERTICAL) //mario style left_right { if (nameTable == 0 && this.ppu.nametable_x == 0) scrolladjust_x = 0; if (nameTable == 0 && this.ppu.nametable_x == 1) scrolladjust_x = 256; if (nameTable == 1 && this.ppu.nametable_x == 0) scrolladjust_x = 256; if (nameTable == 1 && this.ppu.nametable_x == 1) scrolladjust_x = 0; } scrolladjust_x -= this.ppu.scroll_x; scrolladjust_y -= this.ppu.scroll_y; let scrollXStore = scrolladjust_x; let nameTableCounter = 0; for (let y = 0; y < 30; y++) { for (let x = 0; x < 32; x++) { //smb sprite zero scroll hack if (this.rom_name == "smb.nes") { if (y<4) { if (nameTable==0) scrolladjust_x = 0; if (nameTable==1) scrolladjust_x = 256; } else scrolladjust_x = scrollXStore; } let isOffScreen = false; let x_screen = (x * 8) + scrolladjust_x; let y_screen = (y * 8) + scrolladjust_y; //first pass check if (x_screen < -8 || x_screen >= this.SCREEN_WIDTH || y_screen < -8 || y_screen >= this.SCREEN_HEIGHT) isOffScreen = true; let wraparound_x = 0; let wraparound_y = 0; //WRAPAROUND //currently only handles the 2 most common //types of wraparound when it is //updating the last row of tiles as you're walking //examples - Double Dragon, Castlevania 2 if (isOffScreen) { if (this.cartridge.mirroring == Mirroring.HORIZONTAL) //ice climber style up_down { if (x_screen < 0) wraparound_x += 256 } if (this.cartridge.mirroring == Mirroring.VERTICAL) //mario style left_right { if (y_screen < 0) wraparound_y += 240; } isOffScreen = false; x_screen += wraparound_x; y_screen += wraparound_y; //second pass check if (x_screen < -8 || x_screen >= this.SCREEN_WIDTH || y_screen < -8 || y_screen >= this.SCREEN_HEIGHT) isOffScreen = true; } if (!isOffScreen) { let nametable_offset = 0; if (nameTable == 1) { //TODO implement proper single screen //mirroring - currently doing special //case for mapper 7 - fix for jeopardy if (this.cartridge.mirroring == Mirroring.VERTICAL || this.cartridge.mapperType==7) nametable_offset += 0x400; else nametable_offset += 0x800; } let byte = this.ppu.readVRAM(0x2000 + nametable_offset + nameTableCounter); let offset = 0; if (this.ppu.pattern_background == 1) offset = 256 * 16; this.ppu.renderTile((byte * 16) + offset, x * 8, y * 8, this.SCREEN_MAIN, scrolladjust_x + wraparound_x, scrolladjust_y + wraparound_y, nameTableCounter, nameTable); } nameTableCounter++; } } } applyScreenBuffers() { this.canvasImage.data.set(this.SCREEN_MAIN.pixel_data); this.canvas_ctx.putImageData(this.canvasImage, 0, 0); if (this.DEBUGMODE) { this.canvasDebug_Image.data.set(this.SCREEN_DEBUG.pixel_data); this.canvasDebug_ctx.putImageData(this.canvasDebug_Image, 0, 0); } } drawDebugScreen() { let x = 0, y = 0; //DRAW SECOND NAMETABLE if (this.debug_view_nametable) { let nameTableCounter = 0; for (let y = 0; y < 30; y++) { for (let x = 0; x < 32; x++) { let nametable_offset = 0; if (this.debugNametable == 1) { if (this.cartridge.mirroring == Mirroring.VERTICAL) nametable_offset += 0x400; else nametable_offset += 0x800; } let byte = this.ppu.readVRAM(0x2000 + nametable_offset + nameTableCounter); let offset = 0; if (this.ppu.pattern_background == 1) offset = 256 * 16; this.ppu.renderTile((byte * 16) + offset, x * 8, (y * 8), this.SCREEN_DEBUG, 0, 0, nameTableCounter, this.debugNametable); nameTableCounter++; } } } if (this.debug_view_chr) { //DRAW FULL PALETTE //EXPENSIVE // for (let i = 0; i < this.ppu.palette.length; i++) { // this.SCREEN_DEBUG.drawSquareOnBuffer(x * 20, y * 20, 20, this.ppu.palette[i]); // //move to next row // x++; // if (x == 16) { // x = 0; // y++; // } // } //DRAW CHR SPRITES x = 0; y = 150; for (let i = 0; i < 256; i++) { this.ppu.renderTile(i * 16, x, y, this.SCREEN_DEBUG, 0, 0); x += 8; if (x == 8 * 16) { x = 0; y += 8; } } x = 0; y = 150; for (let i = 256; i < 512; i++) { this.ppu.renderTile(i * 16, x + 128, y, this.SCREEN_DEBUG, 0, 0); x += 8; if (x == 8 * 16) { x = 0; y += 8; } } } //DRAW CURRENT PALETTES y = 285 for (let i = 0; i < 32; i++) { this.SCREEN_DEBUG.drawSquareOnBuffer(i * 10, y, 10, this.ppu.getPaletteColor(i)); } } stepDebugMode() { if (this.nestestlogmode) this.compareNesTestLog(); this.cpu.clock(); //ppu is clocked at 3 times the speed of the cpu this.ppu.clock(); // this.ppu.clock(); // this.ppu.clock(); } compareNesTestLog() { if (this.nestestlogmode) { this.nestestframecounter++; //only do 60 a frame rather than the usual 30,000 frame cycles if (this.nestestframecounter>60) { this.ppu.frame_complete = true; this.nestestframecounter = 0; } //check address var compare1 = this.nestestlog[this.nestestcounter]; var compare2 = this.cpu.PC.toString(16).toUpperCase(); //pad with zeroes so it lines up if (compare2.length == 3) compare2 = '0' + compare2; if (compare1 == compare2) { console.log(this.nestestcounter + ') matches: ' + compare1 + ' ' + compare2); } else { console.log('ADDRESS does not match epected(' + compare1 + ') received (' + compare2 + ')'); this.PAUSED = true; } //check status compare1 = this.nestestlogstatus[this.nestestcounter]; compare2 = this.cpu.STATUS.toString(16).toUpperCase(); if (compare1 == compare2) { // this.nestestcounter++; // console.log('matches: ' + compare1 + ' ' + compare2); } else { console.log('STATUS does not match epected(' + compare1 + ') received (' + compare2 + ')'); this.PAUSED = true; } this.nestestcounter++; } } drawDebugInfo() { let program_current_location = 0x8000; let program = ''; let memory = ''; let stats = ''; let soundStats = ''; //draw memory // Program Counter // current_page = this.cpu.PC - (this.cpu.PC % 256); // for (let i = 0; i < 16; i++) { // memory += '$' + current_page.toString(16) + ': '; // for (let j = 0; j < 16; j++) { // let byte = this.memory.read(current_page).toString(16) + ' '; // if (byte.length == 2) // byte = '0' + byte; // if (current_page == this.cpu.PC) // byte = "<b style='background-color: yellow;'>" + byte + '</b>'; // memory += byte; // current_page++;; // } // memory += '<br>'; // } // Zero Page program_current_location = this.debugMemPage; for (let i = 0; i < 16; i++) { if (program_current_location.toString(16).length == 1) memory += '$0' + program_current_location.toString(16) + ': '; else memory += '$' + program_current_location.toString(16) + ': '; for (let j = 0; j < 16; j++) { let byte = this.memory.read(program_current_location).toString(16) + ' '; if (byte.length == 2) byte = '0' + byte; if (program_current_location == this.cpu.PC) byte = "<b style='background-color: yellow;'>" + byte + '</b>'; memory += byte; program_current_location++;; } memory += '<br>'; } //draw stats stats += 'PC: ' + this.cpu.PC.toString(16) + '<br>'; stats += 'A: ' + this.cpu.A.toString(16) + '<br>'; stats += 'X: ' + this.cpu.X.toString(16) + '<br>'; stats += 'Y: ' + this.cpu.Y.toString(16) + '<br>'; stats += 'Next Instruction: ' + this.cpu.next_op + '<br>'; stats += 'Next Address Mode: ' + this.cpu.next_addressmode + '<br>'; stats += 'STACK: ' + this.cpu.STACK.toString(16) + '<br>'; stats += 'STATUS: C-' + this.cpu.getFlag(this.cpu.FLAG_C) + ' Z-' + this.cpu.getFlag(this.cpu.FLAG_Z) + ' I-' + this.cpu.getFlag(this.cpu.FLAG_I) + ' D-' + this.cpu.getFlag(this.cpu.FLAG_D) + ' B-' + this.cpu.getFlag(this.cpu.FLAG_B) + ' U-' + this.cpu.getFlag(this.cpu.FLAG_U) + ' V-' + this.cpu.getFlag(this.cpu.FLAG_V) + ' N-' + this.cpu.getFlag(this.cpu.FLAG_N) + '<BR>'; stats += 'Scanline: ' + this.ppu.scanline + '<br>'; stats += 'Tick: ' + this.ppu.tick + '<br>'; // stats += 'Nametable X: ' + this.ppu.nametable_x + '<br>'; // stats += 'Nametable Y: ' + this.ppu.nametable_y + '<br>'; //don't crash on sound stats if (this.apu._soundDisabled == false) { let square1Equalizer = ''; let square1Amount = 0; if (this.apu.square1.tone.volume.value > -100) { let equalizerCount = Math.floor(this.apu.square1.debugCurrentFrequency / 50); if (equalizerCount > 20) equalizerCount = 20; for (let i = 0; i < equalizerCount; i++) square1Equalizer += '*'; square1Amount = Math.floor(this.apu.square1.debugCurrentFrequency / 2); if (square1Amount > 400) square1Amount = 400; } stats += 'Square1: ' + square1Equalizer + '<br>'; let square2Equalizer = ''; let square2Amount = 0; if (this.apu.square2.tone.volume.value > -100) { let equalizerCount = Math.floor(this.apu.square2.debugCurrentFrequency / 50); if (equalizerCount > 20) equalizerCount = 20; for (let i = 0; i < equalizerCount; i++) square2Equalizer += '*'; square2Amount = Math.floor(this.apu.square2.debugCurrentFrequency / 2); if (square2Amount > 400) square2Amount = 400; } stats += 'Square2: ' + square2Equalizer + '<br>'; let triangleEqualizer = ''; let triangleAmount = 0; if (this.apu.triangle.tone.volume.value > -100) { let equalizerCount = Math.floor(this.apu.triangle.debugCurrentFrequency / 50); if (equalizerCount > 20) equalizerCount = 20; for (let i = 0; i < equalizerCount; i++) triangleEqualizer += '*'; triangleAmount = Math.floor(this.apu.triangle.debugCurrentFrequency / 2); if (triangleAmount > 400) triangleAmount = 400; } stats += 'Triangl: ' + triangleEqualizer + '<br>'; this.debugSquare1Visual = "<div style='border-color: black;background-color:lightskyblue;width:" + square1Amount + "px;height:60px;'></div>"; this.debugSquare2Visual = "<div style='border-color: black;background-color:lightskyblue;width:" + square2Amount + "px;height:60px;'></div>"; this.debugTriangleVisual = "<div style='border-color: black;background-color:lightskyblue;width:" + triangleAmount + "px;height:60px;'></div>"; let note1 = Note.getNote(square1Amount); let note2 = Note.getNote(square2Amount); let note3 = Note.getNote(triangleAmount); if (note1!='') this.debugSquare1Note = note1; if (note2!='') this.debugSquare2Note = note2; if (note3!='') this.debugTriangleNote = note3; // soundStats = // 'Square1 Frequency: ' + this.apu.square1.debugCurrentFrequency +'<br>' + // 'Square2 Frequency: ' + this.apu.square2.debugCurrentFrequency +'<br>' + // 'Triangl Frequency: ' + this.apu.triangle.debugCurrentFrequency +'<br>'; // stats += 'Bank0offset: ' + this.memory.prgBank0offset + '<br>'; // stats += 'Bank1offset: ' + this.memory.prgBank1offset + '<br>'; // stats += 'Bank2offset: ' + this.memory.prgBank2offset + '<br>'; // stats += 'Bank3offset: ' + this.memory.prgBank3offset + '<br>'; let vol1 = this.apu.square1.volume; if (vol1==-100) vol1 = 0; else vol1 = vol1-this.apu.square1.SQUARE_VOLUME + 15; let vol2 = this.apu.square2.volume; if (vol2==-100) vol2 = 0; else vol2 = vol2-this.apu.square2.SQUARE_VOLUME + 15; let vol3 = this.apu.triangle.volume; if (vol3==-100) vol3 = 0; else vol3 = 15; let vol4 = this.apu.noise.volume; if (vol4==-100) vol4 = 0; else vol4 = vol4-this.apu.noise.NOISE_VOLUME + 15; soundStats = 'Square1 Volume: ' + vol1 +'<br>' + 'Square1 Frequency: ' + this.apu.square1.debugCurrentFrequency +'<br>' + 'Square2 Volume: ' + vol2 +'<br>' + 'Square2 Frequency: ' + this.apu.square2.debugCurrentFrequency +'<br>' + 'Triangle Volume: ' + vol3 +'<br>' + 'Triangle Frequency: ' + this.apu.triangle.debugCurrentFrequency +'<br>' + 'Noise Volume: ' + vol4 +'<br>'; } // stats += 'Sprite Size: ' + this.ppu.sprite_size + '<br>'; // switch(this.cartridge.mirroring){ // case Mirroring.HORIZONTAL: // stats += 'Mirroring: HORIZONTAL<br>'; break; // case Mirroring.VERTICAL: // stats += 'Mirroring: VERTICAL<br>'; break; // } // stats += 'Square1: ' + Math.floor(this.apu.square1.debugCurrentFrequency) + '<br>'; // stats += 'Square2: ' + Math.floor(this.apu.square2.debugCurrentFrequency) + '<br>'; // stats += 'Triangl: ' + Math.floor(this.apu.triangle.debugCurrentFrequency) + '<br>'; // stats += 'Square2 Sweep Mode: ' + this.apu.square2.sweepMode + '<br>'; // stats += 'Square2 Frequency: ' + Math.floor(this.apu.square2.debugCurrentFrequency) + '<br>'; // stats += 'Square2 Length Counter Halt: ' + this.apu.square2.lengthCounterHalt + '<br>'; // stats += 'Square2 Constant Volume: ' + this.apu.square2.constantVolume + '<br>'; // stats += 'Square2 Length Counter: ' + this.apu.square2.lengthCounter + '<br>'; // stats += 'Square2 Sweep Mode: ' + this.apu.square2.sweepMode + '<br>'; // stats += 'Square2 Frequency: ' + Math.floor(this.apu.square2.debugCurrentFrequency) + '<br>'; // stats += 'Sprite 0 X: ' + this.ppu.oam[3] + '<br>'; // stats += 'Sprite 0 Y: ' + this.ppu.oam[0] + '<br>'; // stats += 'greyscale: ' + this.ppu.greyscale + '<br>'; // stats += 'show_background_leftmost: ' + this.ppu.show_background_leftmost + '<br>'; // stats += 'show_sprites_leftmost: ' + this.ppu.show_sprites_leftmost + '<br>'; // stats += 'show_background: ' + this.ppu.show_background + '<br>'; // stats += 'show_sprites: ' + this.ppu.show_sprites + '<br>'; // stats += 'emphasize_red: ' + this.ppu.emphasize_red + '<br>'; // stats += 'emphasize_green: ' + this.ppu.emphasize_green + '<br>'; // stats += 'emphasize_blue: ' + this.ppu.emphasize_blue + '<br>'; // stats += 'Left: ' + this.inputController.Key_Left + '<br>'; // stats += 'Right: ' + this.inputController.Key_Right + '<br>'; // stats += 'Start: ' + this.inputController.Key_Action_Start + '<br>'; // stats += 'NESTEST Counter: ' + this.nestestcounter + ' / ' + this.nestestlog.length + '<br>'; // stats += 'Cycle Count: ' + this.cpu.allcyclecount + '<br>'; // stats += 'Cycles Left: ' + this.cpu.cycles + '<br>'; // stats += 'Last Address: ' + this.cpu.last_address + '<br>'; // stats += 'Last Read: ' + this.cpu.last_read + '<br>'; this.debugProgram = program; this.debugMemory = memory; this.debugStats = stats; this.debugSoundStats = soundStats; } recordMusicMode = false; recordMusicArray: number[] = []; playBackMusicMode = false; playBackMusicCounter = 0; startRecordingMusic() { console.log('recording started'); this.recordMusicArray = []; this.recordMusicMode = true; } stopRecordingMusic() { this.recordMusicMode = false; localStorage.setItem('nes-music', this.recordMusicArray.toString()); console.log('recording saved'); } processRecordMusic() { if (this.recordMusicMode) { if (this.apu.square1.tone.volume.value > -100) this.recordMusicArray.push(Math.floor(this.apu.square1.debugCurrentFrequency)); else this.recordMusicArray.push(0); if (this.apu.square2.tone.volume.value > -100) this.recordMusicArray.push(Math.floor(this.apu.square2.debugCurrentFrequency)); else this.recordMusicArray.push(0); if (this.apu.triangle.tone.volume.value > -100) this.recordMusicArray.push(Math.floor(this.apu.triangle.debugCurrentFrequency)); else this.recordMusicArray.push(0); } if (this.playBackMusicMode) { let square1note = this.recordMusicArray[this.playBackMusicCounter]; let square2note = this.recordMusicArray[this.playBackMusicCounter + 1]; let trianglenote = this.recordMusicArray[this.playBackMusicCounter + 2]; this.apu.square1.tone.frequency.value = square1note; this.apu.square1.debugCurrentFrequency = square1note; if (square1note != 0) { this.apu.square1.tone.volume.value = this.apu.square1.SQUARE_VOLUME; this.apu.square1.start(); } else this.apu.square1.stop(); this.apu.square2.tone.frequency.value = square2note; this.apu.square2.debugCurrentFrequency = square2note; if (square2note != 0) { this.apu.square2.tone.volume.value = this.apu.square2.SQUARE_VOLUME; this.apu.square2.start(); } else this.apu.square2.stop(); this.apu.triangle.tone.frequency.value = trianglenote; this.apu.triangle.debugCurrentFrequency = trianglenote; if (trianglenote != 0) { this.apu.triangle.tone.volume.value = this.apu.triangle.TRIANGLE_VOLUME; this.apu.triangle.start(); } else this.apu.triangle.stop(); this.playBackMusicCounter += 3; if (this.playBackMusicCounter == this.recordMusicArray.length) this.stopPlaybackMusic(); } } stopPlaybackMusic() { this.playBackMusicMode = false; this.apu.square1.stop(); this.apu.square2.stop(); this.apu.triangle.stop(); } playRecordedMusic() { let musicString = localStorage.getItem('nes-music'); let musicArray = musicString.split(','); let musicArrayNums: number[] = []; musicArray.forEach(note => { musicArrayNums.push(parseFloat(note)); }); this.recordMusicArray = musicArrayNums; this.playBackMusicMode = true; this.playBackMusicCounter = 0; this.apu.unMuteAll() } // startCounter1 = false; // startCounter2 = false; // startCounter3 = false; // smb3StartHack = false; // smb3hackCounter = 0; // smb3Hack(){ // if (this.inputController.Key_Action_Start && this.startCounter1==false){ // this.startCounter1 = true; // console.log('start counter 1'); // } // if (this.startCounter1 && this.inputController.Key_Action_Start==false && this.startCounter2==false){ // this.startCounter2 = true; // console.log('start counter 2'); // } // if (this.startCounter2 && this.inputController.Key_Action_Start==true && this.startCounter3==false){ // this.startCounter3 = true; // console.log('start counter 3'); // this.smb3StartHack=true; // } // } }
the_stack
import { withSlots, stagedComponent } from '@fluentui-react-native/use-slot'; import { mergeProps } from '@fluentui-react-native/merge-props'; import { buildUseSlots } from './buildUseSlots'; import toJson from 'enzyme-to-json'; import { mount } from 'enzyme'; import { CSSProperties } from 'react'; // types for web type TextProps = { style?: CSSProperties }; type ViewProps = { style?: CSSProperties }; type ViewStyle = CSSProperties; type TextStyle = CSSProperties; /** * This file contains samples and description to help explain what the useSlots hook does and why it is useful * for building components. */ describe('useSlots sample code test suite', () => { /** * The first mechanism to understand is the stagedComponent mechanic. This allows a component to be written, separating * hook calls and component rendering. This allows it to be safely called as a function by a higher order component, even conditionally. */ /** * Example #1: Single level simple component ---------------------------------------- * * First we are going to create a wrapped text component that bolds all text. One component will be authored as a staged * component and one as a regular component. */ const boldBaseProps: TextProps = { style: { fontWeight: 900 } }; /** * First create the bold text in the standard way. This is just a function component. */ const BoldTextStandard: React.FunctionComponent<TextProps> = (props: React.PropsWithChildren<TextProps>) => { /** * Pick out the children to pass them on to the child Text element */ const { children, ...rest } = props; /** * Now render the text, merging the baseProps with the style updates with the rest param. Note that this leverages the fact * that mergeProps will reliably produce style objects with the same reference, given the same inputs. */ return <span {...mergeProps(boldBaseProps, rest)}>{children}</span>; }; BoldTextStandard.displayName = 'BoldTextStandard'; /** * To write the same component using the staged pattern is only slightly more complex. The pattern involves splitting the component rendering into * two parts and executing any hooks in the first part. * * The stagedComponent function takes an input function of this form and wraps it in a function component that react knows how to render */ const BoldTextStaged = stagedComponent((props: TextProps) => { /** * This section would be where hook/styling code would go, props here would include everything coming in from the base react tree with the * exception of children, which will be passed in stage 2. */ return (extra: TextProps, children: React.ReactNode) => { /** * extra are additional props that may be filled in by a higher order component. They should not include styling and are only props the * enclosing component are passing to the JSX elements */ return <span {...mergeProps(boldBaseProps, props, extra)}>{children}</span>; }; }); BoldTextStaged.displayName = 'BoldTextStaged'; /** * The demos of the code use enzyme with JSDom to show the full tree. This has the side effect of doubling up primitive elements in the output * JSON. This is an issue with rendering react-native with enzyme but in real usage the nodes only render once. */ it('renders sample 1 - the two types of basic bold text components', () => { const styleToMerge: TextStyle = { color: 'black' }; /** * First render the staged component. This invokes the wrapper that was built by the stagedComponent function */ const wrapper = mount( <div> <BoldTextStaged style={styleToMerge}>Staged component at one level</BoldTextStaged> <BoldTextStandard style={styleToMerge}>Standard component of a single level</BoldTextStandard> </div>, ); expect(toJson(wrapper)).toMatchSnapshot(); }); /** * Example #2 - Simple component containing another simple component ------------------------------------- * * Next we will build a layer on top of the previously authored components to turn the bold text components into header components. This is * to illustrate the way in which components can be commonly built on top of other simpler components. */ const headerBaseProps: TextProps = { style: { fontSize: 20 } }; /** * The standard way of doing things is a repeat of what happens above. Grab the children, pass them on, merge the rest of the props with * base props. * * This again leverages style merging via mergeProps to avoid changing the references of the style objects on every render */ const HeaderStandard: React.FunctionComponent<TextProps> = (props) => { const { children, ...rest } = props; return <BoldTextStandard {...mergeProps(headerBaseProps, rest)}>{children}</BoldTextStandard>; }; HeaderStandard.displayName = 'HeaderStandard'; /** * To consume the staged component we'll use the use slots hook builder. This allows easy consumption of staged components (or standard components) * This will be described in more detail further on but in this case the component has a single child component, so it only has one slot that we * will call 'text' * * This should be built once, and consumed by the component, not built on the fly inside */ const useHeaderSlots = buildUseSlots({ slots: { text: BoldTextStaged } }); /** * Now author the staged component using the slot hook */ const HeaderStaged = stagedComponent((props: TextProps) => { /** * Call the slots hook (or any hook) outside of the inner closure. The useSlots hook will return an object with each slot as a renderable * function. The hooks for sub-components will be called as part of this call. Props passed in at this point will be the props that appear * in outer part of the staged component. (For this example `props`) * * Note that while we are passing in props, in the simple usage case it isn't used and could be omitted if desired * */ const BoldText = useHeaderSlots(props).text; /** Now the inner closure, pretty much the same as before */ return (extra: TextProps, children: React.ReactNode) => { /** * Instead of rendering the <BoldTextStageed> component directly we render using the slot. If this is a staged component it will call the * inner closure directly, without going through createElement. Entries passed into the JSX, including children, are what appear in the * props of the inner closure. (In this example `extra`) * * NOTE: this requires using the withSlots helper via the jsx directive. This knows how to pick apart the entries and just call the second * part of the function */ return <BoldText {...mergeProps(headerBaseProps, props, extra)}>{children}</BoldText>; }; }); HeaderStaged.displayName = 'HeaderStaged'; /** * Look at the snapshots to compare the rendered output. The staged component will skip the intermediate levels of the react hieararchy while * still rendering to the correct primitives. */ it('renders sample 2 = the two types of two level header components', () => { const styleToMerge: TextStyle = { color: 'black' }; /** * First render the staged component. This invokes the wrapper that was built by the stagedComponent function */ const wrapper = mount( <div> <HeaderStaged style={styleToMerge}>Staged component with two levels</HeaderStaged> <HeaderStandard style={styleToMerge}>Standard component with two levels</HeaderStandard> </div>, ); expect(toJson(wrapper)).toMatchSnapshot(); }); /** * Example #3: Complex components built using useSlots -------------------------------------------------------------------- * * We'll build a component that shows two labels, a header and a caption, embedded inside a view */ type HeaderWithCaptionProps = ViewProps & { headerColor?: string; captionColor?: string; captionText?: string }; /** standard props for the container */ const containerProps: ViewProps = { style: { display: 'flex', flexDirection: 'column' } }; /** * add a quick cache to ensure that we don't thrash the styles. This is a danger any time a value from a style is added as * a prop on a component */ const colorProps = {}; const getColorProps = (value?: string) => { if (value !== undefined) { colorProps[value] = colorProps[value] || { style: { color: value } }; return colorProps[value]; } return {}; }; /** * now just create the component like a standard react functional component */ const CaptionedHeaderStandard: React.FunctionComponent<HeaderWithCaptionProps> = (props) => { const { headerColor, captionColor, captionText, children, ...rest } = props; const headerColorProps = getColorProps(headerColor); const captionColorProps = getColorProps(captionColor); return ( <div {...mergeProps(containerProps, rest)}> <HeaderStandard {...headerColorProps}>{children}</HeaderStandard> {captionText && <BoldTextStandard {...captionColorProps}>{captionText}</BoldTextStandard>} </div> ); }; CaptionedHeaderStandard.displayName = `CaptionedHeaderStandard';`; /** * now build the same component using slots hook. This will also add use of the style injection pattern */ const useCaptionedHeaderSlots = buildUseSlots({ /** Slots are just like above, this component will have three sub-components */ slots: { container: 'div', header: HeaderStaged, caption: BoldTextStaged, }, /** useStyling is an optional function that turns props into props for the sub-components */ useStyling: (props: HeaderWithCaptionProps) => ({ container: containerProps, header: getColorProps(props.headerColor), caption: getColorProps(props.captionColor), }), }); /** a mask to clear props that we don't want to pass to the inner view */ const clearCustomProps = { headerColor: undefined, captionColor: undefined }; /** * now use the hook to implement it as a staged component */ const CaptionedHeaderStaged = stagedComponent<HeaderWithCaptionProps>((props) => { // At the point where this is called the slots are initialized with the initial prop values from useStyling above const Slots = useCaptionedHeaderSlots(props); return (extra: HeaderWithCaptionProps, children: React.ReactNode) => { // merge the props together, picking out the caption text and clearing any custom values we don't want forwarded to the view const { captionText, ...rest } = mergeProps(props, extra, clearCustomProps); // now render using the slots. Any values passed in via JSX will be merged with values from the slot hook above return ( <Slots.container {...rest}> <Slots.header>{children}</Slots.header> {captionText && <Slots.caption>{captionText}</Slots.caption>} </Slots.container> ); }; }); CaptionedHeaderStaged.displayName = 'CaptionedHeaderStaged'; /** * Render to enzyme snapshots */ it('renders sample 3 - the two types of higher order header components', () => { const styleToMerge: ViewStyle = { backgroundColor: 'gray', borderColor: 'purple', borderWidth: 1 }; /** * Render the two sets of components. Note in the snapshots how the render tree layers for the standard approach are starting * to add up. */ const wrapper = mount( <div> <span>--- SIMPLE USAGE COMPARISON ---</span> <CaptionedHeaderStandard style={styleToMerge}>Standard HOC</CaptionedHeaderStandard> <CaptionedHeaderStaged style={styleToMerge}>Staged HOC</CaptionedHeaderStaged> <span>--- COMPARISON WITH CAPTIONS ---</span> <CaptionedHeaderStandard style={styleToMerge} captionText="Caption text"> Standard HOC with Caption </CaptionedHeaderStandard> <CaptionedHeaderStaged style={styleToMerge} captionText="Caption text"> Staged HOC with Caption </CaptionedHeaderStaged> <span>--- COMPARISON WITH CAPTIONS AND CUSTOMIZATIONS ---</span> <CaptionedHeaderStandard style={styleToMerge} captionText="Caption text" captionColor="yellow" headerColor="red"> Standard HOC with caption and customizations </CaptionedHeaderStandard> <CaptionedHeaderStaged style={styleToMerge} captionText="Caption text" captionColor="yellow" headerColor="red"> Staged HOC with caption and customizations </CaptionedHeaderStaged> </div>, ); expect(toJson(wrapper)).toMatchSnapshot(); }); });
the_stack
import { Browser, EventHandler, createElement, EmitType } from '@syncfusion/ej2-base'; import { ILoadedEventArgs, ILoadEventArgs } from '../../src/linear-gauge/model/interface'; import { LinearGauge } from '../../src/linear-gauge/linear-gauge'; import {profile , inMB, getMemoryProfile} from '../common.spec'; import { GaugeLocation } from '../../src'; describe('Linear gauge control', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('linear gauge direct properties', () => { let gauge: LinearGauge; let element: HTMLElement; let svg: HTMLElement; beforeAll((): void => { element = createElement('div', { id: 'container' }); document.body.appendChild(element); gauge = new LinearGauge(); gauge.appendTo('#container'); }); afterAll((): void => { element.remove(); }); it('checking with marker pointer', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.refresh(); }); it('checking with bar pointer', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_BarPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].type = 'Bar'; gauge.refresh(); }); it('checking with marker pointer in Triangle', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Triangle'; gauge.refresh(); }); it('checking with marker pointer in Diamond', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].markerType = 'Diamond'; gauge.refresh(); }); it('checking with marker pointer in Rectangle', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].markerType = 'Rectangle'; gauge.refresh(); }); it('checking with marker pointer in InvertedTriangle', (done:Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); done(); }; gauge.axes[0].pointers[0].markerType = 'InvertedTriangle'; gauge.refresh(); }); it('checking with marker pointer in Circle', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking with marker pointer in InvertedTriangle', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].markerType = 'Image'; gauge.axes[0].pointers[0].imageUrl = 'http://js.syncfusion.com/demos/web/content/images/chart/sun_annotation.png'; gauge.refresh(); }); it('checking with marker pointer animation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].value = 50; gauge.axes[0].pointers[0].animationDuration = 2000; gauge.refresh(); }); it('checking with marker pointer animation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_BarPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].type = 'Bar'; gauge.axes[0].pointers[0].value = 70; gauge.axes[0].pointers[0].animationDuration = 4000; gauge.refresh(); }); it('checking with marker pointer with databind', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_BarPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].value = 50; gauge.dataBind(); }); it('checking with marker pointer fill', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg !== null).toBe(true); }; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.axes[0].pointers[0].color = 'red'; gauge.axes[0].pointers[0].value = 70; gauge.refresh(); }); it('checking with marker pointer stroke', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg !== null).toBe(true); }; gauge.axes[0].pointers[0].border.color = 'green'; gauge.refresh(); }); it('checking with marker pointer stoke width', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg !== null).toBe(true); }; gauge.axes[0].pointers[0].border.width = 5; gauge.refresh(); }); it('checking with marker pointer placement center', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Center'; gauge.refresh(); }); it('checking with marker pointer placement far', (done:Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); done(); }; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Far'; gauge.refresh(); }); it('checking with marker pointer placement as center in opposed position', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Center'; gauge.refresh(); }); it('checking with marker pointer placement far in opposed position', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Far'; gauge.refresh(); }); it('checking with poineter placement as near', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Near'; gauge.refresh(); }); it('checking with poineter placement as Center', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Center'; gauge.refresh(); }); it('checking with poineter placement as Center', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Far'; gauge.refresh(); }); it('checking with poineter placement as near in opposed position', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.axes[0].opposedPosition = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Near'; gauge.refresh(); }); it('checking with poineter placement as Center in opposed position', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.axes[0].opposedPosition = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Center'; gauge.refresh(); }); it('checking with poineter placement as Center in opposed position', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.axes[0].opposedPosition = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].placement = 'Far'; gauge.refresh(); }); it('checking with multiple marker pointers', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); svg = document.getElementById('container_AxisIndex_0_MarkerPointer_1'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers = [{ value: 50 }, { value: 80 } ]; gauge.refresh(); gauge.axes[0].pointers = [{},{}]; }); // it('checking with bar into the container in vertical orientation', () => { // gauge.loaded = (args: ILoadedEventArgs): void => { // svg = document.getElementById('container_AxisIndex_0_BarPointer_0'); // //expect(svg != null).toBe(true); // }; // gauge.container.width = 40; // gauge.orientation = 'Vertical'; // gauge.axes[0].pointers[0].type = 'Bar'; // gauge.refresh(); // }); // it('checking with bar in vertical orientation', () => { // gauge.loaded = (args: ILoadedEventArgs): void => { // svg = document.getElementById('container_AxisIndex_0_BarPointer_0'); // expect(svg != null).toBe(true); // }; // gauge.container.width = 0; // gauge.orientation = 'Vertical'; // gauge.axes[0].opposedPosition = true; // gauge.axes[0].pointers[0].type = 'Bar'; // gauge.refresh(); // }); it('checking with bar into the container in horizontal orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_BarPointer_0'); expect(svg != null).toBe(true); }; gauge.container.width = 0; gauge.orientation = 'Horizontal'; gauge.axes[0].opposedPosition = false; gauge.axes[0].pointers[0].type = 'Bar'; gauge.refresh(); }); it('checking with pointer circle in near position', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = false; gauge.axes[0].pointers[0].placement = 'Near'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking with pointer circle in axis opposed position', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.axes[0].pointers[0].placement = 'Near'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking with pointer circle in center placement', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.axes[0].pointers[0].placement = 'Center'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking with pointer circle in far placement', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = false; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Far'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking with pointer circle in horizontal orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = false; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Far'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking with pointer diamond in horizontal orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = false; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Far'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Diamond'; gauge.refresh(); }); it('checking with pointer diamond in vertical orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].placement = 'Near'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Diamond'; gauge.refresh(); }); it('checking with diamond pointer in horizontal orientation in near plcement', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = false; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Near'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Diamond'; gauge.refresh(); }); it('checking with diamond pointer in near plcement', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Near'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Diamond'; gauge.refresh(); }); it('checking with diamond pointer in center plcement', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Center'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Diamond'; gauge.refresh(); }); it('checking with rectangle pointer in near plcement', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Center'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Rectangle'; gauge.refresh(); }); it('checking with rectangle pointer in vertical orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].placement = 'Near'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Rectangle'; gauge.refresh(); }); it('checking with rectangle pointer in far placement', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = false; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Far'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Rectangle'; gauge.refresh(); }); it('checking with rectangle pointer in center placement', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = false; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Center'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Rectangle'; gauge.refresh(); }); it('checking with rectangle pointer in axis opposed position', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); // expect(svg != null).toBe(true); }; gauge.axes[0].opposedPosition = true; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].placement = 'Near'; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Rectangle'; gauge.refresh(); }); }); describe('Axis pointer position based on position property', () => { let gauge: LinearGauge; let ele: HTMLElement; let direction: string; let boundingRect: ClientRect; let boundingRect1: ClientRect; let svg: HTMLElement; let value: string[] | string | number; let value1: string[] | string | number; beforeAll((): void => { ele = createElement('div', { id: 'gauge' }); document.body.appendChild(ele); gauge = new LinearGauge({ orientation : "Horizontal", axes: [{ pointers: [ { value: 50, markerType: 'Triangle', position: 'Inside', type: 'Marker' }, { type: 'Bar', value: 30, position: 'Inside' } ] }] }, '#gauge' ); }); afterAll((): void => { gauge.destroy(); ele.remove(); }); it('Checking pointer position as inside', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '384.5' || value[1] == '379' || value[1] == '381.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('204'); done(); }; gauge.refresh(); }); it('Checking pointer position as inside with opposed', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '384.5' || value[1] == '379' || value[1] == '381.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('226'); done(); }; gauge.axes[0].opposedPosition = true; gauge.refresh(); }); it('Checking pointer position as outside', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '384.5' || value[1] == '379' || value[1] == '381.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('226'); done(); }; gauge.axes[0].opposedPosition = false; gauge.axes[0].pointers[0].position = 'Outside'; gauge.axes[0].pointers[1].position = 'Outside'; gauge.refresh(); }); it('Checking pointer position as outside and opposed', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '384.5' || value[1] == '379' || value[1] == '381.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('204'); done(); }; gauge.axes[0].opposedPosition = true; gauge.refresh(); }); it('Checking pointer position as cross', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '384.5' || value[1] == '379' || value[1] == '381.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('215'); done(); }; gauge.axes[0].opposedPosition = false; gauge.axes[0].pointers[0].position = 'Cross'; gauge.axes[0].pointers[1].position = 'Cross'; gauge.refresh(); }); it('Checking pointer position as inside with vertical orientation', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '383.5' || value[1] == '378' || value[1] == '380.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('289.5'); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].position = 'Inside'; gauge.axes[0].pointers[1].position = 'Inside'; gauge.refresh(); }); it('Checking pointer position as inside with opposed with vertical orientation', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '385.5' || value[1] == '380' || value[1] == '382.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('289.5'); done(); }; gauge.axes[0].opposedPosition = true; gauge.refresh(); }); it('Checking pointer position as outside with vertical orientation', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '385.5' || value[1] == '380' || value[1] == '382.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('289.5'); done(); }; gauge.axes[0].opposedPosition = false; gauge.axes[0].pointers[0].position = 'Outside'; gauge.axes[0].pointers[1].position = 'Outside'; gauge.refresh(); }); it('Checking pointer position as outside and opposed with vertical orientation', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '383.5' || value[1] == '378' || value[1] == '380.5').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('289.5'); done(); }; gauge.axes[0].opposedPosition = true; gauge.refresh(); }); it('Checking pointer position as cross with vertical orientation', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { let svgNode: NodeListOf<Element> = document.querySelectorAll('path#gauge_AxisIndex_0_MarkerPointer_0'); value = svgNode[0].getAttribute('d').split(' '); expect(value[1] == '336.05' || value[1] == '331.1' || value[1] == '333.35').toBe(true); let svgNode1: NodeListOf<Element> = document.querySelectorAll('rect#gauge_AxisIndex_0_BarPointer_1'); expect(svgNode1[0].getAttribute('y')).toBe('289.5'); done(); }; gauge.axes[0].opposedPosition = false; gauge.axes[0].pointers[0].offset = '10%'; gauge.axes[0].pointers[1].offset = '10%'; gauge.axes[0].pointers[0].position = 'Cross'; gauge.axes[0].pointers[1].position = 'Cross'; gauge.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import {assert, assertInstanceof} from '../assert.js'; import * as dom from '../dom.js'; import {Box, Line, Point, Size, Vector, vectorFromPoints} from '../geometry.js'; import {I18nString} from '../i18n_string.js'; import {speak} from '../toast.js'; import {Rotation, ViewName} from '../type.js'; import * as util from '../util.js'; import {Option, Options, Review} from './review.js'; /** * Delay for movement announcer gathering user pressed key to announce first * feedback in milliseconds. */ const MOVEMENT_ANNOUNCER_START_DELAY_MS = 500; /** * Interval for movement announcer to announce next movement. */ const MOVEMENT_ANNOUNCER_INTERVAL_MS = 2000; /** * Maps from sign of x, y movement to corresponding i18n labels to be announced. */ const MOVEMENT_ANNOUNCE_LABELS = new Map([ [ -1, new Map<number, I18nString>([ [-1, I18nString.MOVING_IN_TOP_LEFT_DIRECTION], [0, I18nString.MOVING_IN_LEFT_DIRECTION], [1, I18nString.MOVING_IN_BOTTOM_LEFT_DIRECTION], ]), ], [ 0, new Map<number, I18nString>([ [-1, I18nString.MOVING_IN_TOP_DIRECTION], [1, I18nString.MOVING_IN_BOTTOM_DIRECTION], ]), ], [ 1, new Map<number, I18nString>([ [-1, I18nString.MOVING_IN_TOP_RIGHT_DIRECTION], [0, I18nString.MOVING_IN_RIGHT_DIRECTION], [1, I18nString.MOVING_IN_BOTTOM_RIGHT_DIRECTION], ]), ], ]); /** * Announces the movement direction of document corner with screen reader. */ class MovementAnnouncer { /** * Interval to throttle the consecutive announcement. */ private announceInterval: util.DelayInterval|null = null; /** * X component of last not announced movement. */ private lastXMovement = 0; /** * Y component of last not announced movement. */ private lastYMovement = 0; updateMovement(dx: number, dy: number) { this.lastXMovement = dx; this.lastYMovement = dy; if (this.announceInterval === null) { this.announceInterval = new util.DelayInterval(() => { this.announce(); }, MOVEMENT_ANNOUNCER_START_DELAY_MS, MOVEMENT_ANNOUNCER_INTERVAL_MS); } } private announce() { if (this.lastXMovement === 0 && this.lastYMovement === 0) { this.announceInterval.stop(); this.announceInterval = null; return; } const signX = Math.sign(this.lastXMovement); const signY = Math.sign(this.lastYMovement); speak(MOVEMENT_ANNOUNCE_LABELS.get(signX).get(signY)); this.lastXMovement = this.lastYMovement = 0; } } /** * The closest distance ratio with respect to corner space size. The dragging * corner should not be closer to the 3 lines formed by another 3 corners than * this ratio times scale of corner space size. */ const CLOSEST_DISTANCE_RATIO = 1 / 10; const ROTATIONS = [ Rotation.ANGLE_0, Rotation.ANGLE_90, Rotation.ANGLE_180, Rotation.ANGLE_270, ]; interface Corner { el: HTMLDivElement; pt: Point; pointerId: number|null; } /** * View controller for review document crop area page. */ export class CropDocument extends Review { private imageFrame: HTMLDivElement; /** * Size of image frame. */ private frameSize = new Size(0, 0); /** * The original size of the image to be cropped. */ private imageOriginalSize: Size|null = null; /** * Space size coordinates in |this.corners_|. Will change when image client * area resized. */ private cornerSpaceSize: Size|null = null; private cropAreaContainer: SVGElement; private cropArea: SVGPolygonElement; /** * Index of |ROTATION| as current photo rotation. */ private rotation = 0; private initialCorners: Point[]|null = null; private corners: Corner[]; constructor() { super(ViewName.CROP_DOCUMENT); this.imageFrame = dom.getFrom(this.root, '.review-frame', HTMLDivElement); this.cropAreaContainer = dom.getFrom(this.root, '.crop-area-container', SVGElement); this.cropArea = dom.getFrom(this.image, '.crop-area', SVGPolygonElement); /** * Coordinates of document with respect to |this.cornerSpaceSize_|. */ this.corners = (() => { const ret = []; for (let i = 0; i < 4; i++) { const tpl = util.instantiateTemplate('#document-drag-point-template'); ret.push({ el: dom.getFrom(tpl, `.dot`, HTMLDivElement), pt: new Point(0, 0), pointerId: null, }); this.image.appendChild(tpl); } return ret; })(); const updateRotation = (newRotation) => { this.rotation = newRotation; this.updateImage(); this.updateCornerElAriaLabel(); }; const clockwiseBtn = dom.getFrom( this.root, 'button[i18n-aria=rotate_clockwise_button]', HTMLButtonElement); clockwiseBtn.addEventListener('click', () => { updateRotation((this.rotation + 1) % ROTATIONS.length); }); const counterclockwiseBtn = dom.getFrom( this.root, 'button[i18n-aria=rotate_counterclockwise_button]', HTMLButtonElement); counterclockwiseBtn.addEventListener('click', () => { updateRotation((this.rotation + ROTATIONS.length - 1) % ROTATIONS.length); }); const cornerSize = (() => { const style = this.corners[0].el.computedStyleMap(); const width = util.getStyleValueInPx(style, 'width'); const height = util.getStyleValueInPx(style, 'height'); return new Size(width, height); })(); this.corners.forEach((corn) => { // Start dragging on one corner. corn.el.addEventListener('pointerdown', (e) => { e.preventDefault(); assert(e.target === corn.el); this.setDragging(corn, assertInstanceof(e, PointerEvent).pointerId); }); // Use arrow key to move corner. const KEYS = ['ArrowUp', 'ArrowLeft', 'ArrowDown', 'ArrowRight']; const getKeyIndex = (e) => KEYS.indexOf(assertInstanceof(e, KeyboardEvent).key); const KEY_MOVEMENTS = [ new Vector(0, -1), new Vector(-1, 0), new Vector(0, 1), new Vector(1, 0), ]; const pressedKeyIndices = new Set<number>(); let keyInterval = null; const clearKeydown = () => { if (keyInterval !== null) { keyInterval.stop(); keyInterval = null; } pressedKeyIndices.clear(); }; const announcer = new MovementAnnouncer(); corn.el.addEventListener('blur', () => { clearKeydown(); }); corn.el.addEventListener('keydown', (e) => { const keyIdx = getKeyIndex(e); if (keyIdx === -1 || pressedKeyIndices.has(keyIdx)) { return; } const move = () => { let announceMoveX = 0; let announceMoveY = 0; let moveX = 0; let moveY = 0; for (const keyIdx of pressedKeyIndices) { const announceMoveXY = KEY_MOVEMENTS[keyIdx]; announceMoveX += announceMoveXY.x; announceMoveY += announceMoveXY.y; const moveXY = KEY_MOVEMENTS[(keyIdx + this.rotation) % 4]; moveX += moveXY.x; moveY += moveXY.y; } announcer.updateMovement(announceMoveX, announceMoveY); const {x: curX, y: curY} = corn.pt; const nextPt = new Point(curX + moveX, curY + moveY); const validPt = this.mapToValidArea(corn, nextPt); if (validPt === null) { return; } corn.pt = validPt; this.updateCornerEl(); }; pressedKeyIndices.add(keyIdx); move(); if (keyInterval === null) { const PRESS_TIMEOUT = 500; const HOLD_INTERVAL = 100; keyInterval = new util.DelayInterval(() => { move(); }, PRESS_TIMEOUT, HOLD_INTERVAL); } }); corn.el.addEventListener('keyup', (e) => { const keyIdx = getKeyIndex(e); if (keyIdx === -1) { return; } pressedKeyIndices.delete(keyIdx); if (pressedKeyIndices.size === 0) { clearKeydown(); } }); }); // Stop dragging. for (const eventName of ['pointerup', 'pointerleave', 'pointercancel']) { this.image.addEventListener(eventName, (e) => { e.preventDefault(); this.clearDragging(assertInstanceof(e, PointerEvent).pointerId); }); } // Move drag corner. this.image.addEventListener('pointermove', (e) => { e.preventDefault(); const pointerId = assertInstanceof(e, PointerEvent).pointerId; const corn = this.findDragging(pointerId); if (corn === null) { return; } assert(corn.el.classList.contains('dragging')); let dragX = e.offsetX; let dragY = e.offsetY; const target = assertInstanceof(e.target, HTMLElement); // The offsetX, offsetY of corners.el are measured from their own left, // top. if (this.corners.find(({el}) => el === target) !== undefined) { const style = target.attributeStyleMap; dragX += util.getStyleValueInPx(style, 'left') - cornerSize.width / 2; dragY += util.getStyleValueInPx(style, 'top') - cornerSize.height / 2; } const validPt = this.mapToValidArea(corn, new Point(dragX, dragY)); if (validPt === null) { return; } corn.pt = validPt; this.updateCornerEl(); }); // Prevent contextmenu popup triggered by long touch. this.image.addEventListener('contextmenu', (e) => { if (e['pointerType'] === 'touch') { e.preventDefault(); } }); } /** * @param corners Initial guess from corner detector. * @return Returns new selected corners to be cropped and its rotation. */ async reviewCropArea(corners: Point[]): Promise<{corners: Point[], rotation: Rotation}> { this.initialCorners = corners; this.cornerSpaceSize = null; await super.startReview({ positive: new Options( new Option(I18nString.LABEL_CROP_DONE, {exitValue: true}), ), negative: new Options(), }); const newCorners = this.corners.map( ({pt: {x, y}}) => new Point( x / this.cornerSpaceSize.width, y / this.cornerSpaceSize.height)); return {corners: newCorners, rotation: ROTATIONS[this.rotation]}; } private setDragging(corn: Corner, pointerId: number) { corn.el.classList.add('dragging'); corn.pointerId = pointerId; } private findDragging(pointerId: number): Corner|null { return this.corners.find(({pointerId: id}) => id === pointerId) || null; } private clearDragging(pointerId: number) { const corn = this.findDragging(pointerId); if (corn === null) { return; } corn.el.classList.remove('dragging'); corn.pointerId = null; } private mapToValidArea(corn: Corner, pt: Point): Point|null { pt = new Point( Math.max(Math.min(pt.x, this.cornerSpaceSize.width), 0), Math.max(Math.min(pt.y, this.cornerSpaceSize.height), 0)); const idx = this.corners.findIndex((c) => c === corn); assert(idx !== -1); const prevPt = this.corners[(idx + 3) % 4].pt; const nextPt = this.corners[(idx + 1) % 4].pt; const restPt = this.corners[(idx + 2) % 4].pt; const closestDist = Math.min(this.cornerSpaceSize.width, this.cornerSpaceSize.height) * CLOSEST_DISTANCE_RATIO; const prevDir = vectorFromPoints(restPt, prevPt).direction(); const prevBorder = (new Line(prevPt, prevDir)).moveParallel(closestDist); const nextDir = vectorFromPoints(nextPt, restPt).direction(); const nextBorder = (new Line(nextPt, nextDir)).moveParallel(closestDist); const restDir = vectorFromPoints(nextPt, prevPt).direction(); const restBorder = (new Line(prevPt, restDir)).moveParallel(closestDist); if (prevBorder.isInward(pt) && nextBorder.isInward(pt) && restBorder.isInward(pt)) { return pt; } const prevBorderPt = prevBorder.intersect(restBorder); if (prevBorderPt === null) { // May completely overlapped. return null; } const nextBorderPt = nextBorder.intersect(restBorder); if (nextBorderPt === null) { // May completely overlapped. return null; } const box = new Box(assertInstanceof(this.cornerSpaceSize, Size)); // Find boundary points of valid area by cases of whether |prevBorderPt| and // |nextBorderPt| are inside/outside the box. const boundaryPts = []; if (!box.inside(prevBorderPt) && !box.inside(nextBorderPt)) { const intersectPts = box.segmentIntersect(prevBorderPt, nextBorderPt); if (intersectPts.length === 0) { // Valid area is completely outside the bounding box. return null; } else { boundaryPts.push(...intersectPts); } } else { if (box.inside(prevBorderPt)) { const boxPt = box.rayIntersect(prevBorderPt, prevBorder.direction.reverse()); boundaryPts.push(boxPt, prevBorderPt); } else { const newPrevBorderPt = box.rayIntersect( nextBorderPt, vectorFromPoints(prevBorderPt, nextBorderPt)); boundaryPts.push(newPrevBorderPt); } if (box.inside(nextBorderPt)) { const boxPt = box.rayIntersect(nextBorderPt, nextBorder.direction); boundaryPts.push(nextBorderPt, boxPt); } else { const newBorderPt = box.rayIntersect( prevBorderPt, vectorFromPoints(nextBorderPt, prevBorderPt)); boundaryPts.push(newBorderPt); } } /** * @return Square distance of |pt3| to segment formed by |pt1| and |pt2| * and the corresponding nearest point on the segment. */ const distToSegment = (pt1: Point, pt2: Point, pt3: Point): {dist2: number, nearest: Point} => { // Minimum Distance between a Point and a Line: // http://paulbourke.net/geometry/pointlineplane/ const v12 = vectorFromPoints(pt2, pt1); const v13 = vectorFromPoints(pt3, pt1); const u = (v12.x * v13.x + v12.y * v13.y) / v12.length2(); if (u <= 0) { return {dist2: v13.length2(), nearest: pt1}; } if (u >= 1) { return {dist2: vectorFromPoints(pt3, pt2).length2(), nearest: pt2}; } const projection = vectorFromPoints(pt1).add(v12.multiply(u)).point(); return { dist2: vectorFromPoints(projection, pt3).length2(), nearest: projection, }; }; // Project |pt| to nearest point on boundary. let mn = Infinity; let mnPt = null; for (let i = 1; i < boundaryPts.length; i++) { const {dist2, nearest} = distToSegment(boundaryPts[i - 1], boundaryPts[i], pt); if (dist2 < mn) { mn = dist2; mnPt = nearest; } } return assertInstanceof(mnPt, Point); } private updateCornerEl() { const cords = this.corners.map(({pt: {x, y}}) => `${x},${y}`).join(' '); this.cropArea.setAttribute('points', cords); this.corners.forEach((corn) => { const style = corn.el.attributeStyleMap; style.set('left', CSS.px(corn.pt.x)); style.set('top', CSS.px(corn.pt.y)); }); } private updateCornerElAriaLabel() { [I18nString.LABEL_DOCUMENT_TOP_LEFT_CORNER, I18nString.LABEL_DOCUMENT_BOTTOM_LEFT_CORNER, I18nString.LABEL_DOCUMENT_BOTTOM_RIGHT_CORNER, I18nString.LABEL_DOCUMENT_TOP_RIGHT_CORNER, ].forEach((label, index) => { const cornEl = this.corners[(this.rotation + index) % this.corners.length].el; cornEl.setAttribute('i18n-aria', label); }); util.setupI18nElements(this.root); } /** * Updates image position/size with respect to |this.rotation_|, * |this.frameSize_| and |this.imageOriginalSize_|. */ private updateImage() { const {width: frameW, height: frameH} = this.frameSize; const {width: rawImageW, height: rawImageH} = this.imageOriginalSize; const style = this.image.attributeStyleMap; let rotatedW = rawImageW; let rotatedH = rawImageH; if (ROTATIONS[this.rotation] === Rotation.ANGLE_90 || ROTATIONS[this.rotation] === Rotation.ANGLE_270) { [rotatedW, rotatedH] = [rotatedH, rotatedW]; } const scale = Math.min(1, frameW / rotatedW, frameH / rotatedH); const newImageW = scale * rawImageW; const newImageH = scale * rawImageH; style.set('width', CSS.px(newImageW)); style.set('height', CSS.px(newImageH)); this.cropAreaContainer.setAttribute( 'viewBox', `0 0 ${newImageW} ${newImageH}`); // Update corner space. if (this.cornerSpaceSize === null) { this.initialCorners.forEach(({x, y}, idx) => { this.corners[idx].pt = new Point(x * newImageW, y * newImageH); }); this.initialCorners = null; } else { const oldImageW = this.cornerSpaceSize?.width || newImageW; const oldImageH = this.cornerSpaceSize?.height || newImageH; this.corners.forEach((corn) => { corn.pt = new Point( corn.pt.x / oldImageW * newImageW, corn.pt.y / oldImageH * newImageH); }); } this.cornerSpaceSize = new Size(newImageW, newImageH); const originX = frameW / 2 + rotatedW * scale / 2 * [-1, 1, 1, -1][this.rotation]; const originY = frameH / 2 + rotatedH * scale / 2 * [-1, -1, 1, 1][this.rotation]; style.set('left', CSS.px(originX)); style.set('top', CSS.px(originY)); const deg = ROTATIONS[this.rotation]; style.set( 'transform', new CSSTransformValue([new CSSRotate(CSS.deg(deg))])); this.updateCornerEl(); } async setReviewPhoto(blob: Blob): Promise<void> { const image = new Image(); await this.loadImage(image, blob); this.imageOriginalSize = new Size(image.width, image.height); const style = this.image.attributeStyleMap; if (style.has('background-image')) { const oldUrl = style.get('background-image') .toString() .match(/url\(['"]([^'"]+)['"]\)/)[1]; URL.revokeObjectURL(oldUrl); } style.set('background-image', `url('${image.src}')`); this.rotation = 0; this.updateCornerElAriaLabel(); } layout(): void { super.layout(); const rect = this.imageFrame.getBoundingClientRect(); this.frameSize = new Size(rect.width, rect.height); this.updateImage(); // Clear all dragging corners. for (const corn of this.corners) { if (corn.pointerId !== null) { this.clearDragging(corn.pointerId); } } } }
the_stack
import { mat4 } from 'gl-matrix'; import Buffers, { IOBuffer } from '../buffers/buffers'; import OrbitCamera from '../camera/orbit-camera'; import CanvasTimer from '../canvas/canvas-timer'; import { ContextMode, ContextVertexBuffers } from '../context/context'; import Common from '../core/common'; import Subscriber from '../core/subscriber'; import BoxGeometry from '../geometry/box-geometry'; import FlatGeometry from '../geometry/flat-geometry'; import Geometry from '../geometry/geometry'; import SphereGeometry from '../geometry/sphere-geometry'; import TorusGeometry from '../geometry/torus-geometry'; import ObjLoader from '../loaders/obj-loader'; import Logger from '../logger/logger'; import Vector2 from '../math/vector2'; import Textures, { ITextureInput } from '../textures/textures'; import Uniforms, { UniformMethod, UniformType } from '../uniforms/uniforms'; export default class Renderer extends Subscriber { gl: WebGLRenderingContext | WebGL2RenderingContext; program: WebGLProgram; timer: CanvasTimer; uniforms: Uniforms = new Uniforms(); buffers: Buffers = new Buffers(); textures: Textures = new Textures(); textureList: ITextureInput[] = []; W: number = 0; H: number = 0; mouse: Vector2 = new Vector2(); radians: number = 0; dirty: boolean = true; animated: boolean = false; drawFunc_: (deltaTime: number) => void; vertexString: string; fragmentString: string; camera: OrbitCamera = new OrbitCamera(); geometry: Geometry; vertexBuffers: ContextVertexBuffers; projectionMatrix: mat4; modelViewMatrix: mat4; normalMatrix: mat4; mode: ContextMode; mesh: string; defaultMesh: string; doubleSided: boolean; cache: { [key: string]: Geometry } = {}; workpath: string; constructor() { super(); this.drawFunc_ = this.drawArrays_; } protected render(): void { const gl = this.gl; if (!gl) { return; } const BW = gl.drawingBufferWidth; const BH = gl.drawingBufferHeight; this.update_(); gl.viewport(0, 0, BW, BH); const uniforms = this.uniforms; Object.keys(this.buffers.values).forEach((key) => { const buffer: IOBuffer = this.buffers.values[key]; buffer.geometry.attachAttributes_(gl, buffer.program); // uniforms.get('u_resolution').values = [1024, 1024]; uniforms.apply(gl, buffer.program); /* // console.log('uniforms'); Object.keys(uniforms.values).forEach((key) => { if (key.indexOf('u_buff') === 0) { // console.log(key); } }); */ buffer.render(gl, BW, BH); }); // uniforms.get('u_resolution').values = [BW, BH]; this.geometry.attachAttributes_(gl, this.program); uniforms.apply(gl, this.program); // gl.viewport(0, 0, BW, BH); this.drawFunc_(this.timer.delta); uniforms.clean(); this.textures.clean(); this.dirty = false; this.trigger('render', this); } protected drawArrays_(deltaTime: number) { const gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, null); // Clear gl.viewport(0, 0, this.W, this.H); gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clearDepth(1.0); // Clear the canvas before we start drawing on it. // gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.enable(gl.CULL_FACE); if (this.doubleSided && this.mode !== ContextMode.Flat) { // back // gl.frontFace(gl.CW); gl.cullFace(gl.FRONT); gl.drawArrays(gl.TRIANGLES, 0, this.geometry.size); // front gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } // gl.frontFace(gl.CCW); gl.cullFace(gl.BACK); gl.drawArrays(gl.TRIANGLES, 0, this.geometry.size); // gl.drawElements(gl.TRIANGLES, this.geometry.size, gl.UNSIGNED_SHORT, 0); } protected create_(): void { this.createGeometry_(); this.createUniforms_(); } protected createGeometry_() { // console.log('Geometry', Geometry); // console.log('FlatGeometry', FlatGeometry); // console.log('BoxGeometry', BoxGeometry); this.parseGeometry_(); this.setMode(this.mode); } protected parseGeometry_() { const regexp = /^attribute\s+vec4\s+a_position\s*;\s*\/\/\s*([\w|\:\/\/|\.|\-|\_|\?|\&|\=]+)/gm; const match = regexp.exec(this.vertexString); if (match && match.length > 1) { this.mesh = match[1]; } else { this.mesh = this.defaultMesh; } } protected createUniforms_(): void { const gl = this.gl; const fragmentString = this.fragmentString; const BW = gl.drawingBufferWidth; const BH = gl.drawingBufferHeight; const timer = this.timer = new CanvasTimer(); const hasDelta = (fragmentString.match(/u_delta/g) || []).length > 1; const hasTime = (fragmentString.match(/u_time/g) || []).length > 1; const hasDate = (fragmentString.match(/u_date/g) || []).length > 1; const hasMouse = (fragmentString.match(/u_mouse/g) || []).length > 1; const hasCamera = (fragmentString.match(/u_camera/g) || []).length > 1; // this.animated = hasTime || hasDate || hasMouse; this.animated = true; // !!! const uniforms = this.uniforms; uniforms.create(UniformMethod.Uniform2f, UniformType.Float, 'u_resolution', [BW, BH]); if (hasDelta) { uniforms.create(UniformMethod.Uniform1f, UniformType.Float, 'u_delta', [timer.delta / 1000.0]); this.updateUniformDelta_ = this.updateUniformDelta__; } else { this.updateUniformDelta_ = this.updateUniformNoop_; } if (hasTime) { uniforms.create(UniformMethod.Uniform1f, UniformType.Float, 'u_time', [timer.current / 1000.0]); this.updateUniformTime_ = this.updateUniformTime__; } else { this.updateUniformTime_ = this.updateUniformNoop_; } if (hasDate) { const date = new Date(); uniforms.create(UniformMethod.Uniform4f, UniformType.Float, 'u_date', [date.getFullYear(), date.getMonth(), date.getDate(), date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds() * 0.001]); this.updateUniformDate_ = this.updateUniformDate__; } else { this.updateUniformDate_ = this.updateUniformNoop_; } if (hasMouse) { uniforms.create(UniformMethod.Uniform2f, UniformType.Float, 'u_mouse', [0, 0]); this.updateUniformMouse_ = this.updateUniformMouse__; } else { this.updateUniformMouse_ = this.updateUniformNoop_; } if (hasCamera) { uniforms.create(UniformMethod.Uniform3f, UniformType.Float, 'u_camera', [0, 0, 0]); this.updateUniformCamera_ = this.updateUniformCamera__; } else { this.updateUniformCamera_ = this.updateUniformNoop_; } // if (this.mode !== ContextMode.Flat) { this.projectionMatrix = mat4.create(); uniforms.create(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_projectionMatrix', this.projectionMatrix as number[]); this.modelViewMatrix = mat4.create(); uniforms.create(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_modelViewMatrix', this.modelViewMatrix as number[]); this.normalMatrix = mat4.create(); uniforms.create(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_normalMatrix', this.normalMatrix as number[]); // } } protected update_(): void { const gl = this.gl; const BW = gl.drawingBufferWidth; const BH = gl.drawingBufferHeight; if (!this.timer) { return; } const timer = this.timer.next(); const uniforms = this.uniforms; uniforms.update(UniformMethod.Uniform2f, UniformType.Float, 'u_resolution', [BW, BH]); this.updateUniformDelta_(timer); this.updateUniformTime_(timer); this.updateUniformDate_(); this.updateUniformMouse_(); this.updateUniformCamera_(); this.updateUniformMesh_(); } updateUniformNoop_(): void {}; updateUniformDelta_: (timer:CanvasTimer) => void; updateUniformTime_: (timer:CanvasTimer) => void; updateUniformDate_: () => void; updateUniformMouse_: () => void; updateUniformCamera_: () => void; updateUniformMesh_: () => void; protected updateUniformDelta__(timer:CanvasTimer):void { const uniforms = this.uniforms; uniforms.update(UniformMethod.Uniform1f, UniformType.Float, 'u_delta', [timer.delta / 1000.0]); }; protected updateUniformTime__(timer:CanvasTimer):void { const uniforms = this.uniforms; uniforms.update(UniformMethod.Uniform1f, UniformType.Float, 'u_time', [timer.current / 1000.0]); }; protected updateUniformDate__():void { const uniforms = this.uniforms; const date = new Date(); uniforms.update(UniformMethod.Uniform4f, UniformType.Float, 'u_date', [date.getFullYear(), date.getMonth(), date.getDate(), date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds() * 0.001]); }; protected updateUniformMouse__():void { const uniforms = this.uniforms; const mouse = this.mouse; uniforms.update(UniformMethod.Uniform2f, UniformType.Float, 'u_mouse', [mouse.x, mouse.y]); /* const rect = this.rect; if (mouse.x >= rect.left && mouse.x <= rect.right && mouse.y >= rect.top && mouse.y <= rect.bottom) { const MX = (mouse.x - rect.left) * this.devicePixelRatio; const MY = (this.canvas.height - (mouse.y - rect.top) * this.devicePixelRatio); uniforms.update(UniformMethod.Uniform2f, UniformType.Float, 'u_mouse', [MX, MY]); } */ }; protected updateUniformCamera__():void { const uniforms = this.uniforms; const array = OrbitCamera.toArray(this.camera); uniforms.update(UniformMethod.Uniform3f, UniformType.Float, 'u_camera', array); }; protected updateUniformMesh__():void { const uniforms = this.uniforms; uniforms.update(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_projectionMatrix', this.updateProjectionMatrix_() as number[]); uniforms.update(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_modelViewMatrix', this.updateModelViewMatrix_(this.timer.delta) as number[]); uniforms.update(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_normalMatrix', this.updateNormalMatrix_(this.modelViewMatrix) as number[]); }; protected updateUniformFlat__():void { const uniforms = this.uniforms; uniforms.update(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_projectionMatrix', mat4.create() as number[]); uniforms.update(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_modelViewMatrix', mat4.create() as number[]); uniforms.update(UniformMethod.UniformMatrix4fv, UniformType.Float, 'u_normalMatrix', mat4.create() as number[]); } protected updateProjectionMatrix_(): mat4 { const gl = this.gl; const fieldOfView = 45 * Math.PI / 180; const aspect = gl.drawingBufferWidth / gl.drawingBufferHeight; const zNear = 0.1; const zFar = 100.0; mat4.perspective(this.projectionMatrix, fieldOfView, aspect, zNear, zFar); return this.projectionMatrix; } protected updateModelViewMatrix_(deltaTime: number): mat4 { const camera = this.camera; let modelViewMatrix = this.modelViewMatrix; modelViewMatrix = mat4.identity(modelViewMatrix); mat4.translate(modelViewMatrix, modelViewMatrix, [0.0, 0.0, -camera.radius]); // amount to translate mat4.rotate(modelViewMatrix, modelViewMatrix, camera.theta + this.radians, [0, 1, 0]); // axis to rotate around (Y) mat4.rotate(modelViewMatrix, modelViewMatrix, camera.phi, [1, 0, 0]); // axis to rotate around (X) if (!camera.mouse) { camera.theta += (0 - camera.theta) / 20; camera.phi += (0 - camera.phi) / 20; this.radians += deltaTime * 0.0005; } return modelViewMatrix; } protected updateNormalMatrix_(modelViewMatrix: mat4): mat4 { // this.normalMatrix = mat4.create(); let normalMatrix = this.normalMatrix; normalMatrix = mat4.identity(normalMatrix); mat4.invert(normalMatrix, modelViewMatrix); mat4.transpose(normalMatrix, normalMatrix); return normalMatrix; } public setMode(mode: ContextMode) { let geometry: Geometry; if (mode === ContextMode.Mesh) { geometry = this.cache[this.mesh]; if (geometry) { this.geometry = geometry; this.mode = ContextMode.Mesh; this.updateUniformMesh_ = this.updateUniformMesh__; this.dirty = true; return; } } let loader: ObjLoader; switch (mode) { case ContextMode.Flat: geometry = new FlatGeometry(); this.updateUniformMesh_ = this.updateUniformNoop_; this.updateUniformFlat__(); break; case ContextMode.Box: geometry = new BoxGeometry(); this.updateUniformMesh_ = this.updateUniformMesh__; break; case ContextMode.Sphere: geometry = new SphereGeometry(); this.updateUniformMesh_ = this.updateUniformMesh__; break; case ContextMode.Torus: geometry = new TorusGeometry(); this.updateUniformMesh_ = this.updateUniformMesh__; break; case ContextMode.Mesh: geometry = new FlatGeometry(); if (this.mesh) { loader = new ObjLoader(); loader.load(Common.getResource(this.mesh, this.workpath)).then(geometry => { geometry.createAttributes_(this.gl, this.program); const cache: { [key: string]: Geometry } = {}; cache[this.mesh] = geometry; this.cache = cache; this.geometry = geometry; this.dirty = true; }, error => { Logger.warn('GlslCanvas', error); this.mode = ContextMode.Flat; }); } else { mode = ContextMode.Flat; } this.updateUniformMesh_ = this.updateUniformMesh__; break; } geometry.create(this.gl, this.program); this.geometry = geometry; this.mode = mode; this.dirty = true; } public setMesh(mesh: string) { this.mesh = mesh; } }
the_stack
/// <reference types="node" /> export = massive; declare function massive( connection: massive.ConnectionInfo | string, loaderConfig?: massive.Loader, driverConfig?: object ): Promise<massive.Database>; declare namespace massive { type UUID = string; interface AnyObject<T = any> { [key: string]: T; } interface Loader { blacklist?: string | string[] | undefined; whitelist?: string | string[] | undefined; functionBlacklist?: string | string[] | undefined; functionWhitelist?: string | string[] | undefined; allowedSchemas?: string | string[] | undefined; exceptions?: string | string[] | undefined; scripts?: string | undefined; } interface DropOptions { cascade?: boolean | undefined; } interface ConnectionInfo { user?: string | undefined; database?: string | undefined; password?: string | null | undefined; port?: number | undefined; host?: string | undefined; ssl?: boolean | undefined; application_name?: string | undefined; fallback_application_name?: boolean | undefined; } interface RetrievalOptions { fields?: string[] | undefined; exprs?: AnyObject<string> | undefined; limit?: number | undefined; offset?: number | undefined; order?: OrderingOptions[] | undefined; pageLength?: number | undefined; } interface OrderingOptions { field?: string | undefined; expr?: string | undefined; direction?: "ASC" | "asc" | "DESC" | "desc" | undefined; nulls?: "FIRST" | "first" | "LAST" | "last" | undefined; type?: string | undefined; last?: string | undefined; } interface PersistenceInsertOptions { onConflictIgnore?: boolean | undefined; deepInsert?: boolean | undefined; } interface PersistenceUpdateDocOptions { body?: string | undefined; } interface InheritanceOptions { only?: boolean | undefined; } interface ResultProcessingOptions { build?: boolean | undefined; document?: boolean | undefined; single?: boolean | undefined; stream?: boolean | undefined; decompose?: DecomposeOptions | undefined; } interface DecomposeOptions { pk: string; columns?: string[] | AnyObject<string> | undefined; [foreignTable: string]: DecomposeOptions | any; } interface SearchDefinition { fields: string[]; term: string; where: AnyObject; } interface SearchCriteria { fields: string[]; term: string; } type QueryParamTypes = string | number | object; type QueryParams = QueryParamTypes[] | QueryParamTypes; interface EntitySpecification { /** A Database. */ db: Database; /** The entity's name. */ name: string; /** Path to the entity, if a file. */ path: string; /** Entity's owning schema, if a database object. */ schema: string; /** Name of the loader that discovered the entity. */ loader: string; } class Entity { constructor(spec: EntitySpecification); } interface ExecutableSpecification { /** A Database. */ db: Database; /** The table or view's name. */ name: string; /** The name of the schema owning the table or */ schema: string; /** A function invocation statement or a pg-promise QueryFile. */ sql: any; /** Number of parameters the executable expects. */ paramCount: number; /** Whether a database function accepts variable-length argument lists as the last parameter. */ isVariadic: boolean; /** True to enable single row/value results processing. */ enhancedFunctions: boolean; /** If true, return the first result row as an object (with enhancedFunctions). */ singleRow: boolean; /** If true, return results as a primitive or primitives (with enhancedFunctions). */ singleValue: boolean; } class Executable { constructor(spec: ExecutableSpecification); /** Invoke the function or script. */ invoke(options?: ResultProcessingOptions): Promise<AnyObject | any[]>; } interface ReadableSpecification { /** A Database. */ db: Database; /** The table or view's name. */ name: string; /** The name of the schema owning the table or view. */ schema: string; /** Whether the object is a materialized view (default false). */ is_matview?: boolean | undefined; } class Readable extends Entity { constructor(spec: ReadableSpecification); /** Count rows matching criteria. */ count(conditions: AnyObject): Promise<number>; count(conditions: string, params: any[]): Promise<number>; /** Count documents matching criteria. Unlike count, this function only supports criteria objects. */ countDoc(criteria: object): Promise<number>; /** Find rows matching criteria. */ find( criteria?: AnyObject | number | UUID, options?: RetrievalOptions & ResultProcessingOptions ): Promise<any>; /** Find a document by searching in the body. */ findDoc( criteria?: AnyObject | number | UUID, options?: RetrievalOptions ): Promise<any>; /** Return a single record. */ findOne( criteria: AnyObject | number | UUID, options?: RetrievalOptions & ResultProcessingOptions ): Promise<any>; /** * Determine whether criteria represent a search by primary key. * If a number or uuid are passed, it is assumed to be a primary key value; if an object, it must have only one key, which must specify the primary key column. */ isPkSearch(criteria: AnyObject | UUID | number): boolean; /** Refresh a materialized view. */ refresh(concurrently?: boolean): Promise<void>; /** * Perform a full-text search on queryable fields. If options.document is true, looks in the document body fields instead of the table columns. */ search( plan: SearchDefinition, options?: RetrievalOptions ): Promise<any[]>; /** Shortcut to perform a full text search on a document table. */ searchDoc( plan: Pick<SearchDefinition, "fields" | "term">, options?: RetrievalOptions ): Promise<any[]>; /** Run a query with a raw SQL predicate, eg: db.mytable.where('id=$1', [123]).then(...); */ where( conditions: string, params?: any[], options?: RetrievalOptions & ResultProcessingOptions ): Promise<any[]>; } interface WritableSpecification { /** A Database. */ db: Database; /** The table or view's name. */ name: string; /** The name of the schema owning the table. */ schema: string; /** The table's primary key. */ pk: string; } class Writable extends Readable { /** A database table or other writable object */ constructor(spec: WritableSpecification); /** Delete a record or records. */ destroy( criteria: AnyObject, options?: ResultProcessingOptions ): Promise<any[]>; /** * Attempts to assemble primary key criteria for a record object representing a row in this table. * The criteria must include the full primary key, and must not invoke any operations. */ getPkCriteria(record: AnyObject): AnyObject; /** Insert a record or records into the table. */ insert( data: AnyObject, options?: PersistenceInsertOptions & ResultProcessingOptions ): Promise<AnyObject>; insert( data: AnyObject[], options?: PersistenceInsertOptions & ResultProcessingOptions ): Promise<AnyObject[]>; /** * Saves an object. * If the object does not include a value for the table's primary key, this will emit an INSERT to create a new record. * if it does contain the primary key it will emit an UPDATE for the existing record. * Either way, the newest available version of the record will be returned. * This is not a true Postgres upsert! If you need the behavior of ON CONFLICT DO UPDATE, you'll need to use db.query or create an SQL script file. */ save( record: AnyObject, options?: PersistenceInsertOptions & PersistenceUpdateDocOptions & ResultProcessingOptions ): Promise<AnyObject>; /** Save a document to the database. This function will create or replace the entire document body. */ saveDoc(doc: AnyObject): Promise<AnyObject>; /** Update a record. */ update( criteria: UUID | number, changes: AnyObject, options?: PersistenceUpdateDocOptions & ResultProcessingOptions ): Promise<AnyObject>; update( criteria: AnyObject, changes: AnyObject, options?: PersistenceUpdateDocOptions & ResultProcessingOptions ): Promise<AnyObject[]>; /** * Update a document, adding new information and changing existing information. * This function can be used with any JSON field, not just document tables; however, only document tables can use criteria objects which directly reference document fields. * If calling updateDoc with a criteria object for a non-document table, the criteria will be tested against the entire row (as opposed to the document body as it is for document tables). * To test elements of the JSON field in a non-document table with a criteria object, use a JSON path string. */ updateDoc( criteria: UUID | number | AnyObject, changes: AnyObject, options?: PersistenceUpdateDocOptions & ResultProcessingOptions ): Promise<AnyObject>; } class Sequence { /** A database sequence. */ constructor(db: Database, name: string, schema: string); /** * Get the last value the sequence returned. * The return value will be a stringified number. */ lastValue(): Promise<string>; /** * Increment the sequence counter and return the next value. * The return value will be a stringified number. */ nextValue(): Promise<string>; /** Reset the sequence. */ reset(initialValue: number): Promise<void>; } class SingleValueStream { /** A stream which processes single-key results objects into their values for convenience on the client side. */ constructor(options: AnyObject); /** Converts a single-key object into its value. */ singleValue(obj: AnyObject): any; /** Implement the Transform stream that invokes singleValue on everything which passes through it. */ private _transform( obj: AnyObject, encoding: string, cb: (err?: Error) => void ): void; } /** Represents a SELECT query. */ class Select { /** Represents an SELECT query. */ constructor( source: Readable, criteria: AnyObject | UUID, options?: RetrievalOptions & ResultProcessingOptions ); /** Format this object into a SQL SELECT. */ format(): string; } /** Represents a INSERT query. */ class Insert { /** Represents an INSERT query. */ constructor( source: Readable, record: AnyObject | any[], options?: ResultProcessingOptions & PersistenceInsertOptions ); /** Format this object into a SQL SELECT. */ format(): string; } /** Represents a UPDATE query. */ class Update { /** Represents an UPDATE query. */ constructor( source: Readable, changes: AnyObject, criteria: AnyObject, options?: ResultProcessingOptions & PersistenceUpdateDocOptions ); /** Format this object into a SQL SELECT. */ format(): string; } /** Represents a UPDATE query. */ class Delete { /** Represents a DELETE query. */ constructor( source: Readable, criteria?: AnyObject | UUID | number, options?: ResultProcessingOptions & InheritanceOptions ); /** Format this object into a SQL SELECT. */ format(): string; } class Database { /** * @param connection A connection object or connection string */ constructor( connection: object | string, loader?: Loader, driverConfig?: object ); /** Attach an entity to the connected instance. */ attach(entities: AnyObject | any[]): Promise<any[]>; /** Remove all attached entities from the instance, returning it to the pre- introspection state. */ clean(): void; /** Clones the database handle for a task or transaction, replacing the internal instance with a dedicated connection. */ clone(conn: ConnectionInfo): Database; /** Create a new document table and attach it to the Database for usage. */ createDocumentTable(location: string): Promise<void>; /** Create an extension. */ createExtension(extensionName: string): Promise<void>; /** Create a new schema in the database. */ createSchema(schemaName: string): Promise<void>; /** Forget an entity. */ detach(entityPath: string): void; /** Drop an extension. */ dropExtension(extensionName: string): Promise<void>; /** Drop a schema and remove it and its owned objects from the Database. */ dropSchema(schemaName: string, options?: DropOptions): Promise<void>; /** Drop a table and remove it from the Database. */ dropTable(tablePath: string, options?: DropOptions): Promise<void>; /** List all the functions and scripts attached to the connected instance. */ listFunctions(): Promise<any[]>; /** List all the non-pk sequences attached to the connected instance. */ listSequences(): Promise<any[]>; /** List all the tables attached to the connected instance. */ listTables(): Promise<any[]>; /** List all the views attached to the connected instance. */ listViews(): Promise<any[]>; /** Execute a query. */ query( query: Select | Insert | Update | Delete | string, params?: QueryParams, options?: ResultProcessingOptions ): Promise<any>; /** * Synchronize the database API with the current state by scanning for tables, views, functions, and scripts. * Objects and files which no longer exist are cleared and new objects and files added. */ reload(): Promise<Database>; /** Save a document. */ saveDoc(collection: string, doc: AnyObject): Promise<any>; /** Begin a task, returning a copy of the connected instance which will route all queries made in the callback through the task scope. */ withConnection( cb: (withTask: any) => any, options?: AnyObject ): Promise<any>; /** Begin a transaction, returning a copy of the connected instance which will route all queries made in the callback through the transaction scope. */ withTransaction( cb: (withTx: any) => any, options?: AnyObject ): Promise<any>; [tableName: string]: Writable | any; } }
the_stack
import * as angular from 'angular'; describe('tableDirective: <uif-table />', () => { let element: JQuery; let scope: any; beforeEach(() => { angular.mock.module('officeuifabric.core'); angular.mock.module('officeuifabric.components.table'); }); beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => { scope = $rootScope; })); it('should render table using a table tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.prop('tagName')).toEqual('TABLE'); })); it('should set correct Office UI Fabric classes on the table', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element).toHaveClass('ms-Table'); })); it( 'should set correct Office UI Fabric fixed class on the table for the \'uif-table-type\' attribute', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table uif-table-type="fixed"></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element).toHaveClass('ms-Table--fixed'); })); it( 'should set correct Office UI Fabric fluid class on the table for the \'uif-table-type\' attribute', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table uif-table-type="fluid"></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element).not.toHaveClass('ms-Table--fixed'); })); it( 'should throw an error on an invalid value for the \'uif-table-type\' attribute', inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => { element = angular.element('<uif-table uif-table-type="invalid"></uif-table>'); $compile(element)(scope); scope.$digest(); expect($log.error.logs.length).toEqual(1); })); it('should render the row using a tr tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.children().eq(0).prop('tagName')).toEqual('TR'); })); it('should set no Office UI Fabric classes on the row', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.children().eq(0)).not.toHaveClass('ms-Table-row'); })); it( 'should set correct Office UI Fabric classes on the selected and unselected rows', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row></uif-table-row>\ <uif-table-row uif-selected="true"></uif-table-row><uif-table-row uif-selected="false"></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); let rows: JQuery = element.children(); expect(rows.length).toEqual(3); expect(rows.eq(0)).not.toHaveClass('is-selected'); expect(rows.eq(1)).toHaveClass('is-selected'); expect(rows.eq(2)).not.toHaveClass('is-selected'); })); it( 'should throw an error on an invalid value for the \'uif-selected\' attribute', inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => { element = angular.element('<uif-table><uif-table-row uif-selected="invalid"></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect($log.error.logs.length).toEqual(1); })); it('should render table row select using the td tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.children().eq(0).children().eq(0).prop('tagName')).toEqual('TD'); })); it('should render table row select using the th tag in thead', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table>\ <uif-table-head><uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table-head>\ <uif-table-body><uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table-body>\ </uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.children().eq(0) // thead .children().eq(0) // tr .children().eq(0) // table-row-select .prop('tagName')).toEqual('TH'); })); it('should render table row select using the td tag in tbody', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table>\ <uif-table-head><uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table-head>\ <uif-table-body><uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table-body>\ </uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.children().eq(1) // tbody .children().eq(0) // tr .children().eq(0) // table-row-select .prop('tagName')).toEqual('TD'); })); it( 'should set correct Office UI Fabric classes on the table row select', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.children().eq(0).children().eq(0)).toHaveClass('ms-Table-rowCheck'); })); it('should render the cell using a td tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table-cell></uif-table-cell>'); $compile(element)(scope); scope.$digest(); expect(element.prop('tagName')).toEqual('TD'); })); it('should set no Office UI Fabric classes on the table cell', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table-cell></uif-table-cell>'); $compile(element)(scope); scope.$digest(); expect(element).not.toHaveClass('ms-Table-cell'); })); it('should render the table header using a th tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.children().eq(0).children().eq(0).prop('tagName')).toEqual('TH'); })); it('should set no Office UI Fabric classes on the table header', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(element.children().eq(0).children().eq(0)).not.toHaveClass('ms-Table-cell'); })); it('should trigger sorting only on enabled header cells', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header></uif-table-header>\ <uif-table-header uif-order-by="fileName"></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let headerCells: JQuery = element.children().eq(0).children(); headerCells.eq(0).click(); // sorting disabled for this column; do nothing expect(scope.orderBy).toBeNull(); headerCells.eq(1).click(); // sort fileName:asc expect(scope.orderBy).toEqual('fileName'); })); it( 'should render the data in its originally declared order by default', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header></uif-table-header>\ <uif-table-header uif-order-by="fileName"></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(scope.orderBy).toBeNull(); expect(scope.orderAsc).toBeTruthy(); })); it('should correctly indicate column used for sorting', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header></uif-table-header>\ <uif-table-header uif-order-by="fileName"></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let fileNameHeader: JQuery = element.children().eq(0).children().eq(1); fileNameHeader.click(); expect(fileNameHeader.children().length).toEqual(1, 'Sorting indicator not added to column'); let sortingIndicatorWrapper: JQuery = fileNameHeader.children().eq(0); expect(sortingIndicatorWrapper.prop('tagName')).toEqual('SPAN'); expect(sortingIndicatorWrapper).toHaveClass('uif-sort-order'); let sortingIndicator: JQuery = sortingIndicatorWrapper.children().eq(0); expect(sortingIndicator.prop('tagName')).toEqual('I'); expect(sortingIndicator).toHaveClass('ms-Icon'); expect(sortingIndicator).toHaveClass('ms-Icon--caretDown'); })); it('should correctly indicate reversed sorting order', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header>ID</uif-table-header>\ <uif-table-header uif-order-by="fileName">File name</uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let fileNameHeader: JQuery = element.children().eq(0).children().eq(1); fileNameHeader.click(); fileNameHeader.click(); let sortingIndicatorWrapper: JQuery = fileNameHeader.children().eq(0); let sortingIndicator: JQuery = sortingIndicatorWrapper.children().eq(0); expect(sortingIndicator).toHaveClass('ms-Icon--caretUp'); })); it( 'should sort data ascending after selecting a column for sorting', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header></uif-table-header>\ <uif-table-header uif-order-by="fileName"></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let fileNameHeader: JQuery = element.children().eq(0).children().eq(1); fileNameHeader.click(); expect(scope.orderAsc).toBeTruthy(); })); it( 'should reverse the sorting order when selecting the same column for sorting', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header></uif-table-header>\ <uif-table-header uif-order-by="fileName"></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let fileNameHeader: JQuery = element.children().eq(0).children().eq(1); fileNameHeader.click(); expect(scope.orderAsc).toBeTruthy(); fileNameHeader.click(); expect(scope.orderAsc).toBeFalsy(); fileNameHeader.click(); expect(scope.orderAsc).toBeTruthy(); })); it( 'should clear the sorting indicator after selecting another column for sorting', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header uif-order-by="id">ID</uif-table-header>\ <uif-table-header uif-order-by="fileName">File name</uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let idHeader: JQuery = element.children().eq(0).children().eq(0); let fileNameHeader: JQuery = element.children().eq(0).children().eq(1); idHeader.click(); // sort id:asc fileNameHeader.click(); // sort fileName:asc expect(idHeader.children().length).toEqual(0, 'Sorting indicator not removed from column previously used for sorting'); expect(fileNameHeader.children().length).toEqual(1, 'Sorting indicator not added to the column used for sorting'); })); it( 'should change the sorting order to ascending after selecting another column for sorting', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header uif-order-by="id"></uif-table-header>\ <uif-table-header uif-order-by="fileName"></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let idHeader: JQuery = element.children().eq(0).children().eq(0); let fileNameHeader: JQuery = element.children().eq(0).children().eq(1); idHeader.click(); // sort id:asc idHeader.click(); // sort id:desc fileNameHeader.click(); // sort fileName:asc expect(scope.orderAsc).toBeTruthy(); })); it( 'should keep the sorting data intact after selecting another column for which sorting hasn\'t been enabled', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table><uif-table-row><uif-table-header></uif-table-header>\ <uif-table-header uif-order-by="fileName"></uif-table-header></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let firstHeader: JQuery = element.children().eq(0).children().eq(0); let fileNameHeader: JQuery = element.children().eq(0).children().eq(1); fileNameHeader.click(); // sort fileName:asc firstHeader.click(); // sorting disabled; do nothing expect(scope.orderBy).toEqual('fileName'); expect(scope.orderAsc).toBeTruthy(); })); it('should not allow to select rows by default', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table>' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(scope.rowSelectMode).toEqual('none'); })); it('should allow to explicitly disable row selecting', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table uif-row-select-mode="none">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect(scope.rowSelectMode).toEqual('none'); })); it( 'for row select mode \'single\' should allow to select single row', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="single" uif-selected-items="selectedItems">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); expect(scope.rowSelectMode).toEqual('single'); let firstDataRow: JQuery = element.children().eq(1); let secondDataRow: JQuery = element.children().eq(2); firstDataRow.click(); secondDataRow.click(); let numSelectedItems: number = 0; for (let i: number = 0; i < scope.rows.length; i++) { if (scope.rows[i].selected === true) { numSelectedItems++; } } expect(numSelectedItems).toEqual(1); expect(scope.selectedItems.length).toEqual(1); })); it( 'for row mode select \'multiple\' should allow to select multiple rows', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="multiple" uif-selected-items="selectedItems">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); expect(scope.rowSelectMode).toEqual('multiple'); let firstDataRow: JQuery = element.children().eq(1); let secondDataRow: JQuery = element.children().eq(2); firstDataRow.click(); secondDataRow.click(); let numSelectedItems: number = 0; for (let i: number = 0; i < scope.rows.length; i++) { if (scope.rows[i].selected === true) { numSelectedItems++; } } expect(numSelectedItems).toEqual(2); expect(scope.selectedItems.length).toEqual(2); })); it( 'should throw an error on an invalid row select mode', inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => { element = angular.element('<uif-table uif-row-select-mode="invalid">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); expect($log.error.logs.length).toEqual(1); })); it('shouldn\'t allow selecting the header row', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="single" uif-selected-items="selectedItems">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let headerRow: JQuery = element.children().eq(0); headerRow.click(); expect(headerRow).not.toHaveClass('is-selected'); let numSelectedItems: number = 0; for (let i: number = 0; i < scope.rows.length; i++) { if (scope.rows[i].selected === true) { numSelectedItems++; } } expect(numSelectedItems).toEqual(0); expect(scope.selectedItems.length).toEqual(0); })); it( 'for row select mode \'none\' should use default mouse cursor', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table uif-row-select-mode="none">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); let tableRow: JQuery = element.children().eq(1); expect(tableRow.css('cursor')).toEqual('default'); })); it( 'for row select mode \'none\' shouldn\'t select a row on mouse click', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="none" uif-selected-items="selectedItems">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let tableRow: JQuery = element.children().eq(1); tableRow.click(); expect(tableRow).not.toHaveClass('is-selected'); expect(scope.rows[1].selected).toBeFalsy(); expect(scope.selectedItems.length).toEqual(0); })); it( 'for row select mode \'none\' shouldn\'t select all rows when clicking the table row selector in the header', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="none" uif-selected-items="selectedItems">' + '<uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let tableRowSelect: JQuery = element.children().eq(0).children().eq(0); tableRowSelect.click(); let numSelectedItems: number = 0; for (let i: number = 0; i < scope.rows.length; i++) { if (scope.rows[i].selected === true) { numSelectedItems++; } } expect(numSelectedItems).toEqual(0); expect(scope.selectedItems.length).toEqual(0); })); it( 'for row select mode \'single\' should use hand mouse cursor', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table uif-row-select-mode="single">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); let tableRow: JQuery = element.children().eq(1); // already set to hand by Office UI Fabric expect(tableRow.css('cursor')).toEqual(''); })); it( 'for row select mode \'single\' when clicking a row should select that row and deselect other selected row', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="single" uif-selected-items="selectedItems">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let firstDataRow: JQuery = element.children().eq(1); let secondDataRow: JQuery = element.children().eq(2); firstDataRow.click(); // select first row secondDataRow.click(); // select second row expect(firstDataRow).not.toHaveClass('is-selected'); expect(secondDataRow).toHaveClass('is-selected'); expect(scope.rows[0].selected).toBeFalsy(); expect(scope.rows[1].selected).toBeTruthy(); expect(scope.selectedItems.length).toEqual(1); })); it( 'for row select mode \'single\' when clicking an already selected row should unselect that row', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="single" uif-selected-items="selectedItems">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let firstDataRow: JQuery = element.children().eq(1); firstDataRow.click(); // select first row firstDataRow.click(); // unselect first row expect(firstDataRow).not.toHaveClass('is-selected'); expect(scope.rows[0].selected).toBeFalsy(); expect(scope.selectedItems.length).toEqual(0); })); it( 'for row select mode \'single\' when clicking the row selector in the header shouldn\'t do anything', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="single" uif-selected-items="selectedItems">' + '<uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let tableRowSelectInHeader: JQuery = element.children().eq(0).children().eq(0); tableRowSelectInHeader.click(); let numSelectedItems: number = 0; for (let i: number = 0; i < scope.rows.length; i++) { if (scope.rows[i].selected === true) { numSelectedItems++; } } expect(numSelectedItems).toEqual(0); expect(scope.selectedItems.length).toEqual(0); })); it( 'for row select mode \'multiple\' should use hand mouse cursor', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { element = angular.element('<uif-table uif-row-select-mode="multiple">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); scope.$digest(); let tableRow: JQuery = element.children().eq(1); // already set to hand by Office UI Fabric expect(tableRow.css('cursor')).toEqual(''); })); it( 'for row select mode \'multiple\' clicking an unselected row should select that row', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="multiple" uif-selected-items="selectedItems">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let tableRow: JQuery = element.children().eq(1); tableRow.click(); expect(tableRow).toHaveClass('is-selected'); expect(scope.rows[0].selected).toBeTruthy(); expect(scope.selectedItems.length).toEqual(1); })); it( 'for row select mode \'multiple\' clicking an already selected row should unselect that row', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="multiple" uif-selected-items="selectedItems">' + '<uif-table-row></uif-table-row>' + '<uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-table-row></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let tableRow: JQuery = element.children().eq(1); tableRow.click(); // select row tableRow.click(); // unselect row expect(tableRow).not.toHaveClass('is-selected'); expect(scope.rows[0].selected).toBeFalsy(); expect(scope.selectedItems.length).toEqual(0); })); it( 'for row select mode \'multiple\' clicking the row selected in the header should select all rows if not all rows are selected', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="multiple" uif-selected-items="selectedItems">\ <uif-table-head><uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table-head>\ <uif-table-body>\ <uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"><uif-table-row-select></uif-table-row-select></uif-table-row>\ </uif-table-body></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); let tableRowSelect: JQuery = element.children().eq(0).children().eq(0).children().eq(0); tableRowSelect.click(); let numSelectedItems: number = 0; for (let i: number = 0; i < scope.rows.length; i++) { if (scope.rows[i].selected === true) { numSelectedItems++; } } expect(numSelectedItems).toEqual(3); expect(scope.selectedItems.length).toEqual(3); })); it( 'for row select mode \'multiple\' clicking the row selected in the header should unselect all rows if all rows are selected', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { scope.selectedItems = []; element = angular.element('<uif-table uif-row-select-mode="multiple" uif-selected-items="selectedItems">\ <uif-table-head><uif-table-row><uif-table-row-select></uif-table-row-select></uif-table-row></uif-table-head>\ <uif-table-body>\ <uif-table-row ng-repeat="n in [1, 2, 3]" uif-item="n"><uif-table-row-select></uif-table-row-select></uif-table-row>\ <uif-table-body></uif-table>'); $compile(element)(scope); element = jQuery(element[0]); scope.$digest(); // select all rows element.children().eq(1).children().eq(0).click(); element.children().eq(1).children().eq(1).click(); element.children().eq(1).children().eq(2).click(); let tableRowSelect: JQuery = element.children().eq(0).children().eq(0).children().eq(0); tableRowSelect.click(); let numSelectedItems: number = 0; for (let i: number = 0; i < scope.rows.length; i++) { if (scope.rows[i].selected === true) { numSelectedItems++; } } expect(numSelectedItems).toEqual(0); expect(scope.selectedItems.length).toEqual(0); })); });
the_stack
type State<K, A, B> = | DrainLeft | DrainRight | PullBoth | PullLeft<K, B> | PullRight<K, A> export class DrainLeft { readonly _tag = "DrainLeft" } export class DrainRight { readonly _tag = "DrainRight" } export class PullBoth { readonly _tag = "PullBoth" } export class PullLeft<K, B> { readonly _tag = "PullLeft" constructor(readonly rightChunk: Chunk<Tuple<[K, B]>>) {} } export class PullRight<K, A> { readonly _tag = "PullRight" constructor(readonly leftChunk: Chunk<Tuple<[K, A]>>) {} } /** * Zips this stream that is sorted by distinct keys and the specified stream * that is sorted by distinct keys to produce a new stream that is sorted by * distinct keys. Uses the functions `left`, `right`, and `both` to handle * the cases where a key and value exist in this stream, that stream, or * both streams. * * This allows zipping potentially unbounded streams of data by key in * constant space but the caller is responsible for ensuring that the * streams are sorted by distinct keys. * * @tsplus fluent ets/SortedByKey zipAllSortedByKeyWith * @tsplus fluent ets/Stream zipAllSortedByKeyWith */ export function zipAllSortedByKeyWith_<R, E, K, A>( self: SortedByKey<R, E, K, A>, ord: Ord<K> ) { return <R2, E2, B, C1, C2, C3>( that: LazyArg<SortedByKey<R2, E2, K, B>>, left: (a: A) => C1, right: (b: B) => C2, both: (a: A, b: B) => C3, __tsplusTrace?: string ): Stream<R & R2, E | E2, Tuple<[K, C1 | C2 | C3]>> => { const pull = ( state: State<K, A, B>, pullLeft: Effect<R, Option<E>, Chunk<Tuple<[K, A]>>>, pullRight: Effect<R2, Option<E2>, Chunk<Tuple<[K, B]>>> ): Effect< R & R2, never, Exit<Option<E | E2>, Tuple<[Chunk<Tuple<[K, C1 | C2 | C3]>>, State<K, A, B>]>> > => { switch (state._tag) { case "DrainLeft": return pullLeft.fold( (e) => Exit.fail(e), (leftChunk) => Exit.succeed( Tuple( leftChunk.map(({ tuple: [k, a] }) => Tuple(k, left(a))), new DrainLeft() ) ) ) case "DrainRight": return pullRight.fold( (e) => Exit.fail(e), (rightChunk) => Exit.succeed( Tuple( rightChunk.map(({ tuple: [k, b] }) => Tuple(k, right(b))), new DrainRight() ) ) ) case "PullBoth": { return pullLeft .unsome() .zipPar(pullRight.unsome()) .foldEffect( (e) => Effect.succeedNow(Exit.fail(Option.some(e))), ({ tuple: [a, b] }) => { if (a.isSome() && b.isSome()) { const leftChunk = a.value const rightChunk = b.value if (leftChunk.isEmpty() && rightChunk.isEmpty()) { return pull(new PullBoth(), pullLeft, pullRight) } else if (leftChunk.isEmpty()) { return pull(new PullLeft(rightChunk), pullLeft, pullRight) } else if (rightChunk.isEmpty()) { return pull(new PullRight(leftChunk), pullLeft, pullRight) } else { return Effect.succeedNow( Exit.succeed(mergeSortedByKeyChunk(leftChunk, rightChunk)) ) } } else if (a.isSome()) { const leftChunk = a.value return leftChunk.isEmpty() ? pull(new DrainLeft(), pullLeft, pullRight) : Effect.succeedNow( Exit.succeed( Tuple( leftChunk.map(({ tuple: [k, a] }) => Tuple(k, left(a))), new DrainLeft() ) ) ) } else if (b.isSome()) { const rightChunk = b.value return rightChunk.isEmpty() ? pull(new DrainLeft(), pullLeft, pullRight) : Effect.succeedNow( Exit.succeed( Tuple( rightChunk.map(({ tuple: [k, b] }) => Tuple(k, right(b))), new DrainRight() ) ) ) } else { return Effect.succeedNow(Exit.fail(Option.none)) } } ) } case "PullLeft": { const rightChunk = state.rightChunk return pullLeft.foldEffect( (option) => option.fold( (): Effect< unknown, never, Exit<Option<E>, Tuple<[Chunk<Tuple<[K, C2]>>, DrainRight]>> > => Effect.succeedNow( Exit.succeed( Tuple( rightChunk.map(({ tuple: [k, b] }) => Tuple(k, right(b))), new DrainRight() ) ) ), (e) => Effect.succeedNow(Exit.fail(Option.some(e))) ), (leftChunk) => leftChunk.isEmpty() ? pull(new PullLeft(rightChunk), pullLeft, pullRight) : Effect.succeedNow( Exit.succeed(mergeSortedByKeyChunk(leftChunk, rightChunk)) ) ) } case "PullRight": { const leftChunk = state.leftChunk return pullRight.foldEffect( (option) => option.fold( (): Effect< unknown, never, Exit<Option<E2>, Tuple<[Chunk<Tuple<[K, C1]>>, DrainLeft]>> > => Effect.succeedNow( Exit.succeed( Tuple( leftChunk.map(({ tuple: [k, a] }) => Tuple(k, left(a))), new DrainLeft() ) ) ), (e) => Effect.succeedNow(Exit.fail(Option.some(e))) ), (rightChunk) => rightChunk.isEmpty() ? pull(new PullRight(leftChunk), pullLeft, pullRight) : Effect.succeedNow( Exit.succeed(mergeSortedByKeyChunk(leftChunk, rightChunk)) ) ) } } } function mergeSortedByKeyChunk( leftChunk: Chunk<Tuple<[K, A]>>, rightChunk: Chunk<Tuple<[K, B]>> ): Tuple<[Chunk<Tuple<[K, C1 | C2 | C3]>>, State<K, A, B>]> { const builder = Chunk.builder<Tuple<[K, C1 | C2 | C3]>>() let state: State<K, A, B> | undefined let leftIndex = 0 let rightIndex = 0 let leftTuple = leftChunk.unsafeGet(leftIndex) let rightTuple = rightChunk.unsafeGet(rightIndex) let k1 = leftTuple.get(0) let a = leftTuple.get(1) let k2 = rightTuple.get(0) let b = rightTuple.get(1) let loop = true const hasNext = <T>(c: Chunk<T>, index: number) => index < c.size - 1 while (loop) { const compare = ord.compare(k1, k2) if (compare === 0) { builder.append(Tuple(k1, both(a, b))) if (hasNext(leftChunk, leftIndex) && hasNext(rightChunk, rightIndex)) { leftIndex += 1 rightIndex += 1 leftTuple = leftChunk.unsafeGet(leftIndex) rightTuple = rightChunk.unsafeGet(rightIndex) k1 = leftTuple.get(0) a = leftTuple.get(1) k2 = rightTuple.get(0) b = rightTuple.get(1) } else if (hasNext(leftChunk, leftIndex)) { state = new PullRight(leftChunk.drop(leftIndex + 1)) loop = false } else if (hasNext(rightChunk, rightIndex)) { state = new PullLeft(rightChunk.drop(rightIndex + 1)) loop = false } else { state = new PullBoth() loop = false } } else if (compare < 0) { builder.append(Tuple(k1, left(a))) if (hasNext(leftChunk, leftIndex)) { leftIndex += 1 leftTuple = leftChunk.unsafeGet(leftIndex) k1 = leftTuple.get(0) a = leftTuple.get(1) } else { const rightBuilder = Chunk.builder<Tuple<[K, B]>>() rightBuilder.append(rightTuple) while (hasNext(rightChunk, rightIndex)) { rightIndex += 1 rightTuple = rightChunk.unsafeGet(rightIndex) rightBuilder.append(rightTuple) state = new PullLeft(rightBuilder.build()) loop = false } } } else { builder.append(Tuple(k2, right(b))) if (hasNext(rightChunk, rightIndex)) { rightIndex += 1 rightTuple = rightChunk.unsafeGet(rightIndex) k2 = rightTuple.get(0) b = rightTuple.get(1) } else { const leftBuilder = Chunk.builder<Tuple<[K, A]>>() leftBuilder.append(leftTuple) while (hasNext(leftChunk, leftIndex)) { leftIndex += 1 leftTuple = leftChunk.unsafeGet(leftIndex) leftBuilder.append(leftTuple) state = new PullRight(leftBuilder.build()) loop = false } } } } return Tuple(builder.build(), state!) } return self.combineChunks(that, new PullBoth(), pull) } } /** * Zips this stream that is sorted by distinct keys and the specified stream * that is sorted by distinct keys to produce a new stream that is sorted by * distinct keys. Uses the functions `left`, `right`, and `both` to handle * the cases where a key and value exist in this stream, that stream, or * both streams. * * This allows zipping potentially unbounded streams of data by key in * constant space but the caller is responsible for ensuring that the * streams are sorted by distinct keys. * * @tsplus static ets/SortedByKey/Aspects zipAllSortedByKeyWith */ export const zipAllSortedByKeyWith = Pipeable(zipAllSortedByKeyWith_)
the_stack
export = sjcl; export as namespace sjcl; declare namespace sjcl { export var arrayBuffer: SjclArrayBufferModes; export var bn: BigNumberStatic; export var bitArray: BitArrayStatic; export var codec: SjclCodecs; export var hash: SjclHashes; export var exception: SjclExceptions; export var cipher: SjclCiphers; export var mode: SjclModes; export var misc: SjclMisc; export var ecc: SjclEllipticCurveCryptography; export var random: SjclRandom; export var prng: SjclRandomStatic; export var keyexchange: SjclKeyExchange; export var json: SjclJson; export var encrypt: SjclConvenienceEncryptor; export var decrypt: SjclConvenienceDecryptor; // ________________________________________________________________________ interface BigNumber { radix: number; maxMul: number; copy(): BigNumber; /// Initializes this with it, either as a bn, a number, or a hex string. initWith: TypeHelpers.BigNumberBinaryOperator; /// Returns true if "this" and "that" are equal. Calls fullReduce(). /// Equality test is in constant time. equals(that: BigNumber | number): boolean; /// Get the i'th limb of this, zero if i is too large. getLimb(index: number): number; /// Constant time comparison function. /// Returns 1 if this >= that, or zero otherwise. greaterEquals(that: BigNumber | number): boolean; /// Convert to a hex string. toString(): string; /// this += that. Does not normalize. addM: TypeHelpers.BigNumberBinaryOperator; /// this *= 2. Requires normalized; ends up normalized. doubleM(): BigNumber; /// this /= 2, rounded down. Requires normalized; ends up normalized. halveM(): BigNumber; /// this -= that. Does not normalize. subM: TypeHelpers.BigNumberBinaryOperator; mod: TypeHelpers.BigNumberBinaryOperator; /// return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. inverseMod: TypeHelpers.BigNumberBinaryOperator; /// this + that. Does not normalize. add: TypeHelpers.BigNumberBinaryOperator; /// this - that. Does not normalize. sub: TypeHelpers.BigNumberBinaryOperator; /// this * that. Normalizes and reduces. mul: TypeHelpers.BigNumberBinaryOperator; /// this ^ 2. Normalizes and reduces. square(): BigNumber; /// this ^ n. Uses square-and-multiply. Normalizes and reduces. power(n: BigNumber | number[] | number): BigNumber; /// this * that mod N mulmod: TypeHelpers.BigNumberTrinaryOperator; /// this ^ x mod N powermod: TypeHelpers.BigNumberTrinaryOperator; /// this ^ x mod N with Montomery reduction montpowermod: TypeHelpers.BigNumberTrinaryOperator; trim(): BigNumber; /// Reduce mod a modulus. Stubbed for subclassing. reduce(): BigNumber; /// Reduce and normalize. fullReduce(): BigNumber; /// Propagate carries. normalize(): BigNumber; /// Constant-time normalize. Does not allocate additional space. cnormalize(): BigNumber; /// Serialize to a bit array toBits(len?: number): BitArray; /// Return the length in bits, rounded up to the nearest byte. bitLength(): number; } interface BigNumberStatic { new (): BigNumber; new (n: BigNumber | number | string): BigNumber; fromBits(bits: BitArray): BigNumber; random: TypeHelpers.Bind1<number>; prime: { p127: PseudoMersennePrimeStatic; // Bernstein's prime for Curve25519 p25519: PseudoMersennePrimeStatic; // Koblitz primes p192k: PseudoMersennePrimeStatic; p224k: PseudoMersennePrimeStatic; p256k: PseudoMersennePrimeStatic; // NIST primes p192: PseudoMersennePrimeStatic; p224: PseudoMersennePrimeStatic; p256: PseudoMersennePrimeStatic; p384: PseudoMersennePrimeStatic; p521: PseudoMersennePrimeStatic; }; pseudoMersennePrime(exponent: number, coeff: number[][]): PseudoMersennePrimeStatic; } interface PseudoMersennePrime extends BigNumber { reduce(): PseudoMersennePrime; fullReduce(): PseudoMersennePrime; inverse(): PseudoMersennePrime; } interface PseudoMersennePrimeStatic extends BigNumberStatic { new (): PseudoMersennePrime; new (n: BigNumber | number | string): PseudoMersennePrime; } // ________________________________________________________________________ interface BitArray extends Array<number> {} interface BitArrayStatic { /// Array slices in units of bits. bitSlice(a: BitArray, bstart: number, bend: number): BitArray; /// Extract a number packed into a bit array. extract(a: BitArray, bstart: number, blength: number): number; /// Concatenate two bit arrays. concat(a1: BitArray, a2: BitArray): BitArray; /// Find the length of an array of bits. bitLength(a: BitArray): number; /// Truncate an array. clamp(a: BitArray, len: number): BitArray; /// Make a partial word for a bit array. partial(len: number, x: number, _end?: number): number; /// Get the number of bits used by a partial word. getPartial(x: number): number; /// Compare two arrays for equality in a predictable amount of time. equal(a: BitArray, b: BitArray): boolean; /// Shift an array right. _shiftRight(a: BitArray, shift: number, carry?: number, out?: BitArray): BitArray; /// xor a block of 4 words together. _xor4(x: number[], y: number[]): number[]; /// byteswap a word array inplace. (does not handle partial words) byteswapM(a: BitArray): BitArray; } // ________________________________________________________________________ interface SjclCodec<T> { fromBits(bits: BitArray): T; toBits(value: T): BitArray; } interface SjclArrayBufferCodec extends SjclCodec<ArrayBuffer> { fromBits(bits: BitArray, padding?: boolean, padding_count?: number): ArrayBuffer; hexDumpBuffer(buffer: ArrayBuffer): void; } interface SjclCodecs { arrayBuffer: SjclArrayBufferCodec; utf8String: SjclCodec<string>; hex: SjclCodec<string>; bytes: SjclCodec<number[]>; base32: SjclCodec<string>; base32hex: SjclCodec<string>; base64: SjclCodec<string>; base64url: SjclCodec<string>; z85: SjclCodec<string>; } // ________________________________________________________________________ interface SjclHash { reset(): SjclHash; update(data: BitArray | string): SjclHash; finalize(): BitArray; } interface SjclHashStatic { new (hash?: SjclHash): SjclHash; hash(data: BitArray | string): BitArray; } interface SjclHashes { sha1: SjclHashStatic; sha256: SjclHashStatic; sha512: SjclHashStatic; ripemd160: SjclHashStatic; } // ________________________________________________________________________ interface SjclExceptions { corrupt: SjclExceptionFactory; invalid: SjclExceptionFactory; bug: SjclExceptionFactory; notReady: SjclExceptionFactory; } interface SjclExceptionFactory { new (message: string): Error; } // ________________________________________________________________________ interface SjclCiphers { aes: SjclCipherStatic; } interface SjclCipher { encrypt(data: number[]): number[]; decrypt(data: number[]): number[]; } interface SjclCipherStatic { new (key: number[]): SjclCipher; } // ________________________________________________________________________ interface SjclModes { gcm: SjclGCMMode; ccm: SjclCCMMode; ocb2: SjclOCB2Mode; ocb2progressive: SjclOCB2ProgressiveMode; cbc: SjclCBCMode; ctr: SjclCTRMode; } interface SjclArrayBufferModes { ccm: SjclArrayBufferCCMMode; } interface SjclGCMMode { encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; } interface SjclArrayBufferCCMMode { compat_encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; compat_decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; encrypt( prf: SjclCipher, plaintext_buffer: ArrayBuffer, iv: BitArray, adata?: ArrayBuffer, tlen?: number, ol?: number, ): ArrayBuffer; decrypt( prf: SjclCipher, ciphertext_buffer: ArrayBuffer, iv: BitArray, tag: BitArray, adata?: ArrayBuffer, tlen?: number, ol?: number, ): ArrayBuffer; } interface SjclCCMMode { listenProgress(cb: (val: number) => void): void; unListenProgress(cb: (val: number) => void): void; encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; } interface SjclOCB2Mode { encrypt( prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean, ): BitArray; decrypt( prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean, ): BitArray; pmac(prf: SjclCipher, adata: BitArray): number[]; } interface SjclOCB2ProgressiveProcessor { process(data: BitArray): BitArray; finalize(): BitArray; } interface SjclOCB2ProgressiveMode { createEncryptor( prp: SjclCipher, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean, ): SjclOCB2ProgressiveProcessor; createDecryptor( prp: SjclCipher, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean, ): SjclOCB2ProgressiveProcessor; } interface SjclCBCMode { encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray): BitArray; decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray): BitArray; } interface SjclCTRMode { encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray): BitArray; decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray): BitArray; } // ________________________________________________________________________ interface PBKDF2Params { iter?: number | undefined; salt?: BitArray | undefined; } interface SjclMisc { pbkdf2( password: BitArray | string, salt: BitArray | string, count?: number, length?: number, Prff?: SjclPRFFamilyStatic, ): BitArray; hmac: SjclHMACStatic; cachedPbkdf2( password: string, obj?: PBKDF2Params, ): { key: BitArray; salt: BitArray; }; hkdf( ikm: BitArray, keyBitLength: number, salt: BitArray | string, info: BitArray | string, Hash?: SjclHashStatic, ): BitArray; scrypt( password: BitArray | string, salt: BitArray | string, N?: number, r?: number, p?: number, length?: number, Prff?: SjclPRFFamilyStatic, ): BitArray; } class SjclPRFFamily { encrypt(data: BitArray | string): BitArray; } interface SjclHMAC extends SjclPRFFamily { mac(data: BitArray | string): BitArray; reset(): void; update(data: BitArray | string): void; digest(): BitArray; } interface SjclPRFFamilyStatic { new (key: BitArray): SjclPRFFamily; } interface SjclHMACStatic { new (key: BitArray, Hash?: SjclHashStatic): SjclHMAC; } // ________________________________________________________________________ interface SjclEllipticCurveCryptography { point: SjclEllipticalPointStatic; pointJac: SjclPointJacobianStatic; curve: SjclEllipticalCurveStatic; curves: { c192: SjclEllipticalCurve; c224: SjclEllipticalCurve; c256: SjclEllipticalCurve; c384: SjclEllipticalCurve; c521: SjclEllipticalCurve; k192: SjclEllipticalCurve; k224: SjclEllipticalCurve; k256: SjclEllipticalCurve; }; curveName(curve: SjclEllipticalCurve): string; deserialize(key: SjclECCKeyPairData): SjclECCPublicKey; deserialize(key: SjclECCKeyPairData): SjclECCSecretKey; basicKey: SjclECCBasic; elGamal: SjclElGamal; ecdsa: SjclECDSA; } interface SjclEllipticalPoint { toJac(): SjclPointJacobian; mult(k: BigNumber): SjclEllipticalPoint; mult2(k: BigNumber, k2: BigNumber, affine2: SjclEllipticalPoint): SjclEllipticalPoint; multiples(): Array<SjclEllipticalPoint>; negate(): SjclEllipticalPoint; isValid(): boolean; toBits(): BitArray; } interface SjclEllipticalPointStatic { new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber): SjclEllipticalPoint; } interface SjclPointJacobian { add(T: SjclEllipticalPoint): SjclPointJacobian; doubl(): SjclPointJacobian; toAffine(): SjclEllipticalPoint; mult(k: BigNumber, affine: SjclEllipticalPoint): SjclPointJacobian; mult2( k1: BigNumber, affine: SjclEllipticalPoint, k2: BigNumber, affine2: SjclEllipticalPoint, ): SjclPointJacobian; negate(): SjclPointJacobian; isValid(): boolean; } interface SjclPointJacobianStatic { new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber, z?: BigNumber): SjclPointJacobian; toAffineMultiple(points: Array<SjclPointJacobian>): Array<SjclEllipticalPoint>; } interface SjclEllipticalCurve { fromBits(bits: BitArray): SjclEllipticalPoint; } interface SjclEllipticalCurveStatic { new ( Field: BigNumber, r: BigNumber, a: BigNumber, b: BigNumber, x: BigNumber, y: BigNumber, ): SjclEllipticalCurve; } interface SjclKeyPair<P extends SjclECCPublicKey, S extends SjclECCSecretKey> { pub: P; sec: S; } interface SjclKeysGenerator<P extends SjclECCPublicKey, S extends SjclECCSecretKey> { (curve: SjclEllipticalCurve | number, paranoia: number, sec?: BigNumber): SjclKeyPair<P, S>; } interface SjclECCKeyPairData { type: string; secretKey: boolean; point: string; curve: string; } interface SjclECCPublicKeyData { x: BitArray; y: BitArray; } class SjclECCPublicKey { serialize(): SjclECCKeyPairData; get(): SjclECCPublicKeyData; getType(): string; } class SjclECCSecretKey { serialize(): SjclECCKeyPairData; get(): BitArray; getType(): string; } interface SjclECCPublicKeyFactory<T extends SjclECCPublicKey> { new (curve: SjclEllipticalCurve, point: SjclEllipticalPoint | BitArray): T; } interface SjclECCSecretKeyFactory<T extends SjclECCSecretKey> { new (curve: SjclEllipticalCurve, exponent: BigNumber): T; } interface SjclECCBasic { publicKey: SjclECCPublicKeyFactory<SjclECCPublicKey>; secretKey: SjclECCSecretKeyFactory<SjclECCSecretKey>; generateKeys(cn: string): SjclKeysGenerator<SjclECCPublicKey, SjclECCSecretKey>; } class SjclElGamalPublicKey extends SjclECCPublicKey { kem( paranoia: number, ): { key: BitArray; tag: BitArray; }; } class SjclElGamalSecretKey extends SjclECCSecretKey { unkem(tag: BitArray): BitArray; dh(pk: SjclECCPublicKey): BitArray; dhJavaEc(pk: SjclECCPublicKey): BitArray; } interface SjclElGamal { publicKey: SjclECCPublicKeyFactory<SjclElGamalPublicKey>; secretKey: SjclECCSecretKeyFactory<SjclElGamalSecretKey>; generateKeys: SjclKeysGenerator<SjclElGamalPublicKey, SjclElGamalSecretKey>; } class SjclECDSAPublicKey extends SjclECCPublicKey { verify(hash: BitArray, rs: BitArray, fakeLegacyVersion: boolean): boolean; } class SjclECDSASecretKey extends SjclECCSecretKey { sign(hash: BitArray, paranoia: number, fakeLegacyVersion: boolean, fixedKForTesting?: BigNumber): BitArray; } interface SjclECDSA { publicKey: SjclECCPublicKeyFactory<SjclECDSAPublicKey>; secretKey: SjclECCSecretKeyFactory<SjclECDSASecretKey>; generateKeys: SjclKeysGenerator<SjclECDSAPublicKey, SjclECDSASecretKey>; } // ________________________________________________________________________ interface SjclRandom { randomWords(nwords: number, paranoia?: number): BitArray; setDefaultParanoia(paranoia: number, allowZeroParanoia: string): void; addEntropy(data: number | number[] | string, estimatedEntropy: number, source: string): void; isReady(paranoia?: number): boolean; getProgress(paranoia?: number): number; startCollectors(): void; stopCollectors(): void; addEventListener(name: string, cb: Function): void; removeEventListener(name: string, cb: Function): void; } interface SjclRandomStatic { new (defaultParanoia: number): SjclRandom; } // ________________________________________________________________________ interface SjclKeyExchange { srp: SjclSecureRemotePassword; } interface SjclSRPGroup { N: BigNumber; g: BigNumber; } interface SjclSecureRemotePassword { makeVerifier(username: string, password: string, salt: BitArray, group: SjclSRPGroup): BitArray; makeX(username: string, password: string, salt: BitArray): BitArray; knownGroup(i: number | string): SjclSRPGroup; } // ________________________________________________________________________ interface SjclCipherParams { v?: number | undefined; iter?: number | undefined; ks?: number | undefined; ts?: number | undefined; mode?: string | undefined; adata?: string | undefined; cipher?: string | undefined; } interface SjclCipherEncryptParams extends SjclCipherParams { salt: BitArray; iv: BitArray; } interface SjclCipherDecryptParams extends SjclCipherParams { salt?: BitArray | undefined; iv?: BitArray | undefined; } interface SjclCipherEncrypted extends SjclCipherEncryptParams { kemtag?: BitArray | undefined; ct: BitArray; } interface SjclCipherDecrypted extends SjclCipherEncrypted { key: BitArray; } interface SjclConvenienceEncryptor { ( password: SjclElGamalPublicKey | BitArray | string, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted, ): SjclCipherEncrypted; } interface SjclConvenienceDecryptor { ( password: SjclElGamalSecretKey | BitArray | string, ciphertext: SjclCipherEncrypted | string, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted, ): string; } interface SjclJson { encrypt: SjclConvenienceEncryptor; decrypt: SjclConvenienceDecryptor; encode(obj: Object): string; decode(obj: string): Object; } // ________________________________________________________________________ namespace TypeHelpers { interface One<T> { (value: T): BigNumber; } interface BigNumberBinaryOperator extends One<number>, One<string>, One<BigNumber> {} interface Two<T1, T2> { (x: T1, N: T2): BigNumber; } interface Bind1<T> extends Two<number, T>, Two<string, T>, Two<BigNumber, T> {} interface BigNumberTrinaryOperator extends Bind1<number>, Bind1<string>, Bind1<BigNumber> {} } }
the_stack
import { Address, Amount, ChainId, Hash, SendTransaction, SwapOfferTransaction, TokenTicker } from "@iov/bcp"; import { fromHex } from "@iov/encoding"; import Long from "long"; import { decodeAmount } from "./decodeobjects"; import { encodeMsg } from "./encodemsg"; import { encodeNumericId } from "./encodinghelpers"; import * as codecImpl from "./generated/codecimpl"; import { pubJson, sendTxBin, sendTxJson } from "./testdata.spec"; import { ActionKind, AddAccountCertificateTx, CreateEscrowTx, CreateMultisignatureTx, CreateProposalTx, DeleteAccountCertificateTx, DeleteAccountTx, DeleteAllAccountsTx, DeleteDomainTx, Participant, RegisterAccountTx, RegisterDomainTx, RegisterUsernameTx, ReleaseEscrowTx, RenewAccountTx, RenewDomainTx, ReplaceAccountMsgFeesTx, ReplaceAccountTargetsTx, ReturnEscrowTx, TransferAccountTx, TransferDomainTx, TransferUsernameTx, UpdateAccountConfigurationTx, UpdateEscrowPartiesTx, UpdateMultisignatureTx, UpdateTargetsOfUsernameTx, VoteOption, VoteTx, } from "./types"; /** A random user on an IOV testnet */ const alice = { bin: fromHex("ae8cf0f2d436db9ecbbe118cf1d1637d568797c9"), bech32: "tiov146x0puk5xmdeaja7zxx0r5tr04tg097fralsxd" as Address, }; describe("encodeMsg", () => { const defaultChainId = "registry-chain" as ChainId; const defaultSender = "tiov1dcg3fat5zrvw00xezzjk3jgedm7pg70y222af3" as Address; // weave address hex: b1ca7e78f74423ae01da3b51e676934d9105f282 const defaultRecipient = "tiov1k898u78hgs36uqw68dg7va5nfkgstu5z0fhz3f" as Address; const defaultArbiter = "tiov17yp0mh3yxwv6yxx386mxyfzlqnhe6q58edka6r" as Address; const defaultAmount: Amount = { quantity: "1000000001", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }; const defaultEscrowId = 4; it("works for testdata", () => { const tx = encodeMsg(sendTxJson); const encoded = Uint8Array.from(codecImpl.bnsd.Tx.encode(tx).finish()); expect(encoded).toEqual(sendTxBin); }); // Token sends it("works for SendTransaction", () => { const transaction: SendTransaction = { kind: "bcp/send", chainId: defaultChainId, amount: defaultAmount, sender: defaultSender, recipient: defaultRecipient, memo: "abc", }; const msg = encodeMsg(transaction).cashSendMsg!; expect(msg.source).toEqual(fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4")); expect(msg.destination).toEqual(fromHex("b1ca7e78f74423ae01da3b51e676934d9105f282")); expect(msg.memo).toEqual("abc"); expect(msg.amount!.whole).toEqual(1); expect(msg.amount!.fractional).toEqual(1); expect(msg.amount!.ticker).toEqual("CASH"); expect(msg.ref!.length).toEqual(0); }); it("works for SendTransaction with mismatched sender pubkey and address", () => { const transaction: SendTransaction = { kind: "bcp/send", chainId: defaultChainId, amount: { quantity: "1000000001", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, senderPubkey: pubJson, sender: defaultRecipient, recipient: defaultRecipient, memo: "abc", }; const msg = encodeMsg(transaction).cashSendMsg!; expect(msg.source).toEqual(fromHex("b1ca7e78f74423ae01da3b51e676934d9105f282")); expect(msg.destination).toEqual(fromHex("b1ca7e78f74423ae01da3b51e676934d9105f282")); expect(msg.memo).toEqual("abc"); expect(msg.amount!.whole).toEqual(1); expect(msg.amount!.fractional).toEqual(1); expect(msg.amount!.ticker).toEqual("CASH"); expect(msg.ref!.length).toEqual(0); }); // Usernames it("works for UpdateTargetsOfUsernameTx", () => { const addAddress: UpdateTargetsOfUsernameTx = { kind: "bns/update_targets_of_username", chainId: defaultChainId, username: "alice*iov", targets: [ { chainId: "other-land" as ChainId, address: "865765858O" as Address, }, ], }; const msg = encodeMsg(addAddress).usernameChangeTokenTargetsMsg!; expect(msg.username).toEqual("alice*iov"); expect(msg.newTargets![0].blockchainId).toEqual("other-land"); expect(msg.newTargets![0].address).toEqual("865765858O"); }); it("works for RegisterUsernameTx", () => { const registerUsername: RegisterUsernameTx = { kind: "bns/register_username", chainId: defaultChainId, username: "alice*iov", targets: [ { chainId: "chain1" as ChainId, address: "367X" as Address, }, { chainId: "chain3" as ChainId, address: "0xddffeeffddaa44" as Address, }, { chainId: "chain2" as ChainId, address: "0x00aabbddccffee" as Address, }, ], }; const msg = encodeMsg(registerUsername).usernameRegisterTokenMsg!; expect(msg.username).toEqual("alice*iov"); expect(msg.targets).toBeDefined(); expect(msg.targets!.length).toEqual(3); expect(msg.targets![0].blockchainId).toEqual("chain1"); expect(msg.targets![0].address).toEqual("367X"); expect(msg.targets![1].blockchainId).toEqual("chain3"); expect(msg.targets![1].address).toEqual("0xddffeeffddaa44"); expect(msg.targets![2].blockchainId).toEqual("chain2"); expect(msg.targets![2].address).toEqual("0x00aabbddccffee"); }); it("works for TransferUsernameTx", () => { const transfer: TransferUsernameTx = { kind: "bns/transfer_username", chainId: defaultChainId, username: "alice*iov", newOwner: defaultRecipient, }; const msg = encodeMsg(transfer).usernameTransferTokenMsg!; expect(msg.username).toEqual("alice*iov"); expect(msg.newOwner).toEqual(fromHex("b1ca7e78f74423ae01da3b51e676934d9105f282")); }); // Accounts it("works for UpdateAccountConfigurationTx", () => { const transfer: UpdateAccountConfigurationTx = { kind: "bns/update_account_configuration", chainId: defaultChainId, configuration: { owner: "tiov1p62uqw00znhr98gwp8vylyyul844aarjhe9duq" as Address, validDomain: "hole", validName: "rabbit", validBlockchainId: "wonderland", validBlockchainAddress: "12345W", domainRenew: 1234, domainGracePeriod: 12345, }, }; const msg = encodeMsg(transfer).accountUpdateConfigurationMsg!; expect(msg.patch?.owner).toEqual(fromHex("0e95c039ef14ee329d0e09d84f909cf9eb5ef472")); expect(msg.patch?.validDomain).toEqual("hole"); expect(msg.patch?.validName).toEqual("rabbit"); expect(msg.patch?.validBlockchainId).toEqual("wonderland"); expect(msg.patch?.validBlockchainAddress).toEqual("12345W"); expect(msg.patch?.domainRenew).toEqual(1234); expect(msg.patch?.domainGracePeriod).toEqual(12345); }); it("works for RegisterDomainTx", () => { const transfer: RegisterDomainTx = { kind: "bns/register_domain", chainId: defaultChainId, domain: "hole", admin: "tiov1p62uqw00znhr98gwp8vylyyul844aarjhe9duq" as Address, hasSuperuser: true, broker: "tiov1zg69v7yszg69v7yszg69v7yszg69v7ysy7xxgy" as Address, msgFees: [{ msgPath: "some-msg-path", fee: decodeAmount({ whole: 1, fractional: 2, ticker: "ASH" }) }], accountRenew: 1234, }; const msg = encodeMsg(transfer).accountRegisterDomainMsg!; expect(msg.domain).toEqual("hole"); expect(msg.admin).toEqual(fromHex("0e95c039ef14ee329d0e09d84f909cf9eb5ef472")); expect(msg.hasSuperuser).toEqual(true); expect(msg.broker).toEqual(fromHex("1234567890123456789012345678901234567890")); expect(msg.msgFees).toEqual([ { msgPath: "some-msg-path", fee: { whole: 1, fractional: 2, ticker: "ASH" } }, ]); expect(msg.accountRenew).toEqual(1234); }); it("works for TransferDomainTx", () => { const transfer: TransferDomainTx = { kind: "bns/transfer_domain", chainId: defaultChainId, domain: "hole", newAdmin: "tiov1p62uqw00znhr98gwp8vylyyul844aarjhe9duq" as Address, }; const msg = encodeMsg(transfer).accountTransferDomainMsg!; expect(msg.domain).toEqual("hole"); expect(msg.newAdmin).toEqual(fromHex("0e95c039ef14ee329d0e09d84f909cf9eb5ef472")); }); it("works for RenewDomainTx", () => { const transfer: RenewDomainTx = { kind: "bns/renew_domain", chainId: defaultChainId, domain: "hole", }; const msg = encodeMsg(transfer).accountRenewDomainMsg!; expect(msg.domain).toEqual("hole"); }); it("works for DeleteDomainTx", () => { const transfer: DeleteDomainTx = { kind: "bns/delete_domain", chainId: defaultChainId, domain: "hole", }; const msg = encodeMsg(transfer).accountDeleteDomainMsg!; expect(msg.domain).toEqual("hole"); }); it("works for RegisterAccountTx", () => { const transfer: RegisterAccountTx = { kind: "bns/register_account", chainId: defaultChainId, domain: "hole", name: "rabbit", owner: "tiov1p62uqw00znhr98gwp8vylyyul844aarjhe9duq" as Address, targets: [{ chainId: "wonderland" as ChainId, address: "12345W" as Address }], broker: "tiov1zg69v7yszg69v7yszg69v7yszg69v7ysy7xxgy" as Address, }; const msg = encodeMsg(transfer).accountRegisterAccountMsg!; expect(msg.domain).toEqual("hole"); expect(msg.name).toEqual("rabbit"); expect(msg.owner).toEqual(fromHex("0e95c039ef14ee329d0e09d84f909cf9eb5ef472")); expect(msg.targets).toEqual([{ blockchainId: "wonderland", address: "12345W" }]); expect(msg.broker).toEqual(fromHex("1234567890123456789012345678901234567890")); }); it("works for TransferAccountTx", () => { const transfer: TransferAccountTx = { kind: "bns/transfer_account", chainId: defaultChainId, domain: "hole", name: "rabbit", newOwner: "tiov1p62uqw00znhr98gwp8vylyyul844aarjhe9duq" as Address, }; const msg = encodeMsg(transfer).accountTransferAccountMsg!; expect(msg.domain).toEqual("hole"); expect(msg.name).toEqual("rabbit"); expect(msg.newOwner).toEqual(fromHex("0e95c039ef14ee329d0e09d84f909cf9eb5ef472")); }); it("works for ReplaceAccountTargetsTx", () => { const transfer: ReplaceAccountTargetsTx = { kind: "bns/replace_account_targets", chainId: defaultChainId, domain: "hole", name: "rabbit", newTargets: [{ chainId: "wonderland" as ChainId, address: "12345W" as Address }], }; const msg = encodeMsg(transfer).accountReplaceAccountTargetsMsg!; expect(msg.domain).toEqual("hole"); expect(msg.name).toEqual("rabbit"); expect(msg.newTargets).toEqual([{ blockchainId: "wonderland", address: "12345W" }]); }); it("works for DeleteAccountTx", () => { const transfer: DeleteAccountTx = { kind: "bns/delete_account", chainId: defaultChainId, domain: "hole", name: "rabbit", }; const msg = encodeMsg(transfer).accountDeleteAccountMsg!; expect(msg.domain).toEqual("hole"); expect(msg.name).toEqual("rabbit"); }); it("works for DeleteAllAccountsTx", () => { const transfer: DeleteAllAccountsTx = { kind: "bns/delete_all_accounts", chainId: defaultChainId, domain: "hole", }; const msg = encodeMsg(transfer).accountFlushDomainMsg!; expect(msg.domain).toEqual("hole"); }); it("works for RenewAccountTx", () => { const transfer: RenewAccountTx = { kind: "bns/renew_account", chainId: defaultChainId, domain: "hole", name: "rabbit", }; const msg = encodeMsg(transfer).accountRenewAccountMsg!; expect(msg.domain).toEqual("hole"); expect(msg.name).toEqual("rabbit"); }); it("works for AddAccountCertificateTx", () => { const transfer: AddAccountCertificateTx = { kind: "bns/add_account_certificate", chainId: defaultChainId, domain: "hole", name: "rabbit", certificate: fromHex("214390591e6ac697319f20887405915e9d2690fd"), }; const msg = encodeMsg(transfer).accountAddAccountCertificateMsg!; expect(msg.domain).toEqual("hole"); expect(msg.name).toEqual("rabbit"); expect(msg.certificate).toEqual(fromHex("214390591e6ac697319f20887405915e9d2690fd")); }); it("works for ReplaceAccountMsgFeesTx", () => { const transfer: ReplaceAccountMsgFeesTx = { kind: "bns/replace_account_msg_fees", chainId: defaultChainId, domain: "hole", newMsgFees: [ { msgPath: "some-msg-path", fee: decodeAmount({ whole: 1, fractional: 2, ticker: "ASH" }) }, ], }; const msg = encodeMsg(transfer).accountReplaceAccountMsgFeesMsg!; expect(msg.domain).toEqual("hole"); expect(msg.newMsgFees).toEqual([ { msgPath: "some-msg-path", fee: { whole: 1, fractional: 2, ticker: "ASH" } }, ]); }); it("works for DeleteAccountCertificateTx", () => { const transfer: DeleteAccountCertificateTx = { kind: "bns/delete_account_certificate", chainId: defaultChainId, domain: "hole", name: "rabbit", certificateHash: fromHex("214390591e6ac697319f20887405915e9d2690fd"), }; const msg = encodeMsg(transfer).accountDeleteAccountCertificateMsg!; expect(msg.domain).toEqual("hole"); expect(msg.name).toEqual("rabbit"); expect(msg.certificateHash).toEqual(fromHex("214390591e6ac697319f20887405915e9d2690fd")); }); // Multisignature contracts it("works for CreateMultisignatureTx", () => { const participants: readonly Participant[] = [ { address: "tiov1zg69v7yszg69v7yszg69v7yszg69v7ysy7xxgy" as Address, weight: 4, }, { address: "tiov140x77qfr40x77qfr40x77qfr40x77qfrj4zpp5" as Address, weight: 1, }, { address: "tiov1nxvenxvenxvenxvenxvenxvenxvenxverxe7mm" as Address, weight: 1, }, ]; // tslint:disable-next-line:readonly-array const iParticipants: codecImpl.multisig.IParticipant[] = [ { signature: fromHex("1234567890123456789012345678901234567890"), weight: 4, }, { signature: fromHex("abcdef0123abcdef0123abcdef0123abcdef0123"), weight: 1, }, { signature: fromHex("9999999999999999999999999999999999999999"), weight: 1, }, ]; const createMultisignature: CreateMultisignatureTx = { kind: "bns/create_multisignature_contract", chainId: defaultChainId, participants: participants, activationThreshold: 2, adminThreshold: 3, }; const msg = encodeMsg(createMultisignature).multisigCreateMsg!; expect(msg.participants).toEqual(iParticipants); expect(msg.activationThreshold).toEqual(2); expect(msg.adminThreshold).toEqual(3); }); it("works for UpdateMultisignatureTx", () => { const participants: readonly Participant[] = [ { address: "tiov1zg69v7yszg69v7yszg69v7yszg69v7ysy7xxgy" as Address, weight: 4, }, { address: "tiov140x77qfr40x77qfr40x77qfr40x77qfrj4zpp5" as Address, weight: 1, }, { address: "tiov1nxvenxvenxvenxvenxvenxvenxvenxverxe7mm" as Address, weight: 1, }, ]; // tslint:disable-next-line:readonly-array const iParticipants: codecImpl.multisig.IParticipant[] = [ { signature: fromHex("1234567890123456789012345678901234567890"), weight: 4, }, { signature: fromHex("abcdef0123abcdef0123abcdef0123abcdef0123"), weight: 1, }, { signature: fromHex("9999999999999999999999999999999999999999"), weight: 1, }, ]; const updateMultisignature: UpdateMultisignatureTx = { kind: "bns/update_multisignature_contract", chainId: defaultChainId, contractId: Number.MAX_SAFE_INTEGER, participants: participants, activationThreshold: 3, adminThreshold: 4, }; const msg = encodeMsg(updateMultisignature).multisigUpdateMsg!; expect(msg.contractId).toEqual(encodeNumericId(Number.MAX_SAFE_INTEGER)); expect(msg.participants).toEqual(iParticipants); expect(msg.activationThreshold).toEqual(3); expect(msg.adminThreshold).toEqual(4); }); // Escrows it("works for CreateEscrowTx", () => { const timeout = { timestamp: new Date().valueOf(), }; const memo = "testing 123"; const createEscrow: CreateEscrowTx = { kind: "bns/create_escrow", chainId: defaultChainId, sender: defaultSender, arbiter: defaultArbiter, recipient: defaultRecipient, amounts: [defaultAmount], timeout: timeout, memo: memo, }; const msg = encodeMsg(createEscrow).escrowCreateMsg!; expect(msg.metadata).toEqual({ schema: 1 }); expect(msg.source).toEqual(fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4")); expect(msg.arbiter).toEqual(fromHex("f102fdde243399a218d13eb662245f04ef9d0287")); expect(msg.destination).toEqual(fromHex("b1ca7e78f74423ae01da3b51e676934d9105f282")); expect(msg.amount!.length).toEqual(1); expect(msg.amount![0].whole).toEqual(1); expect(msg.amount![0].fractional).toEqual(1); expect(msg.amount![0].ticker).toEqual("CASH"); expect(msg.timeout).toEqual(timeout.timestamp); expect(msg.memo).toEqual(memo); }); it("works for ReleaseEscrowTx", () => { const releaseEscrow: ReleaseEscrowTx = { kind: "bns/release_escrow", chainId: defaultChainId, escrowId: defaultEscrowId, amounts: [defaultAmount], }; const msg = encodeMsg(releaseEscrow).escrowReleaseMsg!; expect(msg.metadata).toEqual({ schema: 1 }); expect(msg.escrowId).toEqual(fromHex("0000000000000004")); expect(msg.amount!.length).toEqual(1); expect(msg.amount![0].whole).toEqual(1); expect(msg.amount![0].fractional).toEqual(1); expect(msg.amount![0].ticker).toEqual("CASH"); }); it("works for ReturnEscrowTx", () => { const returnEscrow: ReturnEscrowTx = { kind: "bns/return_escrow", chainId: defaultChainId, escrowId: defaultEscrowId, }; const msg = encodeMsg(returnEscrow).escrowReturnMsg!; expect(msg.metadata).toEqual({ schema: 1 }); expect(msg.escrowId).toEqual(fromHex("0000000000000004")); }); it("works for UpdateEscrowPartiesTx", () => { const updateEscrowSender: UpdateEscrowPartiesTx = { kind: "bns/update_escrow_parties", chainId: defaultChainId, escrowId: defaultEscrowId, sender: defaultSender, }; const msg1 = encodeMsg(updateEscrowSender).escrowUpdatePartiesMsg!; expect(msg1.metadata).toEqual({ schema: 1 }); expect(msg1.escrowId).toEqual(fromHex("0000000000000004")); expect(msg1.source).toEqual(fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4")); const updateEscrowRecipient: UpdateEscrowPartiesTx = { kind: "bns/update_escrow_parties", chainId: defaultChainId, escrowId: defaultEscrowId, recipient: defaultRecipient, }; const msg2 = encodeMsg(updateEscrowRecipient).escrowUpdatePartiesMsg!; expect(msg2.metadata).toEqual({ schema: 1 }); expect(msg2.escrowId).toEqual(fromHex("0000000000000004")); expect(msg2.destination).toEqual(fromHex("b1ca7e78f74423ae01da3b51e676934d9105f282")); const updateEscrowArbiter: UpdateEscrowPartiesTx = { kind: "bns/update_escrow_parties", chainId: defaultChainId, escrowId: defaultEscrowId, arbiter: defaultArbiter, }; const msg3 = encodeMsg(updateEscrowArbiter).escrowUpdatePartiesMsg!; expect(msg3.metadata).toEqual({ schema: 1 }); expect(msg3.escrowId).toEqual(fromHex("0000000000000004")); expect(msg3.arbiter).toEqual(fromHex("f102fdde243399a218d13eb662245f04ef9d0287")); }); it("only updates one party at a time", () => { const updateEscrowParties: UpdateEscrowPartiesTx = { kind: "bns/update_escrow_parties", chainId: defaultChainId, escrowId: defaultEscrowId, sender: defaultSender, arbiter: defaultArbiter, }; expect(() => encodeMsg(updateEscrowParties)).toThrowError(/only one party can be updated at a time/i); }); // Governance describe("CreateProposalTx", () => { it("works with CreateTextResolution action", () => { const createProposal: CreateProposalTx = { kind: "bns/create_proposal", chainId: defaultChainId, title: "Why not try this?", action: { kind: ActionKind.CreateTextResolution, resolution: "la la la", }, description: "foo bar", electionRuleId: 4822531585417728, startTime: 1122334455, author: defaultSender, }; const msg = encodeMsg(createProposal).govCreateProposalMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, title: "Why not try this?", rawOption: codecImpl.bnsd.ProposalOptions.encode({ govCreateTextResolutionMsg: { metadata: { schema: 1 }, resolution: "la la la", }, }).finish(), description: "foo bar", electionRuleId: fromHex("0011221122112200"), startTime: 1122334455, author: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), }); }); it("works with ExecuteProposalBatch action with array of Send actions", () => { const createProposal: CreateProposalTx = { kind: "bns/create_proposal", chainId: defaultChainId, title: "Why not try this?", action: { kind: ActionKind.ExecuteProposalBatch, messages: [ { kind: ActionKind.Send, sender: defaultSender, recipient: defaultRecipient, amount: defaultAmount, memo: "say hi", }, { kind: ActionKind.Send, sender: defaultRecipient, recipient: defaultSender, amount: { quantity: "3000000003", fractionalDigits: 9, tokenTicker: "MASH" as TokenTicker, }, }, ], }, description: "foo bar", electionRuleId: 4822531585417728, startTime: 1122334455, author: defaultSender, }; const msg = encodeMsg(createProposal).govCreateProposalMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, title: "Why not try this?", rawOption: codecImpl.bnsd.ProposalOptions.encode({ executeProposalBatchMsg: { messages: [ { sendMsg: { metadata: { schema: 1 }, source: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), destination: fromHex("b1ca7e78f74423ae01da3b51e676934d9105f282"), amount: { whole: 1, fractional: 1, ticker: "CASH", }, memo: "say hi", }, }, { sendMsg: { metadata: { schema: 1 }, source: fromHex("b1ca7e78f74423ae01da3b51e676934d9105f282"), destination: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), amount: { whole: 3, fractional: 3, ticker: "MASH", }, }, }, ], }, }).finish(), description: "foo bar", electionRuleId: fromHex("0011221122112200"), startTime: 1122334455, author: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), }); }); it("works with ReleaseEscrow action", () => { const createProposal: CreateProposalTx = { kind: "bns/create_proposal", chainId: defaultChainId, title: "Why not try this?", action: { kind: ActionKind.ReleaseEscrow, escrowId: defaultEscrowId, amount: defaultAmount, }, description: "foo bar", electionRuleId: 4822531585417728, startTime: 1122334455, author: defaultSender, }; const msg = encodeMsg(createProposal).govCreateProposalMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, title: "Why not try this?", rawOption: codecImpl.bnsd.ProposalOptions.encode({ escrowReleaseMsg: { metadata: { schema: 1 }, escrowId: fromHex("0000000000000004"), amount: [ { whole: 1, fractional: 1, ticker: "CASH", }, ], }, }).finish(), description: "foo bar", electionRuleId: fromHex("0011221122112200"), startTime: 1122334455, author: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), }); }); it("works with SetValidators action", () => { const createProposal: CreateProposalTx = { kind: "bns/create_proposal", chainId: defaultChainId, title: "Why not try this?", action: { kind: ActionKind.SetValidators, validatorUpdates: { // eslint-disable-next-line @typescript-eslint/camelcase ed25519_0902bb5de30ccb15b6decb6aa1fdb4f0c1c7317df62dcafa81ccad82ce88dd22: { power: 5 }, }, }, description: "foo bar", electionRuleId: 4822531585417728, startTime: 1122334455, author: defaultSender, }; const msg = encodeMsg(createProposal).govCreateProposalMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, title: "Why not try this?", rawOption: codecImpl.bnsd.ProposalOptions.encode({ validatorsApplyDiffMsg: { metadata: { schema: 1 }, validatorUpdates: [ { pubKey: { type: "ed25519", data: fromHex("0902bb5de30ccb15b6decb6aa1fdb4f0c1c7317df62dcafa81ccad82ce88dd22"), }, power: Long.fromNumber(5), }, ], }, }).finish(), description: "foo bar", electionRuleId: fromHex("0011221122112200"), startTime: 1122334455, author: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), }); }); it("works with UpdateElectionRule action", () => { const createProposal: CreateProposalTx = { kind: "bns/create_proposal", chainId: defaultChainId, title: "Why not try this?", action: { kind: ActionKind.UpdateElectionRule, electionRuleId: 5, threshold: { numerator: 2, denominator: 7, }, quorum: { numerator: 4, denominator: 5, }, votingPeriod: 3600, }, description: "foo bar", electionRuleId: 4822531585417728, startTime: 1122334455, author: defaultSender, }; const msg = encodeMsg(createProposal).govCreateProposalMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, title: "Why not try this?", rawOption: codecImpl.bnsd.ProposalOptions.encode({ govUpdateElectionRuleMsg: { metadata: { schema: 1 }, electionRuleId: fromHex("0000000000000005"), threshold: { numerator: 2, denominator: 7, }, quorum: { numerator: 4, denominator: 5, }, votingPeriod: 3600, }, }).finish(), description: "foo bar", electionRuleId: fromHex("0011221122112200"), startTime: 1122334455, author: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), }); }); it("works with UpdateElectorate action", () => { const createProposal: CreateProposalTx = { kind: "bns/create_proposal", chainId: defaultChainId, title: "Why not try this?", action: { kind: ActionKind.UpdateElectorate, electorateId: 5, diffElectors: { [defaultSender]: { weight: 8 }, }, }, description: "foo bar", electionRuleId: 4822531585417728, startTime: 1122334455, author: defaultSender, }; const msg = encodeMsg(createProposal).govCreateProposalMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, title: "Why not try this?", rawOption: codecImpl.bnsd.ProposalOptions.encode({ govUpdateElectorateMsg: { metadata: { schema: 1 }, electorateId: fromHex("0000000000000005"), diffElectors: [{ address: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), weight: 8 }], }, }).finish(), description: "foo bar", electionRuleId: fromHex("0011221122112200"), startTime: 1122334455, author: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), }); }); it("works with SetMsgFee action", () => { const createProposal: CreateProposalTx = { kind: "bns/create_proposal", chainId: defaultChainId, title: "Why not try this?", action: { kind: ActionKind.SetMsgFee, msgPath: "username/register_token", fee: { fractionalDigits: 9, quantity: "10000000001", tokenTicker: "CASH" as TokenTicker, }, }, description: "foo bar", electionRuleId: 4822531585417728, startTime: 1122334455, author: defaultSender, }; const msg = encodeMsg(createProposal).govCreateProposalMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, title: "Why not try this?", rawOption: codecImpl.bnsd.ProposalOptions.encode({ msgfeeSetMsgFeeMsg: { metadata: { schema: 1 }, msgPath: "username/register_token", fee: { whole: 10, fractional: 1, ticker: "CASH", }, }, }).finish(), description: "foo bar", electionRuleId: fromHex("0011221122112200"), startTime: 1122334455, author: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), }); }); it("works with ExecuteMigration action", () => { const createProposal: CreateProposalTx = { kind: "bns/create_proposal", chainId: defaultChainId, title: "Why not try this?", action: { kind: ActionKind.ExecuteMigration, id: "4gh48 u34ug384g34 jj3f232f", }, description: "foo bar", electionRuleId: 4822531585417728, startTime: 1122334455, author: defaultSender, }; const msg = encodeMsg(createProposal).govCreateProposalMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, title: "Why not try this?", rawOption: codecImpl.bnsd.ProposalOptions.encode({ datamigrationExecuteMigrationMsg: { metadata: { schema: 1 }, migrationId: "4gh48 u34ug384g34 jj3f232f", }, }).finish(), description: "foo bar", electionRuleId: fromHex("0011221122112200"), startTime: 1122334455, author: fromHex("6e1114f57410d8e7bcd910a568c9196efc1479e4"), }); }); }); describe("VoteTx", () => { it("works for VoteTx with voter set", () => { const vote: VoteTx = { kind: "bns/vote", chainId: defaultChainId, proposalId: 733292968738, selection: VoteOption.Abstain, voter: alice.bech32, }; const msg = encodeMsg(vote).govVoteMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, proposalId: fromHex("000000AABBAABB22"), selected: codecImpl.gov.VoteOption.VOTE_OPTION_ABSTAIN, voter: alice.bin, }); }); it("throws if voter is not set (in strict mode)", () => { const vote: VoteTx = { kind: "bns/vote", chainId: defaultChainId, proposalId: 733292968738, selection: VoteOption.Abstain, voter: null, }; expect(() => encodeMsg(vote)).toThrowError(/VoteTx\.voter must be set/i); }); it("works for VoteTx with no voter set (in non-strict mode)", () => { const vote: VoteTx = { kind: "bns/vote", chainId: defaultChainId, proposalId: 733292968738, selection: VoteOption.Abstain, voter: null, }; const msg = encodeMsg(vote, false).govVoteMsg!; expect(msg).toEqual({ metadata: { schema: 1 }, proposalId: fromHex("000000AABBAABB22"), selected: codecImpl.gov.VoteOption.VOTE_OPTION_ABSTAIN, voter: undefined, }); }); }); // Other it("encodes unset and empty memo the same way", () => { { const memoUnset: SendTransaction = { kind: "bcp/send", chainId: defaultChainId, sender: defaultSender, amount: defaultAmount, recipient: "tiov1k898u78hgs36uqw68dg7va5nfkgstu5z0fhz3f" as Address, }; const memoEmpty: SendTransaction = { kind: "bcp/send", chainId: defaultChainId, sender: defaultSender, amount: defaultAmount, recipient: "tiov1k898u78hgs36uqw68dg7va5nfkgstu5z0fhz3f" as Address, memo: "", }; expect(encodeMsg(memoUnset)).toEqual(encodeMsg(memoEmpty)); } { const memoUnset: SwapOfferTransaction = { kind: "bcp/swap_offer", chainId: defaultChainId, amounts: [], sender: "tiov1dcg3fat5zrvw00xezzjk3jgedm7pg70y222af3" as Address, recipient: "tiov1k898u78hgs36uqw68dg7va5nfkgstu5z0fhz3f" as Address, timeout: { timestamp: 22 }, hash: fromHex("aabbccdd") as Hash, }; const memoEmpty: SwapOfferTransaction = { kind: "bcp/swap_offer", chainId: defaultChainId, amounts: [], sender: "tiov1dcg3fat5zrvw00xezzjk3jgedm7pg70y222af3" as Address, recipient: "tiov1k898u78hgs36uqw68dg7va5nfkgstu5z0fhz3f" as Address, timeout: { timestamp: 22 }, hash: fromHex("aabbccdd") as Hash, memo: "", }; expect(encodeMsg(memoUnset)).toEqual(encodeMsg(memoEmpty)); } }); it("throws for transactions with invalid memo length", () => { { const transaction: SendTransaction = { kind: "bcp/send", chainId: defaultChainId, amount: { quantity: "1000000001", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, sender: defaultRecipient, recipient: defaultRecipient, // max length is 128; this emoji has string length 3 but byte length 7 memo: "a".repeat(122) + "7️⃣", }; expect(() => encodeMsg(transaction)).toThrowError(/invalid memo length/i); } { const transaction: SwapOfferTransaction = { kind: "bcp/swap_offer", chainId: defaultChainId, amounts: [], sender: "tiov1dcg3fat5zrvw00xezzjk3jgedm7pg70y222af3" as Address, recipient: "tiov1k898u78hgs36uqw68dg7va5nfkgstu5z0fhz3f" as Address, timeout: { timestamp: 22 }, hash: fromHex("aabbccdd") as Hash, // max length is 128; this emoji has string length 3 but byte length 7 memo: "a".repeat(122) + "7️⃣", }; expect(() => encodeMsg(transaction)).toThrowError(/invalid memo length/i); } }); });
the_stack
* @module OrbitGT */ //package orbitgt.spatial.ecrs; type int8 = number; type int16 = number; type int32 = number; type float32 = number; type float64 = number; import { Coordinate } from "../geom/Coordinate"; import { Registry } from "./Registry"; import { Unit } from "./Unit"; /** * Class Ellipsoid defines the parameters of an earth ellipsoid. * * Based on the following document: * * Coordinate Conversions and Transformations including Formulas * Guidance Note Number 7, part 2 * Revised May 2005 * Available at: http://www.epsg.org/ * * Geocentric coordinates are defined as follows: * The point (0,0,0) denotes the center of the ellipsoid. The z-axis is defined as being parallel to the earth rotational axis, pointing towards north. * The x-axis intersects the ellipsoid at the 0 deg latitude, 0 deg longitude point. * * @version 1.0 July 2005 */ /** @internal */ export class Ellipsoid { /** The code */ private _code: int32; /** The name */ private _name: string; /** The code of the unit of measure */ private _unitCode: int32; /** Semi-major axis (meter) */ private _a: float64; /** Semi-minor axis (meter) (derived) */ private _b: float64; /** Flattening (derived) */ private _f: float64; /** Inverse flattening */ private _invF: float64; /** Eccentricity (derived) */ private _e: float64; /** Eccentricity squared (derived) */ private _e2: float64; /** * Create a new ellipsoid. * @param code the code. * @param name the name. * @param unitCode the code of the unit of measure. * @param a the semi-major axis. * @param invF the inverse flattening (value like 300, not like 1/300). * @param b the semi-minor axis. */ public constructor(code: int32, name: string, unitCode: int32, a: float64, invF: float64, b: float64) { /* Store parameters */ this._code = code; this._name = name; this._unitCode = unitCode; this._a = (unitCode == Unit.METER) ? a : Registry.getUnit(this._unitCode).toStandard(a); this._invF = invF; this._b = (unitCode == Unit.METER) ? b : Registry.getUnit(this._unitCode).toStandard(b); /* Derive parameters */ if (this._invF == 0.0) this._invF = a / (a - b); this._f = (1.0 / this._invF); if (this._b == 0.0) this._b = this._a * (1.0 - this._f); this._e = Math.sqrt(2.0 * this._f - this._f * this._f); this._e2 = this._e * this._e; // or = (a*a-b*b)/(a*a); } /** * Get the code. * @return the code. */ public getCode(): int32 { return this._code; } /** * Get the name. * @return the name. */ public getName(): string { return this._name; } /** * Get the code of the unit of measure. * @return the code of the unit of measure. */ public getUnitCode(): int32 { return this._unitCode; } /** * Get the semi-major axis (in meter). * @return the semi-major axis. */ public getA(): float64 { return this._a; } /** * Get the semi-minor axis (in meter). * @return the semi-minor axis. */ public getB(): float64 { return this._b; } /** * Get the flattening. * @return the flattening. */ public getF(): float64 { return this._f; } /** * Get the inverse flattening. * @return the inverse flattening. */ public getInvF(): float64 { return this._invF; } /** * Get the eccentricity. * @return the eccentricity. */ public getE(): float64 { return this._e; } /** * Get the radius of curvature of the ellipsoid in the plane of the meridian at a given latitude (how latitude curves). * @param lat the latitude (in radians). * @return a radius (in meter). */ public getMeridianRadius(lat: float64): float64 { // Formula: see http://en.wikipedia.org/wiki/Latitude let t: float64 = this._e * Math.sin(lat); return this._a * (1.0 - this._e2) / Math.pow(1.0 - t * t, 3.5); } /** * Get the radius of the circle defined by all points at a certain latitude (a circle of latitude, also called a parallel) (a at latitude 0, 0 at latitude 90) (how longitude curves). * @param lat the latitude (in radians). * @return a radius (in meter). */ public getParallelRadius(lat: float64): float64 { // Formula: see http://en.wikipedia.org/wiki/Longitude let t: float64 = this._e * Math.sin(lat); return this._a * Math.cos(lat) / Math.sqrt(1.0 - t * t); } /** * Get the radius of curvature of the ellipsoid perpendicular to the meridian at a given latitude (a at latitude 0, a*a/b at latitude 90). * @param lat the latitude (in radians). * @return a radius (in meter). */ public getPrimeVerticalRadius(lat: float64): float64 { let t: float64 = this._e * Math.sin(lat); return this._a / Math.sqrt(1.0 - t * t); } /** * Get the radius of curvature of the ellipsoid perpendicular to the meridian at a given latitude (a at latitude 0, a*a/b at latitude 90). * @param lat the latitude (in radians). * @param sinLat the sinus of the latitude. * @return a radius (in meter). */ private getPrimeVerticalRadius2(lat: float64, sinLat: float64): float64 { let t: float64 = this._e * sinLat; return this._a / Math.sqrt(1.0 - t * t); } /** * Get the number of meter per radian of longitude. * @param lat the latitude (in radians). * @return the number of meter per radian. */ public getMeterPerRadOfLon(lat: float64): float64 { return this.getParallelRadius(lat); } /** * Get the number of meter per degree of longitude. * @param lat the latitude (in radians). * @return the number of meter per degree. */ public getMeterPerDegreeOfLon(lat: float64): float64 { return this.getMeterPerRadOfLon(lat) * Math.PI / 180.0; } /** * Get the number of meter per radian of latitude. * @param lat the latitude (in radians). * @return the number of meter per radian. */ public getMeterPerRadOfLat(lat: float64): float64 { return this.getMeridianRadius(lat); } /** * Get the number of meter per degree of latitude. * @param lat the latitude (in radians). * @return the number of meter per degree. */ public getMeterPerDegreeOfLat(lat: float64): float64 { return this.getMeterPerRadOfLat(lat) * Math.PI / 180.0; } /** * Calculate the secant. * @param v an angle (in radians). * @return the secant. */ private static sec(v: float64): float64 { return 1.0 / Math.cos(v); } /** * Convert 3D geographic coordinates to 3D geocentric coordinates. * See the EPSG Guidance Note, 2.2.1 * @param geographic the geographic coordinates (lon(x) and lat(y) in radians, height(z) in meter). * @param geocentric the new geocentric coordinates (in meter) (the result object). */ public toGeoCentric(geographic: Coordinate, geocentric: Coordinate): void { /* Get the parameters */ let lon: float64 = geographic.getX(); let lat: float64 = geographic.getY(); let h: float64 = geographic.getZ(); /* Calculate */ let sinLat: float64 = Math.sin(lat); let v: float64 = this.getPrimeVerticalRadius2(lat, sinLat); let s: float64 = (v + h) * Math.cos(lat); let x: float64 = s * Math.cos(lon); let y: float64 = s * Math.sin(lon); let z: float64 = ((1.0 - this._e2) * v + h) * sinLat; /* Store the new coordinates */ geocentric.setX(x); geocentric.setY(y); geocentric.setZ(z); } /** * Convert 3D geographic coordinates to 3D geocentric coordinates. * See the EPSG Guidance Note, 2.2.1 * @param geographic the geographic coordinates (lon(x) and lat(y) in degrees, height(z) in meter). * @param geocentric the new geocentric coordinates (in meter) (the result object). */ public toGeoCentricDeg(geographic: Coordinate, geocentric: Coordinate): void { /* Get the parameters */ let lon: float64 = geographic.getX() / 180.0 * Math.PI; let lat: float64 = geographic.getY() / 180.0 * Math.PI; let h: float64 = geographic.getZ(); /* Calculate */ let sinLat: float64 = Math.sin(lat); let v: float64 = this.getPrimeVerticalRadius2(lat, sinLat); let s: float64 = (v + h) * Math.cos(lat); let x: float64 = s * Math.cos(lon); let y: float64 = s * Math.sin(lon); let z: float64 = ((1.0 - this._e2) * v + h) * sinLat; /* Store the new coordinates */ geocentric.setX(x); geocentric.setY(y); geocentric.setZ(z); } /** * Convert 3D geocentric coordinates to 3D geographic coordinates. * See the EPSG Guidance Note, 2.2.1 * @param geocentric the geocentric coordinates (in meter). * @param geographic the new geographic coordinates (lon(x) and lat(y) in radians, height(z) in meter) (the result object). */ public toGeoGraphic(geocentric: Coordinate, geographic: Coordinate): void { /* Get the parameters */ let x: float64 = geocentric.getX(); let y: float64 = geocentric.getY(); let z: float64 = geocentric.getZ(); /* Calculate */ let r: float64 = Math.sqrt(x * x + y * y); let ir: float64 = (1.0 / r); let lat: float64 = Math.atan(z * ir); for (let i: number = 0; i < 7; i++) { let sinLat: float64 = Math.sin(lat); let vi: float64 = this.getPrimeVerticalRadius2(lat, sinLat); lat = Math.atan((z + this._e2 * vi * sinLat) * ir); } let lon: float64 = Math.atan2(y, x); let v: float64 = this.getPrimeVerticalRadius(lat); let h: float64 = x * Ellipsoid.sec(lon) * Ellipsoid.sec(lat) - v; /* Store the new coordinates */ geographic.setX(lon); geographic.setY(lat); geographic.setZ(h); // // loop lat error: // // i=0: 0.0031239393816600014 // km level // i=1: 6.753891540589585E-6 // m level // i=2: 1.4568768968992174E-8 // mm level // i=3: 3.1426083957342144E-11 // um level // i=4: 6.783462680459706E-14 // nm level // i=5: 1.1102230246251565E-16 // atomic level // i=6: 0.0 // // EPSG example for the WGS84 datum/ellipsoid: // X = 3771793.97; // Y = 140253.34; // Z = 5124304.35; // lat = 53.8093944; (degrees) // lon = 2.12955; (degrees) // h = 73.001873; } /** * Convert 3D geocentric coordinates to 3D geographic coordinates. * See the EPSG Guidance Note, 2.2.1 * @param geocentric the geocentric coordinates (in meter). * @param geographic the new geographic coordinates (lon(x) and lat(y) in degrees, height(z) in meter) (the result object). */ public toGeoGraphicDeg(geocentric: Coordinate, geographic: Coordinate): void { /* Get the parameters */ let x: float64 = geocentric.getX(); let y: float64 = geocentric.getY(); let z: float64 = geocentric.getZ(); /* Calculate */ let r: float64 = Math.sqrt(x * x + y * y); let ir: float64 = (1.0 / r); let lat: float64 = Math.atan(z * ir); for (let i: number = 0; i < 7; i++) { let sinLat: float64 = Math.sin(lat); let vi: float64 = this.getPrimeVerticalRadius2(lat, sinLat); lat = Math.atan((z + this._e2 * vi * sinLat) * ir); } let lon: float64 = Math.atan2(y, x); let v: float64 = this.getPrimeVerticalRadius(lat); let h: float64 = x * Ellipsoid.sec(lon) * Ellipsoid.sec(lat) - v; /* Store the new coordinates */ geographic.setX(lon / Math.PI * 180.0); geographic.setY(lat / Math.PI * 180.0); geographic.setZ(h); } /** * Check if another ellipsoid is compatible with this one. * @param other the other ellipsoid. * @return true if compatible. */ public isCompatible(other: Ellipsoid): boolean { if (other._code == this._code) return true; if (other._unitCode != this._unitCode) return false; if (Math.abs(other._a - this._a) > 0.001) return false; if (Math.abs(other._b - this._b) > 0.001) return false; return true; } /** * The standard toString method. * @see Object#toString */ public toString(): string { return "[Ellipsoid:code=" + this._code + ",name='" + this._name + "']"; } }
the_stack
import { Message, SignedMessage, Signature, KeyInfo, DEFAULT_HD_PATH, TEST_DEFAULT_HD_PATH, MethodMultisig, Cid, ChainEpoch, MethodInit } from "../Types"; import { BaseWalletProvider } from "./BaseWalletProvider"; import { MultisigProviderInterface, WalletProviderInterface } from "../ProviderInterfaces"; import { Keystore } from "../../utils/keystore"; import { LightWalletSigner } from "../../signers/LightWalletSigner"; import { LotusClient } from "../.."; import { addressAsBytes } from "@zondax/filecoin-signing-tools" import cbor from "ipld-dag-cbor"; import cid from "cids"; import BigNumber from "bignumber.js"; import { createApproveMessage, createCancelMessage, createProposeMessage } from "../../utils/msig"; interface LighWalletOptions { encKeystore?: string; hdPathString?: string; seedPhrase?: string; password?: string; } export class LightWalletProvider extends BaseWalletProvider implements WalletProviderInterface, MultisigProviderInterface { public keystore!: Keystore; private hdPathString = DEFAULT_HD_PATH; private signer!: LightWalletSigner; private pwdCallback: Function; constructor(client: LotusClient, pwdCallback: Function, path: string = DEFAULT_HD_PATH,) { super(client); this.pwdCallback = pwdCallback; if (path === 'test' || !path) this.hdPathString = TEST_DEFAULT_HD_PATH; } public async newAddress(): Promise<string> { await this.keystore.newAddress(1, this.pwdCallback()) const addresses = await this.getAddresses(); return addresses[addresses.length -1]; } public async deleteAddress(address: string): Promise<void> { await this.keystore.deleteAddress(address, this.pwdCallback()); } public async hasAddress(address: string): Promise<boolean> { return this.keystore.hasAddress(address); } public async exportPrivateKey(address: string): Promise<KeyInfo> { const pk = await this.keystore.getPrivateKey(address, this.pwdCallback()); return { Type: '1', PrivateKey: pk as any, //convert to uint8 array ? }; } public async getAddresses(): Promise<string[]> { return await this.keystore.getAddresses(); } public async getDefaultAddress(): Promise<string> { return await this.keystore.getDefaultAddress(); } public async setDefaultAddress(address: string): Promise<void> { this.keystore.setDefaultAddress(address) } public async sendMessage(msg: Message): Promise<SignedMessage> { const signedMessage: SignedMessage | undefined = await this.signMessage(msg); if (signedMessage) { await this.sendSignedMessage(signedMessage); return signedMessage as SignedMessage; } return undefined as any; } public async signMessage(msg: Message): Promise<SignedMessage> { return await this.signer.sign(msg, this.pwdCallback()); } //todo public async sign(data: string | ArrayBuffer): Promise<Signature> { return undefined as any; } //todo public async verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise<boolean> { return undefined as any; } //MultisigProvider Implementation /** * creates a multisig wallet * @param requiredNumberOfSenders * @param approvingAddresses * @param unlockDuration * @param initialBalance * @param senderAddressOfCreateMsg */ public async msigCreate( requiredNumberOfSenders: number, approvingAddresses: string[], startEpoch: ChainEpoch, unlockDuration: ChainEpoch, initialBalance: string, senderAddressOfCreateMsg: string, ): Promise<Cid> { const addresses: any[] = []; approvingAddresses.forEach(address => { addresses.push(addressAsBytes(address)); }); const constructorParams = [addresses, requiredNumberOfSenders, unlockDuration, startEpoch]; const serializedConstructorParams = cbor.util.serialize(constructorParams); const MultisigActorCodeID = new cid('bafkqadtgnfwc6mrpnv2wy5djonuwo'); const execParams = [ MultisigActorCodeID, serializedConstructorParams, ]; const serializedParams = cbor.util.serialize(execParams); const buff = Buffer.from(serializedParams); let messageWithoutGasParams = { From: senderAddressOfCreateMsg, To: "t01", Value: new BigNumber(initialBalance), Method: MethodInit.Exec, Params: buff.toString('base64') }; const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * proposes a multisig message * @param address * @param recipientAddres * @param value * @param senderAddressOfProposeMsg */ public async msigProposeTransfer( address: string, recipientAddres: string, value: string, senderAddressOfProposeMsg: string, ): Promise<Cid> { const params: any[] = []; const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, recipientAddres, value, 0, params) const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * approves a previously-proposed multisig message by transaction ID * @param address * @param proposedTransactionId * @param signerAddress */ public async msigApproveTransfer( address: string, proposedTransactionId: number, signerAddress: string, ): Promise<Cid> { return null as any; } /** * approves a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfApproveMsg */ public async msigApproveTransferTxHash( address: string, proposedMessageId: number, proposerAddress: string, recipientAddres: string, value: string, senderAddressOfApproveMsg: string, ): Promise<Cid> { const proposerId = await this.client.state.lookupId(proposerAddress); const messageWithoutGasParams = await createApproveMessage( address, senderAddressOfApproveMsg, proposedMessageId, proposerId, recipientAddres, 0, value, [] ); const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * cancels a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfCancelMsg */ public async msigCancelTransfer( address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, recipientAddres: string, value: string, ): Promise<Cid> { const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); const messageWithoutGasParams = await createCancelMessage( address, senderAddressOfCancelMsg, proposedMessageId, proposerId, recipientAddres, 0, value, [] ); const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * proposes adding a signer in the multisig * @param address * @param senderAddressOfProposeMsg * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ public async msigProposeAddSigner( address: string, senderAddressOfProposeMsg: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean, ): Promise<Cid> { const params: any[] = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.AddSigner, params) const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * approves a previously proposed AddSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ public async msigApproveAddSigner( address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean ): Promise<Cid> { const values = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; const proposerId = await this.client.state.lookupId(proposerAddress); const messageWithoutGasParams = await createApproveMessage( address, senderAddressOfApproveMsg, proposedMessageId, proposerId, address, MethodMultisig.AddSigner, '0', values ) const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * cancels a previously proposed AddSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ public async msigCancelAddSigner( address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean ): Promise<Cid> { const values = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); const messageWithoutGasParams = await createCancelMessage( address, senderAddressOfCancelMsg, proposedMessageId, proposerId, address, MethodMultisig.AddSigner, '0', values ) const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * proposes swapping 2 signers in the multisig * @param address * @param senderAddressOfProposeMsg * @param oldSignerAddress * @param newSignerAddress */ public async msigProposeSwapSigner( address: string, senderAddressOfProposeMsg: string, oldSignerAddress: string, newSignerAddress: string, ): Promise<Cid> { const params: any[] = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.SwapSigner, params) const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * approves a previously proposed SwapSigner * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param oldSignerAddress * @param newSignerAddress */ public async msigApproveSwapSigner( address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, oldSignerAddress: string, newSignerAddress: string, ): Promise<Cid> { const values = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; const proposerId = await this.client.state.lookupId(proposerAddress); const messageWithoutGasParams = await createApproveMessage( address, senderAddressOfApproveMsg, proposedMessageId, proposerId, address, MethodMultisig.SwapSigner, '0', values ); const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * cancels a previously proposed SwapSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param oldSignerAddress * @param newSignerAddress */ public async msigCancelSwapSigner( address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, oldSignerAddress: string, newSignerAddress: string, ): Promise<Cid> { const values = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); const messageWithoutGasParams = await createCancelMessage( address, senderAddressOfCancelMsg, proposedMessageId, proposerId, address, MethodMultisig.SwapSigner, '0', values ); const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; } /** * proposes removing a signer from the multisig * @param address * @param senderAddressOfProposeMsg * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ public async msigProposeRemoveSigner( address: string, senderAddressOfProposeMsg: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean, ): Promise<Cid> { const params: any[] = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.RemoveSigner, params) const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; }; /** * approves a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ public async msigApproveRemoveSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid> { const values = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; const proposerId = await this.client.state.lookupId(proposerAddress); const messageWithoutGasParams = await createApproveMessage( address, senderAddressOfApproveMsg, proposedMessageId, proposerId, address, MethodMultisig.RemoveSigner, '0', values ) const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; }; /** * cancels a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ public async msigCancelRemoveSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid> { const values = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); const messageWithoutGasParams = await createCancelMessage( address, senderAddressOfCancelMsg, proposedMessageId, proposerId, address, MethodMultisig.RemoveSigner, '0', values ) const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; }; // Own functions public async createLightWallet(password: string) { this.keystore = new Keystore(); const mnemonic = this.keystore.generateRandomSeed(); await this.keystore.createVault({ hdPathString: this.hdPathString, seedPhrase: mnemonic, password: password, }); this.signer = new LightWalletSigner(this.keystore); return mnemonic; } public async recoverLightWallet(mnemonic: string, password: string) { this.keystore = new Keystore(); await this.keystore.createVault({ hdPathString: this.hdPathString, seedPhrase: mnemonic, password: password, }); this.signer = new LightWalletSigner(this.keystore); } public loadLightWallet(encryptedWallet: string) { this.keystore = new Keystore(); this.keystore.deserialize(encryptedWallet); this.signer = new LightWalletSigner(this.keystore); } public prepareToSave() { return this.keystore.serialize(); } public getSigner(): LightWalletSigner { return this.signer; } }
the_stack
import { getContractAddressesForChainOrThrow } from '@0x/contract-addresses'; import { ERC1155ProxyContract, ERC20ProxyContract, ERC721ProxyContract, MultiAssetProxyContract, } from '@0x/contracts-asset-proxy'; import { ExchangeContract } from '@0x/contracts-exchange'; import { ZeroExGovernorContract } from '@0x/contracts-multisig'; import { StakingContract, StakingProxyContract, ZrxVaultContract } from '@0x/contracts-staking'; import { EmptyWalletSubprovider, RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders'; import { AssetProxyId } from '@0x/types'; import { logUtils, providerUtils } from '@0x/utils'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { SupportedProvider } from 'ethereum-types'; import { getConfigsByChainId } from './utils/configs_by_chain'; import { getTimelockRegistrationsByChainId } from './utils/timelocks'; // NOTE: add your own Infura Project ID to RPC urls before running const INFURA_PROJECT_ID = ''; const networkIdToRpcUrl = { 1: `https://mainnet.infura.io/v3/${INFURA_PROJECT_ID}`, 3: `https://ropsten.infura.io/v3/${INFURA_PROJECT_ID}`, 4: `https://rinkeby.infura.io/v3/${INFURA_PROJECT_ID}`, 42: `https://kovan.infura.io/v3/${INFURA_PROJECT_ID}`, }; // tslint:disable:custom-no-magic-numbers async function testContractConfigsAsync(provider: SupportedProvider): Promise<void> { const web3Wrapper = new Web3Wrapper(provider); const chainId = await web3Wrapper.getChainIdAsync(); const addresses = getContractAddressesForChainOrThrow(chainId); const configs = getConfigsByChainId(chainId); function warnIfMismatch(actual: any, expected: any, message: string): void { if (actual !== expected) { logUtils.warn(`${message}: actual: ${actual}, expected: ${expected}, chainId: ${chainId}`); } } const exchange = new ExchangeContract(addresses.exchange, provider); const exchangeV2 = new ExchangeContract(addresses.exchangeV2, provider); const erc20Proxy = new ERC20ProxyContract(addresses.erc20Proxy, provider); const erc721Proxy = new ERC721ProxyContract(addresses.erc721Proxy, provider); const erc1155Proxy = new ERC1155ProxyContract(addresses.erc1155Proxy, provider); const multiAssetProxy = new MultiAssetProxyContract(addresses.multiAssetProxy, provider); const erc20BridgeProxy = new ERC20ProxyContract(addresses.erc20BridgeProxy, provider); const governor = new ZeroExGovernorContract(addresses.zeroExGovernor, provider); const stakingProxy = new StakingProxyContract(addresses.stakingProxy, provider); const stakingContract = new StakingContract(addresses.stakingProxy, provider); const zrxVault = new ZrxVaultContract(addresses.zrxVault, provider); async function verifyExchangeV2ConfigsAsync(): Promise<void> { const exchangeOwner = await exchangeV2.owner().callAsync(); warnIfMismatch(exchangeOwner, governor.address, 'Unexpected ExchangeV2 owner'); const registeredERC20Proxy = await exchangeV2.getAssetProxy(AssetProxyId.ERC20).callAsync(); warnIfMismatch(registeredERC20Proxy, erc20Proxy.address, 'Unexpected ERC20Proxy registered in ExchangeV2'); const registeredERC721Proxy = await exchangeV2.getAssetProxy(AssetProxyId.ERC721).callAsync(); warnIfMismatch(registeredERC721Proxy, erc721Proxy.address, 'Unexpected ERC721Proxy registered in ExchangeV2'); const registeredERC1155Proxy = await exchangeV2.getAssetProxy(AssetProxyId.ERC1155).callAsync(); warnIfMismatch( registeredERC1155Proxy, erc1155Proxy.address, 'Unexpected ERC1155Proxy registered in ExchangeV2', ); const registeredMultiAssetProxy = await exchangeV2.getAssetProxy(AssetProxyId.MultiAsset).callAsync(); warnIfMismatch( registeredMultiAssetProxy, multiAssetProxy.address, 'Unexpected MultiAssetProxy registered in ExchangeV2', ); const registeredStaticCallProxy = await exchangeV2.getAssetProxy(AssetProxyId.StaticCall).callAsync(); warnIfMismatch( registeredStaticCallProxy, addresses.staticCallProxy, 'Unexpected StaticCallProxy registered in ExchangeV2', ); } async function verifyExchangeV3ConfigsAsync(): Promise<void> { const exchangeOwner = await exchange.owner().callAsync(); warnIfMismatch(exchangeOwner, governor.address, 'Unexpected Exchange owner'); const registeredERC20Proxy = await exchange.getAssetProxy(AssetProxyId.ERC20).callAsync(); warnIfMismatch(registeredERC20Proxy, erc20Proxy.address, 'Unexpected ERC20Proxy registered in Exchange'); const registeredERC721Proxy = await exchange.getAssetProxy(AssetProxyId.ERC721).callAsync(); warnIfMismatch(registeredERC721Proxy, erc721Proxy.address, 'Unexpected ERC721Proxy registered in Exchange'); const registeredERC1155Proxy = await exchange.getAssetProxy(AssetProxyId.ERC1155).callAsync(); warnIfMismatch(registeredERC1155Proxy, erc1155Proxy.address, 'Unexpected ERC1155Proxy registered in Exchange'); const registeredMultiAssetProxy = await exchange.getAssetProxy(AssetProxyId.MultiAsset).callAsync(); warnIfMismatch( registeredMultiAssetProxy, multiAssetProxy.address, 'Unexpected MultiAssetProxy registered in Exchange', ); const registeredStaticCallProxy = await exchange.getAssetProxy(AssetProxyId.StaticCall).callAsync(); warnIfMismatch( registeredStaticCallProxy, addresses.staticCallProxy, 'Unexpected StaticCallProxy registered in Exchange', ); const registeredERC20BridgeProxy = await exchange.getAssetProxy(AssetProxyId.ERC20Bridge).callAsync(); warnIfMismatch( registeredERC20BridgeProxy, addresses.erc20BridgeProxy, 'Unexpected ERC20BridgeProxy registered in Exchange', ); const protocolFeeCollector = await exchange.protocolFeeCollector().callAsync(); warnIfMismatch(protocolFeeCollector, addresses.stakingProxy, 'Unexpected StakingProxy attached to Exchange'); const protocolFeeMultiplier = await exchange.protocolFeeMultiplier().callAsync(); warnIfMismatch(protocolFeeMultiplier.toString(), '150000', 'Unexpected protocolFeeMultiplier in Exchange'); } async function verifyAssetProxyConfigsAsync(): Promise<void> { // Verify ERC20Proxy configs const erc20ProxyOwner = await erc20Proxy.owner().callAsync(); warnIfMismatch(erc20ProxyOwner, governor.address, 'Unexpected ERC20Proxy owner'); const erc20AuthorizedAddresses = await erc20Proxy.getAuthorizedAddresses().callAsync(); warnIfMismatch(erc20AuthorizedAddresses.length, 4, 'Unexpected number of authorized addresses in ERC20Proxy'); const isExchangeV2AuthorizedInERC20Proxy = await erc20Proxy.authorized(exchangeV2.address).callAsync(); warnIfMismatch(isExchangeV2AuthorizedInERC20Proxy, true, 'ExchangeV2 not authorized in ERC20Proxy'); const isExchangeAuthorizedInERC20Proxy = await erc20Proxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInERC20Proxy, true, 'Exchange not authorized in ERC20Proxy'); const isMAPAuthorizedInER20Proxy = await erc20Proxy.authorized(multiAssetProxy.address).callAsync(); warnIfMismatch(isMAPAuthorizedInER20Proxy, true, 'MultiAssetProxy not authorized in ERC20Proxy'); const isZrxVaultAuthorizedInER20Proxy = await erc20Proxy.authorized(zrxVault.address).callAsync(); warnIfMismatch(isZrxVaultAuthorizedInER20Proxy, true, 'ZrxVault not authorized in ERC20Proxy'); // Verify ERC721Proxy configs const erc721ProxyOwner = await erc721Proxy.owner().callAsync(); warnIfMismatch(erc721ProxyOwner, governor.address, 'Unexpected ERC721Proxy owner'); const erc721AuthorizedAddresses = await erc721Proxy.getAuthorizedAddresses().callAsync(); warnIfMismatch(erc721AuthorizedAddresses.length, 3, 'Unexpected number of authorized addresses in ERC721Proxy'); const isExchangeV2AuthorizedInERC721Proxy = await erc721Proxy.authorized(exchangeV2.address).callAsync(); warnIfMismatch(isExchangeV2AuthorizedInERC721Proxy, true, 'ExchangeV2 not authorized in ERC721Proxy'); const isExchangeAuthorizedInERC721Proxy = await erc721Proxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInERC721Proxy, true, 'Exchange not authorized in ERC721Proxy'); const isMAPAuthorizedInER721Proxy = await erc721Proxy.authorized(multiAssetProxy.address).callAsync(); warnIfMismatch(isMAPAuthorizedInER721Proxy, true, 'MultiAssetProxy not authorized in ERC721Proxy'); // Verify ERC1155Proxy configs const erc1155ProxyOwner = await erc1155Proxy.owner().callAsync(); warnIfMismatch(erc1155ProxyOwner, governor.address, 'Unexpected ERC1155Proxy owner'); const erc1155AuthorizedAddresses = await erc1155Proxy.getAuthorizedAddresses().callAsync(); warnIfMismatch( erc1155AuthorizedAddresses.length, 3, 'Unexpected number of authorized addresses in ERC1155Proxy', ); const isExchangeV2AuthorizedInERC1155Proxy = await erc1155Proxy.authorized(exchangeV2.address).callAsync(); warnIfMismatch(isExchangeV2AuthorizedInERC1155Proxy, true, 'ExchangeV2 not authorized in ERC1155Proxy'); const isExchangeAuthorizedInERC1155Proxy = await erc1155Proxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInERC1155Proxy, true, 'Exchange not authorized in ERC1155Proxy'); const isMAPAuthorizedInERC1155Proxy = await erc1155Proxy.authorized(multiAssetProxy.address).callAsync(); warnIfMismatch(isMAPAuthorizedInERC1155Proxy, true, 'MultiAssetProxy not authorized in ERC1155Proxy'); // Verify ERC20BridgeProxy configs const erc20BridgeProxyOwner = await erc20BridgeProxy.owner().callAsync(); warnIfMismatch(erc20BridgeProxyOwner, governor.address, 'Unexpected ERC20BridgeProxy owner'); const erc20BridgeAuthorizedAddresses = await erc20BridgeProxy.getAuthorizedAddresses().callAsync(); warnIfMismatch( erc20BridgeAuthorizedAddresses.length, 2, 'Unexpected number of authorized addresses in ERC20BridgeProxy', ); const isExchangeAuthorizedInERC20BridgeProxy = await erc20BridgeProxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInERC20BridgeProxy, true, 'Exchange not authorized in ERC20BridgeProxy'); const isMAPAuthorizedInERC20BridgeProxy = await erc20BridgeProxy .authorized(multiAssetProxy.address) .callAsync(); warnIfMismatch(isMAPAuthorizedInERC20BridgeProxy, true, 'MultiAssetProxy not authorized in ERC20BridgeProxy'); // Verify MultiAssetProxy configs const multiAssetProxyOwner = await multiAssetProxy.owner().callAsync(); warnIfMismatch(multiAssetProxyOwner, governor.address, 'Unexpected MultiAssetProxy owner'); const multiAssetProxyAuthorizedAddresses = await multiAssetProxy.getAuthorizedAddresses().callAsync(); warnIfMismatch( multiAssetProxyAuthorizedAddresses.length, 2, 'Unexpected number of authorized addresses in MultiAssetProxy', ); const isExchangeV2AuthorizedInMultiAssetProxy = await multiAssetProxy .authorized(exchangeV2.address) .callAsync(); warnIfMismatch(isExchangeV2AuthorizedInMultiAssetProxy, true, 'ExchangeV2 not authorized in MultiAssetProxy'); const isExchangeAuthorizedInMultiAssetProxy = await multiAssetProxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInMultiAssetProxy, true, 'Exchange not authorized in MultiAssetProxy'); const registeredERC20ProxyInMAP = await multiAssetProxy.getAssetProxy(AssetProxyId.ERC20).callAsync(); warnIfMismatch( registeredERC20ProxyInMAP, erc20Proxy.address, 'Unexpected ERC20Proxy registered in MultiAssetProxy', ); const registeredERC721ProxyInMAP = await multiAssetProxy.getAssetProxy(AssetProxyId.ERC721).callAsync(); warnIfMismatch( registeredERC721ProxyInMAP, erc721Proxy.address, 'Unexpected ERC721Proxy registered in MultiAssetProxy', ); const registeredERC1155ProxyInMAP = await multiAssetProxy.getAssetProxy(AssetProxyId.ERC1155).callAsync(); warnIfMismatch( registeredERC1155ProxyInMAP, erc1155Proxy.address, 'Unexpected ERC1155Proxy registered in MultiAssetProxy', ); const registeredStaticCallProxyInMAP = await multiAssetProxy.getAssetProxy(AssetProxyId.StaticCall).callAsync(); warnIfMismatch( registeredStaticCallProxyInMAP, addresses.staticCallProxy, 'Unexpected StaticCallProxy registered in MultiAssetProxy', ); const registeredERC20BridgeProxyInMAP = await multiAssetProxy .getAssetProxy(AssetProxyId.ERC20Bridge) .callAsync(); warnIfMismatch( registeredERC20BridgeProxyInMAP, addresses.erc20BridgeProxy, 'Unexpected ERC20BridgeProxy registered in MultiAssetProxy', ); } async function verifyStakingConfigsAsync(): Promise<void> { const stakingLogicAddress = await stakingProxy.stakingContract().callAsync(); warnIfMismatch(stakingLogicAddress, addresses.staking, 'Unexpected Staking contract attached to StakingProxy'); const isExchangeRegistered = await stakingContract.validExchanges(addresses.exchange).callAsync(); warnIfMismatch(isExchangeRegistered, true, 'Exchange not registered in StakingProxy'); const zrxVaultAddress = await stakingContract.getZrxVault().callAsync(); warnIfMismatch(zrxVaultAddress, addresses.zrxVault, 'Unexpected ZrxVault set in StakingProxy'); const wethAddress = await stakingContract.getWethContract().callAsync(); warnIfMismatch(wethAddress, addresses.etherToken, 'Unexpected WETH contract set in StakingProxy'); const stakingProxyOwner = await stakingProxy.owner().callAsync(); warnIfMismatch(stakingProxyOwner, addresses.zeroExGovernor, 'Unexpected StakingProxy owner'); const stakingProxyAuthorizedAddresses = await stakingProxy.getAuthorizedAddresses().callAsync(); warnIfMismatch( stakingProxyAuthorizedAddresses.length, 1, 'Unexpected number of authorized addresses in StakingProxy', ); const isGovernorAuthorizedInStakingProxy = await stakingProxy.authorized(addresses.zeroExGovernor).callAsync(); warnIfMismatch(isGovernorAuthorizedInStakingProxy, true, 'ZeroExGovernor not authorized in StakingProxy'); const zrxVaultOwner = await zrxVault.owner().callAsync(); warnIfMismatch(zrxVaultOwner, addresses.zeroExGovernor, 'Unexpected ZrxVault owner'); const zrxVaultAuthorizedAddresses = await zrxVault.getAuthorizedAddresses().callAsync(); warnIfMismatch(zrxVaultAuthorizedAddresses.length, 1, 'Unexpected number of authorized addresses in ZrxVault'); const isGovernorAuthorizedInZrxVault = await zrxVault.authorized(addresses.zeroExGovernor).callAsync(); warnIfMismatch(isGovernorAuthorizedInZrxVault, true, 'ZeroExGovernor not authorized in ZrxVault'); const zrxAssetProxy = await zrxVault.zrxAssetProxy().callAsync(); warnIfMismatch(zrxAssetProxy, addresses.erc20Proxy, 'Unexpected ERC20Proxy set in ZrxVault'); const zrxVaultStakingProxy = await zrxVault.stakingProxyAddress().callAsync(); warnIfMismatch(zrxVaultStakingProxy, addresses.stakingProxy, 'Unexpected StakingProxy set in ZrxVault'); const params = await stakingContract.getParams().callAsync(); warnIfMismatch( params[0].toNumber(), configs.staking.epochDurationInSeconds.toNumber(), 'Unexpected epoch duration in StakingProxy', ); warnIfMismatch( params[1].toString(), configs.staking.rewardDelegatedStakeWeight.toString(), 'Unexpected delegated stake weight in StakingProxy', ); warnIfMismatch( params[2].toNumber(), configs.staking.minimumPoolStake.toNumber(), 'Unexpected minimum pool stake in StakingProxy', ); warnIfMismatch( params[3].toString(), configs.staking.cobbDouglasAlphaNumerator.toString(), 'Unexpected alpha numerator in StakingProxy', ); warnIfMismatch( params[4].toString(), configs.staking.cobbDouglasAlphaDenominator.toString(), 'Unexpected alpha denominator in StakingProxy', ); } async function verifyZeroExGovernorConfigsAsync(): Promise<void> { const timelockRegistrations = getTimelockRegistrationsByChainId(chainId); for (const timelockRegistration of timelockRegistrations) { const actualRegistration = await governor .functionCallTimeLocks(timelockRegistration.functionSelector, timelockRegistration.destination) .callAsync(); warnIfMismatch( actualRegistration[0], true, `Function ${timelockRegistration.functionSelector} at address ${ timelockRegistration.destination } not registered in ZeroExGovernor`, ); warnIfMismatch( actualRegistration[1].toNumber(), timelockRegistration.secondsTimeLocked.toNumber(), `Timelock for function ${timelockRegistration.functionSelector} at address ${ timelockRegistration.destination } in ZeroExGovernor`, ); } const owners = await governor.getOwners().callAsync(); warnIfMismatch( owners.length, configs.zeroExGovernor.owners.length, 'Unexpected number of owners in ZeroExGovernor', ); owners.forEach((owner, i) => { warnIfMismatch( owners[i], configs.zeroExGovernor.owners[i], `Unexpected owner in ZeroExGovernor at index ${i}`, ); }); const secondsTimeLocked = await governor.secondsTimeLocked().callAsync(); warnIfMismatch( secondsTimeLocked.toNumber(), configs.zeroExGovernor.secondsTimeLocked.toNumber(), 'Unexpected secondsTimeLocked in ZeroExGovernor', ); const confirmationsRequired = await governor.required().callAsync(); warnIfMismatch( confirmationsRequired.toNumber(), configs.zeroExGovernor.required.toNumber(), 'Unexpected number of confirmations required in ZeroExGovernor', ); } await verifyExchangeV2ConfigsAsync(); await verifyExchangeV3ConfigsAsync(); await verifyStakingConfigsAsync(); await verifyAssetProxyConfigsAsync(); await verifyZeroExGovernorConfigsAsync(); } (async () => { for (const rpcUrl of Object.values(networkIdToRpcUrl)) { const provider = new Web3ProviderEngine(); provider.addProvider(new EmptyWalletSubprovider()); provider.addProvider(new RPCSubprovider(rpcUrl)); providerUtils.startProviderEngine(provider); await testContractConfigsAsync(provider); } })().catch(err => { logUtils.log(err); process.exit(1); });
the_stack
import {Component, ViewEncapsulation} from "@angular/core"; import { JigsawMenu, MenuTheme, SimpleNode, SimpleTreeData, PopupService, BreadcrumbNode, JigsawTheme } from "jigsaw/public_api"; @Component({ templateUrl: './demo.component.html', styleUrls:['demo.component.css'], encapsulation: ViewEncapsulation.None }) export class ThemeBuildInDemoComponent { public data: SimpleTreeData; public fishBoneData: SimpleTreeData; public breadData: (string | BreadcrumbNode)[]; public navigationData: SimpleTreeData = new SimpleTreeData(); public theme: string[] = ['dark']; public breadcrumbTheme: string[] = ['dark']; public fishBoneTheme: string[] = ['dark']; public navigationTheme: string[] = ['dark']; public width: number = 150; public height: number = 0; constructor( private ps: PopupService) { /* menu */ this.data = new SimpleTreeData(); this.data.fromXML(` <node> <node label="File"> <node label="New"> <node label="Project"></node> <node label="File"></node> <node label="Directory"></node> </node> <node label="Open"></node> <node label="Save As"></node> </node> <node label="Edit"> <node label="Cut"></node> <node label="Copy"> <node label="Copy Reference"></node> <node label="Copy Path"></node> </node> <node label="Paste" disabled="true"></node> <!-- 无label属性的node节点表示这是一个分隔符 --> <node></node> <node label="Delete"></node> </node> <node label="Run" > <node label="Run" icon="iconfont iconfont-e314" subTitle="Shift+F10"></node> <node label="Debug" icon="iconfont iconfont-e5e0" subTitle="Shift+F9"></node> </node> <!-- 无label属性的node节点表示这是一个分隔符 --> <node></node> <node label="Exit"></node> </node> `); /* breadcrumb */ this.resetBreadcrumbItems(); /* fish-bone */ this.fishBoneData = new SimpleTreeData(); this.fishBoneData.label = '<span class="orange">目标标题</span>'; this.fishBoneData.fromObject([ { label: '<span class="orange"><span class="iconfont iconfont-e221"></span>父节点1</span>', nodes: [ { label: '<span class="iconfont iconfont-e67a"></span>父节点11', nodes: [ { label: '子节点111', nodes: [ { label: '子节点1111', nodes: [ { label: "子节点11111", nodes: [ { label: '<span class="line">5,3,9,6,5,9,7,3,5,2</span>' } ] }, { label: 'end' } ] } ] }, { label: '子节点112', nodes: [ { label: '<span class="bar-colours-1">5,3,9,6,5,9,7,3,5,2</span>' } ] } ] }, { label: '父节点12' } ] }, { label: '<span class="orange"><span class="iconfont iconfont-e1ee"></span>父节点2</span>', nodes: [ { label: '<span class="iconfont iconfont-e67a"></span>父节点21', nodes: [ { label: '子节点211', nodes: [ { label: '<span class="iconfont iconfont-e547"></span>end' }, { label: '<span class="line">5,3,9,6,5,9,7,3,5,2</span>' }, { label: ` <div class="jigsaw-table-host" style="width: 300px;"> <table> <thead><tr><td>ID</td><td>name</td><td>gender</td><td>city</td></tr></thead> <tbody> <tr><td>1</td><td><a onclick="hello('tom')">tom</a></td><td>male</td><td>nj</td></tr> <tr><td>2</td><td><a onclick="hello('jerry')">jerry</a></td><td>male</td><td>shz</td></tr> <tr><td>3</td><td><a onclick="hello('marry')">marry</a></td><td>female</td><td>sh</td></tr> </tbody> </table> </div> `, // 这里需要特别注意,由于我们给了一段html片段并且包含了回调函数`hello()`, // 因此这里必须设置 `innerHtmlContext` 属性作为`hello()`函数的上下文 // 如果html片段中不包含回调函数,则无需设置 `innerHtmlContext` 属性 innerHtmlContext: this } ] }, { label: '子节点212' } ] }, { label: '父节点22', nodes: [ { label: '子节点221' } ] } ] }, { label: '<span class="orange"><span class="iconfont iconfont-e67a"></span>父节点3</span>', nodes: [ { label: '父节点31', nodes: [ { label: '<span class="iconfont iconfont-e547"></span>end' } ] } ] }, { label: '<span class="orange">父节点4</span>', nodes: [ { label: '<span class="bar-colours-1">5,3,9,6,5,9,7,3,5,2</span>' }, { label: 'end' } ] }, { label: '<span class="orange">父节点5</span>', nodes: [ { label: '<span class="pie-colours-2">5,3,9,6,5</span>' } ] } ]); /* navigation */ this.navigationData.fromXML(` <node> <node label="当前告警" icon="iconfont iconfont-e5fd" isActive="true" selected="true"> <node label="告警监控" selected="true" icon="iconfont iconfont-e2d8"></node> <node label="告警统计"></node> <node label="定时导出" icon="iconfont iconfont-e601"></node> <node label="告警同步"></node> <node label="告警提示" icon="iconfont iconfont-e52a"></node> </node> <node label="历史告警" icon="iconfont iconfont-e5f7"> <node label="告警查询"></node> </node> <node label="通知" icon="iconfont iconfont-e605"> <node label="通知监控"></node> </node> <node label="告警设置" icon="iconfont iconfont-e36f"></node> </node> `); } menuSelect(node: SimpleNode) { console.log("Dropdown menu selected, node =", node); } contextMenu(event: MouseEvent) { JigsawMenu.show(event, { data: this.data, width: this.width, height: this.height, theme: this.theme[0] as MenuTheme, }, node => { console.log("Context menu selected, node =", node); }); } public itemSelect(item: BreadcrumbNode) { console.log("当前点击的节点是:", item); const idx = this.breadData.findIndex(i => item === i); this.breadData = this.breadData.slice(0, idx + 1); } public resetBreadcrumbItems() { this.breadData = [ { label: "主页", icon: "iconfont iconfont-e647" }, // 当节点只有文本时,也可以直接给字符串,这样更便捷 "业务管理", "业务清单-1", "业务清单-2", "业务清单-3", // 也支持label属性 { label: "业务样本" } ]; } // ==================================================================== // ignore the following lines, they are not important to this demo // ==================================================================== summary: string = '本demo演示了jigsaw-cascading-menu指令实现多级菜单,展示了各个可用配置项及其效果,事件回调效果请查看控制台'; description: string = ''; }
the_stack
declare function cancelAnimationFrame(requestID: number): void; /** * 在下次进行重绘时执行。 */ declare function requestAnimationFrame(callback: () => void): number; /** * 可取消由 setTimeout() 方法设置的定时器。 */ declare function clearTimeout(timeoutID: number): void; /** * 可取消由 setInterval() 方法设置的定时器。 */ declare function clearInterval(intervalID: number): void; /** * 设定一个定时器,在定时到期以后执行注册的回调函数 */ declare function setTimeout(callback: () => void, delay: number, rest: any): number; /** * 设定一个定时器,按照指定的周期(以毫秒计)来执行注册的回调函数 */ declare function setInterval(callback: () => void, delay: number, rest: any): number; declare const wx: { /** * 创建一个画布对象。首次调用创建的是显示在屏幕上的画布,之后调用创建的都是离屏画布。 */ createCanvas(): Canvas; /** * 只有开放数据域能调用,获取主域和开放数据域共享的 sharedCanvas */ getSharedCanvas(): Canvas; /** * 创建一个图片对象 */ createImage(): Image; /** * 获取一行文本的行高 */ getTextLineHeight(object: { fontStyle: string, fontWeight: string, fontSize: number, fontFamily: string, text: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): number; /** * 加载自定义字体文件 */ loadFont(path: string): string; /** * 可以修改渲染帧率。默认渲染帧率为 60 帧每秒。修改后,requestAnimationFrame 的回调频率会发生改变。 */ setPreferredFramesPerSecond(fps: number): void; /** * 退出当前小游戏 */ exitMiniProgram(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 返回小程序启动参数 */ getLaunchOptionsSync(): LaunchOption; /** * 监听小游戏隐藏到后台事件。锁屏、按 HOME 键退到桌面、显示在聊天顶部等操作会触发此事件。 */ onHide(callback: () => void): void; /** * 取消监听小游戏隐藏到后台事件。锁屏、按 HOME 键退到桌面、显示在聊天顶部等操作会触发此事件。 */ offHide(callback: () => void): void; /** * 监听小游戏回到前台的事件 */ onShow(callback: () => void): void; /** * 取消监听小游戏回到前台的事件 */ offShow(callback: () => void): void; /** * 获取系统信息 */ getSystemInfo(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * wx.getSystemInfo 的同步版本 */ getSystemInfoSync(): SystemInfo; /** * 监听音频中断结束,在收到 onAudioInterruptionBegin 事件之后,小程序内所有音频会暂停,收到此事件之后才可再次播放成功 */ onAudioInterruptionEnd(callback: () => void): void; /** * 取消监听音频中断结束,在收到 onAudioInterruptionBegin 事件之后,小程序内所有音频会暂停,收到此事件之后才可再次播放成功 */ offAudioInterruptionEnd(callback: () => void): void; /** * 监听音频因为受到系统占用而被中断开始,以下场景会触发此事件:闹钟、电话、FaceTime 通话、微信语音聊天、微信视频聊天。此事件触发后,小程序内所有音频会暂停。 */ onAudioInterruptionBegin(callback: () => void): void; /** * 取消监听音频因为受到系统占用而被中断开始,以下场景会触发此事件:闹钟、电话、FaceTime 通话、微信语音聊天、微信视频聊天。此事件触发后,小程序内所有音频会暂停。 */ offAudioInterruptionBegin(callback: () => void): void; /** * 监听全局错误事件 */ onError(callback: () => void): void; /** * 取消监听全局错误事件 */ offError(callback: () => void): void; /** * 监听开始触摸事件 */ onTouchStart(callback: () => void): void; /** * 取消监听开始触摸事件 */ offTouchStart(callback: () => void): void; /** * 监听触点移动事件 */ onTouchMove(callback: () => void): void; /** * 取消监听触点移动事件 */ offTouchMove(callback: () => void): void; /** * 监听触摸结束事件 */ onTouchEnd(callback: () => void): void; /** * 取消监听触摸结束事件 */ offTouchEnd(callback: () => void): void; /** * 监听触点失效事件 */ onTouchCancel(callback: () => void): void; /** * 取消监听触点失效事件 */ offTouchCancel(callback: () => void): void; /** * 监听加速度数据,频率:5次/秒,接口调用后会自动开始监听,可使用 wx.stopAccelerometer 停止监听。 */ onAccelerometerChange(callback: () => void): void; startAccelerometer(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; stopAccelerometer(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 获取设备电量 */ getBatteryInfo(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * wx.getBatteryInfo 的同步版本 */ getBatteryInfoSync(): string; getClipboardData(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; setClipboardData(object: { data: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 监听罗盘数据,频率:5 次/秒,接口调用后会自动开始监听,可使用 wx.stopCompass 停止监听。 */ onCompassChange(callback: () => void): void; startCompass(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; stopCompass(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 获取网络类型 */ getNetworkType(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; onNetworkStatusChange(callback: () => void): void; getScreenBrightness(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; setKeepScreenOn(object: { keepScreenOn: boolean, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; setScreenBrightness(object: { value: number, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; vibrateShort(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; vibrateLong(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 获取全局唯一的文件管理器 */ getFileSystemManager(): FileSystemManager; /** * 获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用;当用户点击“显示在聊天顶部”时,此接口可继续调用。 */ getLocation(object: { type: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地文件路径。 */ downloadFile(object: { url: string, header: Object, filePath: string, fail: (res: any) => void, complete?: (res: any) => void }): DownloadTask; /** * 发起网络请求。 */ request(object: { url: string, data: string | Object, header?: Object, method: string, dataType?: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): RequestTask; /** * 创建一个 WebSocket 连接。最多同时存在 2 个 WebSocket 连接。 */ connectSocket(object: { url: string, header: Object, method: string, protocols: any[], success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): SocketTask; /** * 关闭 WeSocket 连接 */ closeSocket(object: { code: number, reason: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 监听WebSocket 连接打开事件 */ onSocketOpen(callback: () => void): void; /** * 监听WebSocket 连接关闭事件 */ onSocketClose(callback: () => void): void; /** * 监听WebSocket 接受到服务器的消息事件 */ onSocketMessage(callback: () => void): void; /** * 监听WebSocket 错误事件 */ onSocketError(callback: () => void): void; /** * 通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。 */ sendSocketMessage(object: { data: any[], success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 将本地资源上传到开发者服务器,客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data 。 */ uploadFile(object: { url: string, filePath: string, name: string, header: Object, formData: Object, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): UploadTask; /** * 通过 wx.login 接口获得的用户登录态拥有一定的时效性。用户越久未使用小程序,用户登录态越有可能失效。反之如果用户一直在使用小程序,则用户登录态一直保持有效。具体时效逻辑由微信维护,对开发者透明。开发者只需要调用 wx.checkSession 接口检测当前用户登录态是否有效。登录态过期后开发者可以再调用 wx.login 获取新的用户登录态。 */ checkSession(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 调用接口获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。 */ login(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; authorize(object: { scope: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 在无须用户授权的情况下,批量获取用户信息。该接口只在开放数据域下可用 */ createUserInfoButton(object: { type: string, text?: string, image?: string, style: any }): UserInfoButton; getUserInfo(object: { openIdList?: any[], lang?: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; getSetting(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; openSetting(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; getWeRunData(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 拉取当前用户所有同玩好友的托管数据。该接口只可在开放数据域下使用 */ getFriendCloudStorage(object: { keyList: any[], success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 在小游戏是通过群分享卡片打开的情况下,可以通过调用该接口获取群同玩成员的游戏数据。该接口只可在开放数据域下使用。 */ getGroupCloudStorage(object: { shareTicket: string, keyList: any[], success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 获取当前用户托管数据当中对应 key 的数据。该接口只可在开放数据域下使用 */ getUserCloudStorage(object: { keyList: any[], success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 删除用户托管数据当中对应 key 的数据。 */ removeUserCloudStorage(object: { keyList: any[], success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 对用户托管数据进行写数据操作,允许同时写多组 KV 数据。 */ setUserCloudStorage(object: { KVDataList: any[], success: (res: any) => void, fail?: (res: any) => void, complete?: (res: any) => void }): void; /** * 获取开放数据域 */ getOpenDataContext(): OpenDataContext; /** * 监听主域发送的消息 */ onMessage(callback: (data: any) => void): void; getShareInfo(object: { shareTicket: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; hideShareMenu(object?: { success?: (res: any) => void, fail?: (res: any) => void, complete?: (res: any) => void }): void; /** * 监听用户点击右上角菜单的“转发”按钮时触发的事件 */ onShareAppMessage(callback: () => void): void; /** * 取消监听用户点击右上角菜单的“转发”按钮时触发的事件 */ offShareAppMessage(callback: () => void): void; showShareMenu(object: { withShareTicket: boolean, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 主动拉起转发,进入选择通讯录界面。 */ shareAppMessage(object: { title?: string, imageUrl?: string, query?: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; updateShareMenu(object: { withShareTicket?: boolean, success?: (res: any) => void, fail?: (res: any) => void, complete?: (res: any) => void }): void; setEnableDebug(object: { enableDebug: boolean, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 清理本地数据缓存 */ clearStorage(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * wx.clearStorage 的同步版本 */ clearStorageSync(): void; /** * 从本地缓存中异步获取指定 key 的内容 */ getStorage(object: { key: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 异步获取当前storage的相关信息 */ getStorageInfo(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * wx.getStorage 的同步版本 */ getStorageSync(key: string): Object | string; /** * wx.getStorageInfo 的同步版本 */ getStorageInfoSync(): Object; /** * 从本地缓存中移除指定 key */ removeStorage(object: { key: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * wx.removeStorage 的同步版本 */ removeStorageSync(key: string): void; /** * 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容。 */ setStorage(object: { key: string, data: Object | string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * wx.setStorage 的同步版本 */ setStorageSync(key: string, data: Object | string): void; /** * 隐藏消息提示框 */ hideToast(object?: { success?: (res: any) => void, fail?: (res: any) => void, complete?: (res: any) => void }): void; hideLoading(object?: { success?: (res: any) => void, fail?: (res: any) => void, complete?: (res: any) => void }): void; /** * 显示模态对话框 */ showModal(object: { title: string, content: string, showCancel?: boolean, cancelText: string, cancelColor?: string, confirmText: string, confirmColor?: string, success: (res: any) => void, fail?: (res: any) => void, complete?: (res: any) => void }): void; /** * 显示消息提示框 */ showToast(object: { title: Object, icon: Object, image: Object, success?: (res: any) => void, fail?: (res: any) => void, complete?: (res: any) => void }): void; showLoading(object: { title: string, mask: boolean, success?: (res: any) => void, fail?: (res: any) => void, complete?: (res: any) => void }): void; /** * 参数 */ showActionSheet(object: { itemList: any[], itemColor: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 隐藏键盘 */ hideKeyboard(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 监听键盘输入事件 */ onKeyboardInput(callback: () => void): void; /** * 取消监听键盘输入事件 */ offKeyboardInput(callback: () => void): void; /** * 监听用户点击键盘 Confirm 按钮时的事件 */ onKeyboardConfirm(callback: () => void): void; /** * 取消监听用户点击键盘 Confirm 按钮时的事件 */ offKeyboardConfirm(callback: () => void): void; /** * 监听监听键盘收起的事件 */ onKeyboardComplete(callback: () => void): void; /** * 取消监听监听键盘收起的事件 */ offKeyboardComplete(callback: () => void): void; /** * 显示键盘 */ showKeyboard(object: { defaultValue: string, maxLength: number, multiple: boolean, confirmHold: boolean, confirmType: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 动态设置通过右上角按钮拉起的菜单的样式。 */ setMenuStyle(object: { style: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 当在配置中设置 showStatusBarStyle 时,屏幕顶部会显示状态栏。此接口可以修改状态栏的样式。 */ setStatusBarStyle(object: { style: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 监听窗口尺寸变化事件 */ onWindowResize(callback: () => void): void; /** * 取消监听窗口尺寸变化事件 */ offWindowResize(callback: () => void): void; /** * 返回值 */ getUpdateManager(): UpdateManager; /** * 创建一个 Worker 线程,目前限制最多只能创建一个 Worker,创建下一个 Worker 前请调用 Worker.terminate */ createWorker(): Worker; /** * 创建一个 InnerAudioContext 实例 */ createInnerAudioContext(): InnerAudioContext; getRecorderManager(): RecorderManager; /** * 从本地相册选择图片或使用相机拍照。 */ chooseImage(object: { count: number }): void; /** * 预览图片 */ previewImage(object: { current: string, urls: any[], success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; saveImageToPhotosAlbum(object: { filePath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 创建视频 */ createVideo(object: { x: number, y: number, width: number, height: number, src: number, poster: number, initialTime: number, playbackRate: number, live: number, objectFit: number, controls: number, autoplay: number, loop: number, muted: number }): Video; /** * 获取性能管理器 */ getPerformance(): Performance; /** * 加快触发 JavaScrpitCore Garbage Collection(垃圾回收),GC 时机是由 JavaScrpitCore 来控制的,并不能保证调用后马上触发 GC。 */ triggerGC(): void; /** * 发起米大师支付 */ requestMidasPayment(object: { mode: string, env: number, offerId: string, currencyType: string, platform: string, buyQuantity: number, zoneId: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 客服消息 */ openCustomerServiceConversation(object: any): void; /** * 游戏圈 */ createGameClubButton(object: any): void; /** * 视频流量主 */ createRewardedVideoAd(object: any): any; /** * banner广告 */ createBannerAd(object: any): any; } declare interface Canvas { /** * 获取画布对象的绘图上下文 */ getContext(contextType: string, contextAttributes: { antialias: boolean, preserveDrawingBuffer: boolean, antialiasSamples: number }): RenderingContext; /** * 将当前 Canvas 保存为一个临时文件,并生成相应的临时文件路径。 */ toTempFilePath(object: { x: number, y: number, width: number, height: number, destWidth: number, destHeight: number, fileType: string, quality: number, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): string; /** * 把画布上的绘制内容以一个 data URI 的格式返回 */ toDataURL(): string; /** * Canvas.toTempFilePath 的同步版本 */ toTempFilePathSync(object: { x: number, y: number, width: number, height: number, destWidth: number, destHeight: number, fileType: string, quality: number }): void; } declare interface FileSystemManager { /** * 判断文件/目录是否存在 */ access(object: { path: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * FileSystemManager.access 的同步版本 */ accessSync(path: string): void; /** * 复制文件 */ copyFile(object: { srcPath: string, destPath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * FileSystemManager.copyFile 的同步版本 */ copyFileSync(srcPath: string, destPath: string): void; /** * 获取该小程序下的 本地临时文件 或 本地缓存文件 信息 */ getFileInfo(object: { filePath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 获取该小程序下已保存的本地缓存文件列表 */ getSavedFileList(object: { success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 创建目录 */ mkdir(object: { dirPath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * FileSystemManager.mkdir 的同步版本 */ mkdirSync(dirPath: string): void; /** * 删除该小程序下已保存的本地缓存文件 */ removeSavedFile(object: { filePath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 读取本地文件内容 */ readFile(object: { filePath: string, encoding: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 重命名文件,可以把文件从 oldPath 移动到 newPath */ rename(object: { oldPath: string, newPath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 删除目录 */ rmdir(object: { dirPath: Object, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 读取目录内文件列表 */ readdir(object: { dirPath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * FileSystemManager.readdir 的同步版本 */ readdirSync(dirPath: string): string[]; /** * FileSystemManager.rename 的同步版本 */ renameSync(oldPath: string, newPath: string): void; /** * FileSystemManager.rmdir 的同步版本 */ rmdirSync(dirPath: {}): void; /** * FileSystemManager.readFile 的同步版本 */ readFileSync(filePath: string, encoding: string): string[]; /** * 保存临时文件到本地。此接口会移动临时文件,因此调用成功后,tempFilePath 将不可用。 */ saveFile(object: { tempFilePath: string, filePath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 获取文件 Stats 对象 */ stat(object: { path: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): Stats; /** * FileSystemManager.saveFile 的同步版本 */ saveFileSync(tempFilePath: string, filePath: string): number; /** * FileSystemManager.stat 的同步版本 */ statSync(path: string): Stats; /** * 删除文件 */ unlink(object: { filePath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 解压文件 */ unzip(object: { zipFilePath: string, targetPath: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * FileSystemManager.unlink 的同步版本 */ unlinkSync(filePath: string): void; /** * 写文件 */ writeFile(object: { filePath: string, data: any[], encoding: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * FileSystemManager.writeFile 的同步版本 */ writeFileSync(filePath: string, data: string | ArrayBuffer, encoding: string): void; } declare interface Stats { /** * 判断当前文件是否一个目录 */ isDirectory(): boolean; /** * 判断当前文件是否一个普通文件 */ isFile(): boolean; } declare interface DownloadTask { abort(): void; onProgressUpdate(callback: () => void): void; } declare interface RequestTask { abort(): void; } declare interface SocketTask { /** * 关闭 WebSocket 连接 */ close(object: { code: number, reason: string, success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; /** * 监听WebSocket 连接打开事件 */ onOpen(callback: () => void): void; /** * 监听WebSocket 连接关闭事件 */ onClose(callback: () => void): void; /** * 监听WebSocket 错误事件 */ onError(callback: () => void): void; /** * 监听WebSocket 接受到服务器的消息事件 */ onMessage(callback: () => void): void; /** * 通过 WebSocket 连接发送数据 */ send(object: { data: any[], success: (res: any) => void, fail: (res: any) => void, complete?: (res: any) => void }): void; } declare interface UploadTask { abort(): void; onProgressUpdate(callback: () => void): void; } declare interface OpenDataContext { /** * 向开放数据域发送消息 */ postMessage(message: {}): void; } declare interface UpdateManager { /** * 应用更新包并重启 */ applyUpdate(): void; /** * 监听检查更新结果回调 */ onCheckForUpdate(callback: () => void): void; /** * 监听更新包下载成功回调 */ onUpdateReady(callback: () => void): void; /** * 监听更新包下载失败回调 */ onUpdateFailed(callback: () => void): void; } declare interface Worker { /** * 监听接收主线程/Worker 线程向当前线程发送的消息 */ onMessage(callback: () => void): void; /** * 向主线程/Worker 线程发送的消息。 */ postMessage(message: {}): void; /** * 结束当前 worker 线程,仅限在主线程 worker 对象上调用。 */ terminate(): void; } declare interface InnerAudioContext { /** * 销毁当前实例 */ destroy(): void; /** * 取消监听音频进入可以播放状态的事件 */ offCanplay(callback: () => void): void; /** * 监听音频暂停事件 */ onPause(callback: () => void): void; /** * 监听音频停止事件 */ onStop(callback: () => void): void; /** * 取消监听音频停止事件 */ offStop(callback: () => void): void; /** * 监听音频自然播放至结束的事件 */ onEnded(callback: () => void): void; /** * 取消监听音频自然播放至结束的事件 */ offEnded(callback: () => void): void; /** * 监听音频播放进度更新事件 */ onTimeUpdate(callback: () => void): void; /** * 监听音频播放事件 */ onPlay(callback: () => void): void; /** * 监听音频播放错误事件 */ onError(callback: () => void): void; /** * 取消监听音频暂停事件 */ offPause(callback: () => void): void; /** * 监听音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ onWaiting(callback: () => void): void; /** * 取消监听音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ offWaiting(callback: () => void): void; /** * 监听音频进行跳转操作的事件 */ onSeeking(callback: () => void): void; /** * 取消监听音频进行跳转操作的事件 */ offSeeking(callback: () => void): void; /** * 监听音频完成跳转操作的事件 */ onSeeked(callback: () => void): void; /** * 取消监听音频完成跳转操作的事件 */ offSeeked(callback: () => void): void; /** * 取消监听音频播放事件 */ offPlay(callback: () => void): void; /** * 取消监听音频播放进度更新事件 */ offTimeUpdate(callback: () => void): void; /** * 监听音频进入可以播放状态的事件 */ onCanplay(callback: () => void): void; /** * 取消监听音频播放错误事件 */ offError(callback: () => void): void; /** * 停止。停止后的音频再播放会从头开始播放。 */ pause(): void; /** * 播放 */ play(): void; /** * 跳转到指定位置,单位 s */ seek(position: number): void; src: string; autoplay: boolean; loop: boolean; obeyMuteSwitch: boolean; duration: number; buffered: number; volume: number; } declare interface RecorderManager { /** * 监听录音暂停事件 */ onPause(callback: () => void): void; /** * 监听录音结束事件 */ onStop(callback: () => void): void; /** * 监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。 */ onFrameRecorded(callback: () => void): void; /** * 监听录音错误事件 */ onError(callback: () => void): void; /** * 监听录音开始事件 */ onStart(callback: () => void): void; /** * 暂停录音 */ pause(): void; /** * 继续录音 */ resume(): void; /** * 停止录音 */ stop(): void; /** * 开始录音 */ start(object: { duration: number, sampleRate: number, numberOfChannels: number, encodeBitRate: number, format: string, frameSize: number }): void; } declare interface Video { /** * 视频退出全屏 */ exitFullScreen(): Promise<Object>; /** * 取消监听视频暂停事件 */ offPause(callback: () => void): void; /** * 监听视频播放到末尾事件 */ onEnded(callback: () => void): void; /** * 取消监听视频播放到末尾事件 */ offEnded(callback: () => void): void; /** * 监听视频播放进度更新事件 */ onTimeUpdate(callback: () => void): void; /** * 取消监听视频播放进度更新事件 */ offTimeUpdate(callback: () => void): void; /** * 监听视频错误事件 */ onError(callback: () => void): void; /** * 取消监听视频错误事件 */ offError(callback: () => void): void; /** * 监听视频播放事件 */ onPlay(callback: () => void): void; /** * 监听视频暂停事件 */ onPause(callback: () => void): void; /** * 取消监听视频缓冲事件 */ offWaiting(callback: () => void): void; /** * 监听视频缓冲事件 */ onWaiting(callback: () => void): void; /** * 取消监听视频播放事件 */ offPlay(callback: () => void): void; /** * 暂停视频 */ pause(): Promise<Object>; /** * 播放视频 */ play(): Promise<Object>; /** * 视频全屏 */ requestFullScreen(): Promise<Object>; /** * 视频跳转 */ seek(time: number): Promise<Object>; /** * 停止视频 */ stop(): Promise<Object>; } declare interface Performance { /** * 可以获取当前时间以微秒为单位的时间戳 */ now(): number; } declare interface Image { /** * 图片的 URL */ src: string; /** * 图片的真实宽度 */ width: number; /** * 图片的真实高度 */ height: number; /** * 图片的加载完成 */ onload: () => void; } declare class LaunchOption { /** 场景值*/ scene: number; /** 启动参数*/ query: Object; /** 当前小游戏是否被显示在聊天顶部*/ isSticky: boolean; /** shareTicket*/ shareTicket: string; } declare class SystemInfo { /** 手机品牌*/ brand: string; /** 手机型号*/ model: string; /** 设备像素比 */ pixelRatio: number; /** 屏幕宽度*/ screenWidth: number; /** 屏幕高度*/ screenHeight: number; /** 可使用窗口宽度*/ windowWidth: number; /** 可使用窗口高度*/ windowHeight: number; /** 微信设置的语言*/ language: string; /** 微信版本号*/ version: string; /** 操作系统版本*/ system: string; /** 客户端平台*/ platform: string /** 用户字体大小设置。以“我-设置 - 通用 - 字体大小”中的设置为准,单位 px。*/ fontSizeSetting: number; /** 客户端基础库版本*/ SDKVersion: string; /** 性能等级*/ benchmarkLevel: number; /** 电量,范围 1 - 100*/ battery: number; /** wifi 信号强度,范围 0 - 4 */ wifiSignal: number; } declare class Stats { /** * 文件的类型和存取的权限,对应 POSIX stat.st_mode */ mode: string; /** * 文件大小,单位:B,对应 POSIX stat.st_size */ size: number; /** * 文件最近一次被存取或被执行的时间,UNIX 时间戳,对应 POSIX stat.st_atime */ lastAccessedTime: number; /** * 文件最后一次被修改的时间,UNIX 时间戳,对应 POSIX stat.st_mtime */ lastModifiedTime: number; } /** * 通过 Canvas.getContext('2d') 接口可以获取 CanvasRenderingContext2D 对象。CanvasRenderingContext2D 实现了 HTML The 2D rendering context 定义的大部分属性、方法。通过 Canvas.getContext('webgl') 接口可以获取 WebGLRenderingContext 对象。 WebGLRenderingContext 实现了 WebGL 1.0 定义的所有属性、方法、常量。 * 2d 接口支持情况 * iOS/Android 不支持的 2d 属性和接口 * globalCompositeOperation 不支持以下值: source-in source-out destination-atop lighter copy。如果使用,不会报错,但是将得到与预期不符的结果。 * isPointInPath * WebGL 接口支持情况 * iOS/Android 不支持的 WebGL 接 */ declare interface RenderingContext { } /** * 按钮 */ declare interface UserInfoButton { destroy(): void; hide(): void; onTap(callback: (res) => void): void; offTap(callback: () => void): void; show(): void; }
the_stack
import type { CharRange } from "refa" import { visitRegExpAST, RegExpParser } from "regexpp" import type { Character, CharacterClass, CharacterSet, Node, Pattern, Quantifier, } from "regexpp/ast" import type { RegExpVisitor } from "regexpp/visitor" import type { RegExpContext } from "../utils" import { createRule, defineRegexpVisitor } from "../utils" import type { ReadonlyFlags } from "regexp-ast-analysis" import { hasSomeDescendant, toCache, toCharSet, getFirstCharAfter, } from "regexp-ast-analysis" const UTF16_MAX = 0xffff /** * Returns whether the given pattern is compatible with unicode-mode on a * syntactical level. So means that: * * 1. The raw regex is syntactically valid with the u flag. * 2. The regex is parsed the same way (*). * * (*) Unicode mode parses surrogates as one character while non-Unicode mode * parses the pair as two separate code points. We will ignore this difference. * We will also ignore the sematic differences between escape sequences and * so on. * * @returns `false` or the parsed Unicode pattern */ function isSyntacticallyCompatible(pattern: Pattern): false | Pattern { const INCOMPATIBLE = {} // See whether it's syntactically valid let uPattern try { uPattern = new RegExpParser().parsePattern( pattern.raw, undefined, undefined, true, ) } catch (error) { return false } // See whether it's parsed the same way // We will try to find constructs in the non-Unicode regex that we know // will either result in a syntax error or a different construct. Since // we already checked for syntax errors, we know that it's the second // option. // There is another construct that get interpreted differently: Surrogates. // We want to make sure that no surrogate is a quantified element or // character class element. try { visitRegExpAST(pattern, { onCharacterEnter(node) { if (/^\\(?![bfnrtv])[A-Za-z]$/u.test(node.raw)) { // All cool Unicode feature are behind escapes like \p. throw INCOMPATIBLE } }, }) // See no-misleading-character-class for more details visitRegExpAST(uPattern, { onCharacterEnter(node) { if ( node.value > UTF16_MAX && (node.parent.type === "CharacterClass" || node.parent.type === "CharacterClassRange") ) { // /[😃]/ != /[😃]/u throw INCOMPATIBLE } }, onQuantifierEnter(node) { if ( node.element.type === "Character" && node.element.value > UTF16_MAX ) { // /😃+/ != /😃+/u throw INCOMPATIBLE } }, }) } catch (error) { if (error === INCOMPATIBLE) { return false } // just rethrow throw error } return uPattern } const HIGH_SURROGATES: CharRange = { min: 0xd800, max: 0xdbff } const LOW_SURROGATES: CharRange = { min: 0xdc00, max: 0xdfff } const SURROGATES: CharRange = { min: 0xd800, max: 0xdfff } const ASTRAL: CharRange = { min: 0x10000, max: 0x10ffff } /** Returns whether the two given ranges are equal. */ function rangeEqual(a: readonly CharRange[], b: readonly CharRange[]): boolean { if (a.length !== b.length) { return false } for (let i = 0; i < a.length; i++) { const x = a[i] const y = b[i] if (x.min !== y.min || x.max !== y.max) { return false } } return true } type CharLike = Character | CharacterClass | CharacterSet /** Whether the given element is character-like element. */ function isChar(node: Node): node is CharLike { return ( node.type === "Character" || node.type === "CharacterClass" || node.type === "CharacterSet" ) } /** * Whether the given char-like accepts the same characters with and without * the u flag. */ function isCompatibleCharLike( char: CharLike, flags: ReadonlyFlags, uFlags: ReadonlyFlags, ): boolean { const cs = toCharSet(char, flags) if (!cs.isDisjointWith(SURROGATES)) { // If the character (class/set) contains high or low // surrogates, then we won't be able to guarantee that the // Unicode pattern will behave the same way. return false } const uCs = toCharSet(char, uFlags) // Compare the ranges. return rangeEqual(cs.ranges, uCs.ranges) } /** * Whether the given quantifier accepts the same characters with and without * the u flag. * * This will return `undefined` if the function cannot decide. */ function isCompatibleQuantifier( q: Quantifier, flags: ReadonlyFlags, uFlags: ReadonlyFlags, ): boolean | undefined { if (!isChar(q.element)) { return undefined } if (isCompatibleCharLike(q.element, flags, uFlags)) { // trivial return true } // A quantifier `n*` or `n+` is the same with and without the // u flag if all of the following conditions are true: // // 1. The UTF16 characters of the element contain all // surrogates characters (U+D800-U+DFFF). // 2. The Unicode characters of the element contain all // surrogates characters (U+D800-U+DFFF) and astral // characters (U+10000-U+10FFFF). // 3. All non-surrogate and non-astral characters of the UTF16 // and Unicode characters of the element as the same. // 4. The first character before the quantifier is not a // high surrogate (U+D800-U+DBFF). // 5. The first character after the quantifier is not a // low surrogate (U+DC00-U+DFFF). if (q.min > 1 || q.max !== Infinity) { return undefined } const cs = toCharSet(q.element, flags) if (!cs.isSupersetOf(SURROGATES)) { // failed condition 1 return false } const uCs = toCharSet(q.element, uFlags) if (!uCs.isSupersetOf(SURROGATES) || !uCs.isSupersetOf(ASTRAL)) { // failed condition 2 return false } if (!rangeEqual(cs.ranges, uCs.without([ASTRAL]).ranges)) { // failed condition 3 return false } const before = getFirstCharAfter(q, "rtl", flags).char if (!before.isDisjointWith(HIGH_SURROGATES)) { // failed condition 4 return false } const after = getFirstCharAfter(q, "ltr", flags).char if (!after.isDisjointWith(LOW_SURROGATES)) { // failed condition 5 return false } return true } /** * Returns whether the regex would keep its behaviour if the u flag were to be * added. */ function isSemanticallyCompatible( regexpContext: RegExpContext, uPattern: Pattern, ): boolean { const surrogatePositions = new Set<number>() visitRegExpAST(uPattern, { onCharacterEnter(node) { if (node.value > UTF16_MAX) { for (let i = node.start; i < node.end; i++) { surrogatePositions.add(i) } } }, }) const pattern = regexpContext.patternAst const flags = regexpContext.flags const uFlags = toCache({ ...flags, unicode: true }) const skip = new Set<Node>() return !hasSomeDescendant( pattern, (n) => { // The goal is find something that is will change when adding the // Unicode flag. // Surrogates don't change if (n.type === "Character" && surrogatePositions.has(n.start)) { return false } if ( n.type === "Assertion" && n.kind === "word" && flags.ignoreCase ) { // The case canonicalization in Unicode mode is different which // causes `\b` and `\B` to accept/reject a few more characters. return true } if (isChar(n)) { return !isCompatibleCharLike(n, flags, uFlags) } if (n.type === "Quantifier") { const result = isCompatibleQuantifier(n, flags, uFlags) if (result !== undefined) { skip.add(n) return !result } } return false }, (n) => { // Don't go into character classes, we already checked them. // We also don't want to go into elements, we explicitly skipped. return n.type !== "CharacterClass" && !skip.has(n) }, ) } /** * Returns whether the regex would keep its behaviour if the u flag were to be * added. */ function isCompatible(regexpContext: RegExpContext): boolean { const uPattern = isSyntacticallyCompatible(regexpContext.patternAst) if (!uPattern) { return false } return isSemanticallyCompatible(regexpContext, uPattern) } export default createRule("require-unicode-regexp", { meta: { docs: { description: "enforce the use of the `u` flag", category: "Best Practices", recommended: false, }, schema: [], fixable: "code", messages: { require: "Use the 'u' flag.", }, type: "suggestion", // "problem", }, create(context) { /** * Create visitor */ function createVisitor( regexpContext: RegExpContext, ): RegExpVisitor.Handlers { const { node, flags, flagsString, getFlagsLocation, fixReplaceFlags, } = regexpContext if (flagsString === null) { // This means that there are flags (probably) but we were // unable to evaluate them. return {} } if (!flags.unicode) { context.report({ node, loc: getFlagsLocation(), messageId: "require", fix: fixReplaceFlags(() => { if (!isCompatible(regexpContext)) { return null } return `${flagsString}u` }), }) } return {} } return defineRegexpVisitor(context, { createVisitor, }) }, })
the_stack
import * as $protobuf from "protobufjs"; /** Properties of a LinearReference. */ export interface ILinearReference { /** LinearReference startDistance */ startDistance?: (number|Long|null); /** LinearReference endDistance */ endDistance?: (number|Long|null); } /** Represents a LinearReference. */ export class LinearReference implements ILinearReference { /** * Constructs a new LinearReference. * @param [properties] Properties to set */ constructor(properties?: ILinearReference); /** LinearReference startDistance. */ public startDistance: (number|Long); /** LinearReference endDistance. */ public endDistance: (number|Long); /** LinearReference endDistancePresent. */ public endDistancePresent?: "endDistance"; /** * Creates a new LinearReference instance using the specified properties. * @param [properties] Properties to set * @returns LinearReference instance */ public static create(properties?: ILinearReference): LinearReference; /** * Encodes the specified LinearReference message. Does not implicitly {@link LinearReference.verify|verify} messages. * @param message LinearReference message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: ILinearReference, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified LinearReference message, length delimited. Does not implicitly {@link LinearReference.verify|verify} messages. * @param message LinearReference message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: ILinearReference, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a LinearReference message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns LinearReference * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): LinearReference; /** * Decodes a LinearReference message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns LinearReference * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): LinearReference; /** * Verifies a LinearReference message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a LinearReference message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns LinearReference */ public static fromObject(object: { [k: string]: any }): LinearReference; /** * Creates a plain object from a LinearReference message. Also converts values to other types if specified. * @param message LinearReference * @param [options] Conversion options * @returns Plain object */ public static toObject(message: LinearReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this LinearReference to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SharedStreetsLinearReferences. */ export interface ISharedStreetsLinearReferences { /** SharedStreetsLinearReferences referenceId */ referenceId?: (string|null); /** SharedStreetsLinearReferences referenceLength */ referenceLength?: (number|Long|null); /** SharedStreetsLinearReferences references */ references?: (ILinearReference[]|null); } /** Represents a SharedStreetsLinearReferences. */ export class SharedStreetsLinearReferences implements ISharedStreetsLinearReferences { /** * Constructs a new SharedStreetsLinearReferences. * @param [properties] Properties to set */ constructor(properties?: ISharedStreetsLinearReferences); /** SharedStreetsLinearReferences referenceId. */ public referenceId: string; /** SharedStreetsLinearReferences referenceLength. */ public referenceLength: (number|Long); /** SharedStreetsLinearReferences references. */ public references: ILinearReference[]; /** * Creates a new SharedStreetsLinearReferences instance using the specified properties. * @param [properties] Properties to set * @returns SharedStreetsLinearReferences instance */ public static create(properties?: ISharedStreetsLinearReferences): SharedStreetsLinearReferences; /** * Encodes the specified SharedStreetsLinearReferences message. Does not implicitly {@link SharedStreetsLinearReferences.verify|verify} messages. * @param message SharedStreetsLinearReferences message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: ISharedStreetsLinearReferences, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified SharedStreetsLinearReferences message, length delimited. Does not implicitly {@link SharedStreetsLinearReferences.verify|verify} messages. * @param message SharedStreetsLinearReferences message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: ISharedStreetsLinearReferences, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SharedStreetsLinearReferences message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns SharedStreetsLinearReferences * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): SharedStreetsLinearReferences; /** * Decodes a SharedStreetsLinearReferences message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns SharedStreetsLinearReferences * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): SharedStreetsLinearReferences; /** * Verifies a SharedStreetsLinearReferences message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a SharedStreetsLinearReferences message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns SharedStreetsLinearReferences */ public static fromObject(object: { [k: string]: any }): SharedStreetsLinearReferences; /** * Creates a plain object from a SharedStreetsLinearReferences message. Also converts values to other types if specified. * @param message SharedStreetsLinearReferences * @param [options] Conversion options * @returns Plain object */ public static toObject(message: SharedStreetsLinearReferences, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SharedStreetsLinearReferences to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DataBin. */ export interface IDataBin { /** DataBin dataType */ dataType?: (string[]|null); /** DataBin count */ count?: ((number|Long)[]|null); /** DataBin value */ value?: (number[]|null); } /** Represents a DataBin. */ export class DataBin implements IDataBin { /** * Constructs a new DataBin. * @param [properties] Properties to set */ constructor(properties?: IDataBin); /** DataBin dataType. */ public dataType: string[]; /** DataBin count. */ public count: (number|Long)[]; /** DataBin value. */ public value: number[]; /** * Creates a new DataBin instance using the specified properties. * @param [properties] Properties to set * @returns DataBin instance */ public static create(properties?: IDataBin): DataBin; /** * Encodes the specified DataBin message. Does not implicitly {@link DataBin.verify|verify} messages. * @param message DataBin message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IDataBin, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DataBin message, length delimited. Does not implicitly {@link DataBin.verify|verify} messages. * @param message DataBin message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IDataBin, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DataBin message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DataBin * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): DataBin; /** * Decodes a DataBin message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DataBin * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): DataBin; /** * Verifies a DataBin message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DataBin message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DataBin */ public static fromObject(object: { [k: string]: any }): DataBin; /** * Creates a plain object from a DataBin message. Also converts values to other types if specified. * @param message DataBin * @param [options] Conversion options * @returns Plain object */ public static toObject(message: DataBin, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DataBin to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BinnedPeriodicData. */ export interface IBinnedPeriodicData { /** BinnedPeriodicData periodOffset */ periodOffset?: (number[]|null); /** BinnedPeriodicData bins */ bins?: (IDataBin[]|null); } /** Represents a BinnedPeriodicData. */ export class BinnedPeriodicData implements IBinnedPeriodicData { /** * Constructs a new BinnedPeriodicData. * @param [properties] Properties to set */ constructor(properties?: IBinnedPeriodicData); /** BinnedPeriodicData periodOffset. */ public periodOffset: number[]; /** BinnedPeriodicData bins. */ public bins: IDataBin[]; /** * Creates a new BinnedPeriodicData instance using the specified properties. * @param [properties] Properties to set * @returns BinnedPeriodicData instance */ public static create(properties?: IBinnedPeriodicData): BinnedPeriodicData; /** * Encodes the specified BinnedPeriodicData message. Does not implicitly {@link BinnedPeriodicData.verify|verify} messages. * @param message BinnedPeriodicData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IBinnedPeriodicData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BinnedPeriodicData message, length delimited. Does not implicitly {@link BinnedPeriodicData.verify|verify} messages. * @param message BinnedPeriodicData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IBinnedPeriodicData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BinnedPeriodicData message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BinnedPeriodicData * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): BinnedPeriodicData; /** * Decodes a BinnedPeriodicData message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BinnedPeriodicData * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): BinnedPeriodicData; /** * Verifies a BinnedPeriodicData message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BinnedPeriodicData message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BinnedPeriodicData */ public static fromObject(object: { [k: string]: any }): BinnedPeriodicData; /** * Creates a plain object from a BinnedPeriodicData message. Also converts values to other types if specified. * @param message BinnedPeriodicData * @param [options] Conversion options * @returns Plain object */ public static toObject(message: BinnedPeriodicData, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BinnedPeriodicData to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SharedStreetsBinnedLinearReferences. */ export interface ISharedStreetsBinnedLinearReferences { /** SharedStreetsBinnedLinearReferences referenceId */ referenceId?: (string|null); /** SharedStreetsBinnedLinearReferences scaledCounts */ scaledCounts?: (boolean|null); /** SharedStreetsBinnedLinearReferences referenceLength */ referenceLength?: (number|Long|null); /** SharedStreetsBinnedLinearReferences numberOfBins */ numberOfBins?: (number|null); /** SharedStreetsBinnedLinearReferences binPosition */ binPosition?: (number[]|null); /** SharedStreetsBinnedLinearReferences bins */ bins?: (IDataBin[]|null); } /** Represents a SharedStreetsBinnedLinearReferences. */ export class SharedStreetsBinnedLinearReferences implements ISharedStreetsBinnedLinearReferences { /** * Constructs a new SharedStreetsBinnedLinearReferences. * @param [properties] Properties to set */ constructor(properties?: ISharedStreetsBinnedLinearReferences); /** SharedStreetsBinnedLinearReferences referenceId. */ public referenceId: string; /** SharedStreetsBinnedLinearReferences scaledCounts. */ public scaledCounts: boolean; /** SharedStreetsBinnedLinearReferences referenceLength. */ public referenceLength: (number|Long); /** SharedStreetsBinnedLinearReferences numberOfBins. */ public numberOfBins: number; /** SharedStreetsBinnedLinearReferences binPosition. */ public binPosition: number[]; /** SharedStreetsBinnedLinearReferences bins. */ public bins: IDataBin[]; /** * Creates a new SharedStreetsBinnedLinearReferences instance using the specified properties. * @param [properties] Properties to set * @returns SharedStreetsBinnedLinearReferences instance */ public static create(properties?: ISharedStreetsBinnedLinearReferences): SharedStreetsBinnedLinearReferences; /** * Encodes the specified SharedStreetsBinnedLinearReferences message. Does not implicitly {@link SharedStreetsBinnedLinearReferences.verify|verify} messages. * @param message SharedStreetsBinnedLinearReferences message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: ISharedStreetsBinnedLinearReferences, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified SharedStreetsBinnedLinearReferences message, length delimited. Does not implicitly {@link SharedStreetsBinnedLinearReferences.verify|verify} messages. * @param message SharedStreetsBinnedLinearReferences message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: ISharedStreetsBinnedLinearReferences, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SharedStreetsBinnedLinearReferences message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns SharedStreetsBinnedLinearReferences * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): SharedStreetsBinnedLinearReferences; /** * Decodes a SharedStreetsBinnedLinearReferences message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns SharedStreetsBinnedLinearReferences * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): SharedStreetsBinnedLinearReferences; /** * Verifies a SharedStreetsBinnedLinearReferences message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a SharedStreetsBinnedLinearReferences message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns SharedStreetsBinnedLinearReferences */ public static fromObject(object: { [k: string]: any }): SharedStreetsBinnedLinearReferences; /** * Creates a plain object from a SharedStreetsBinnedLinearReferences message. Also converts values to other types if specified. * @param message SharedStreetsBinnedLinearReferences * @param [options] Conversion options * @returns Plain object */ public static toObject(message: SharedStreetsBinnedLinearReferences, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SharedStreetsBinnedLinearReferences to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** PeriodSize enum. */ export enum PeriodSize { OneSecond = 0, FiveSeconds = 1, TenSeconds = 2, FifteenSeconds = 3, ThirtySeconds = 4, OneMinute = 5, FiveMinutes = 6, TenMinutes = 7, FifteenMinutes = 8, ThirtyMinutes = 9, OneHour = 10, OneDay = 11, OneWeek = 12, OneMonth = 13, OneYear = 14 } /** Properties of a SharedStreetsWeeklyBinnedLinearReferences. */ export interface ISharedStreetsWeeklyBinnedLinearReferences { /** SharedStreetsWeeklyBinnedLinearReferences referenceId */ referenceId?: (string|null); /** SharedStreetsWeeklyBinnedLinearReferences periodSize */ periodSize?: (PeriodSize|null); /** SharedStreetsWeeklyBinnedLinearReferences scaledCounts */ scaledCounts?: (boolean|null); /** SharedStreetsWeeklyBinnedLinearReferences referenceLength */ referenceLength?: (number|Long|null); /** SharedStreetsWeeklyBinnedLinearReferences numberOfBins */ numberOfBins?: (number|null); /** SharedStreetsWeeklyBinnedLinearReferences binPosition */ binPosition?: (number[]|null); /** SharedStreetsWeeklyBinnedLinearReferences binnedPeriodicData */ binnedPeriodicData?: (IBinnedPeriodicData[]|null); } /** Represents a SharedStreetsWeeklyBinnedLinearReferences. */ export class SharedStreetsWeeklyBinnedLinearReferences implements ISharedStreetsWeeklyBinnedLinearReferences { /** * Constructs a new SharedStreetsWeeklyBinnedLinearReferences. * @param [properties] Properties to set */ constructor(properties?: ISharedStreetsWeeklyBinnedLinearReferences); /** SharedStreetsWeeklyBinnedLinearReferences referenceId. */ public referenceId: string; /** SharedStreetsWeeklyBinnedLinearReferences periodSize. */ public periodSize: PeriodSize; /** SharedStreetsWeeklyBinnedLinearReferences scaledCounts. */ public scaledCounts: boolean; /** SharedStreetsWeeklyBinnedLinearReferences referenceLength. */ public referenceLength: (number|Long); /** SharedStreetsWeeklyBinnedLinearReferences numberOfBins. */ public numberOfBins: number; /** SharedStreetsWeeklyBinnedLinearReferences binPosition. */ public binPosition: number[]; /** SharedStreetsWeeklyBinnedLinearReferences binnedPeriodicData. */ public binnedPeriodicData: IBinnedPeriodicData[]; /** * Creates a new SharedStreetsWeeklyBinnedLinearReferences instance using the specified properties. * @param [properties] Properties to set * @returns SharedStreetsWeeklyBinnedLinearReferences instance */ public static create(properties?: ISharedStreetsWeeklyBinnedLinearReferences): SharedStreetsWeeklyBinnedLinearReferences; /** * Encodes the specified SharedStreetsWeeklyBinnedLinearReferences message. Does not implicitly {@link SharedStreetsWeeklyBinnedLinearReferences.verify|verify} messages. * @param message SharedStreetsWeeklyBinnedLinearReferences message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: ISharedStreetsWeeklyBinnedLinearReferences, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified SharedStreetsWeeklyBinnedLinearReferences message, length delimited. Does not implicitly {@link SharedStreetsWeeklyBinnedLinearReferences.verify|verify} messages. * @param message SharedStreetsWeeklyBinnedLinearReferences message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: ISharedStreetsWeeklyBinnedLinearReferences, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SharedStreetsWeeklyBinnedLinearReferences message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns SharedStreetsWeeklyBinnedLinearReferences * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): SharedStreetsWeeklyBinnedLinearReferences; /** * Decodes a SharedStreetsWeeklyBinnedLinearReferences message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns SharedStreetsWeeklyBinnedLinearReferences * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): SharedStreetsWeeklyBinnedLinearReferences; /** * Verifies a SharedStreetsWeeklyBinnedLinearReferences message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a SharedStreetsWeeklyBinnedLinearReferences message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns SharedStreetsWeeklyBinnedLinearReferences */ public static fromObject(object: { [k: string]: any }): SharedStreetsWeeklyBinnedLinearReferences; /** * Creates a plain object from a SharedStreetsWeeklyBinnedLinearReferences message. Also converts values to other types if specified. * @param message SharedStreetsWeeklyBinnedLinearReferences * @param [options] Conversion options * @returns Plain object */ public static toObject(message: SharedStreetsWeeklyBinnedLinearReferences, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SharedStreetsWeeklyBinnedLinearReferences to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; }
the_stack
import { Component, OnInit, ViewChild, ViewChildren, QueryList } from '@angular/core'; import { AccountService } from '../account.service'; import { HttpErrorResponse } from '@angular/common/http'; import { MessageService } from 'src/app/shared/message/message.service'; import { VariableInputComponent } from 'src/app/shared/variable-input/variable-input.component'; import { ClrLoadingState } from '@clr/angular'; import { AppInitService } from 'src/app/shared.service/app-init.service'; import { InitStatus, InitStatusCode } from 'src/app/shared.service/app-init.model'; import { User } from '../account.model'; import { BoardService } from 'src/app/shared.service/board.service'; import { ConfigurationService } from 'src/app/shared.service/configuration.service'; import { Configuration } from 'src/app/shared.service/cfg.model'; import { Router } from '@angular/router'; import { Message, ReturnStatus } from 'src/app/shared/message/message.types'; @Component({ selector: 'app-installation', templateUrl: './installation.component.html', styleUrls: ['./installation.component.css'] }) export class InstallationComponent implements OnInit { debugMode = false; status = 'status1'; newDate = new Date('2016-01-01 09:00:00'); passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)([A-Za-z\d#?!@$%^&*-]){8,20}$/; uuidPattern = /^\w{8}(-\w{4}){3}-\w{12}$/; uuid = ''; config: Configuration; showBaselineHelper = false; installStep = 0; ignoreStep1 = false; ignoreStep2 = false; installProgress = 0; enableBtn = true; refresh = false; simpleMode = false; loadingFlag = true; disconnect = false; enableInitialization = false; openSSH = false; uninstallConfirm = false; clearDate = false; responsibility = false; isEditable = true; submitBtnState: ClrLoadingState = ClrLoadingState.DEFAULT; editBtnState: ClrLoadingState = ClrLoadingState.DEFAULT; startBtnState: ClrLoadingState = ClrLoadingState.DEFAULT; uninstallBtnState: ClrLoadingState = ClrLoadingState.DEFAULT; isEdit = false; isStart = false; isUninstall = false; user: User; startLog = ''; modalSize = ''; @ViewChild('UUID') uuidInput: VariableInputComponent; @ViewChildren(VariableInputComponent) myInputTemplateComponents: QueryList<VariableInputComponent>; constructor(private accountService: AccountService, private appInitService: AppInitService, private boardService: BoardService, private configurationService: ConfigurationService, private messageService: MessageService, private router: Router) { this.user = new User(); } ngOnInit() { if (this.debugMode) { setTimeout(() => { this.loadingFlag = false; this.enableInitialization = true; }, 100); return; } this.appInitService.getSystemStatus().subscribe( (res: InitStatus) => { if (InitStatusCode.InitStatusThird === res.status) { this.messageService.showOnlyOkDialogObservable('INITIALIZATION.ALERTS.ALREADY_START').subscribe( (msg: Message) => { if (msg.returnStatus === ReturnStatus.rsConfirm) { this.router.navigateByUrl('account'); } } ); } else { this.accountService.createUUID().subscribe( () => { this.loadingFlag = false; this.enableInitialization = true; }, (err: HttpErrorResponse) => { this.loadingFlag = false; this.disconnect = true; console.error(err.message); this.messageService.showOnlyOkDialog('INITIALIZATION.ALERTS.INITIALIZATION', 'ACCOUNT.ERROR'); this.refresh = true; }); } }, (err: HttpErrorResponse) => { console.error(err.message); this.getSysStatusFailed(); } ); } onNext() { // for test if (this.debugMode) { if ('status1' === this.status) { this.config = new Configuration(); setTimeout(() => { this.ignoreStep1 = true; this.installStep = 2; this.installProgress = 50; }, 1000); } else if ('status2' === this.status) { this.installStep++; this.installProgress += 33; } else if ('status3' === this.status) { this.ignoreStep1 = true; this.ignoreStep2 = true; this.installStep = 3; this.installProgress = 100; this.messageService.showOnlyOkDialog('INITIALIZATION.ALERTS.ALREADY_START'); } else { alert('error status!'); } return; } this.uuidInput.checkSelf(); if (this.uuidInput.isValid) { this.submitBtnState = ClrLoadingState.LOADING; this.user.username = 'boardadmin'; this.user.password = this.uuid; this.accountService.signIn(this.user).subscribe( () => { this.user = new User(); sessionStorage.setItem('token', this.uuid); this.appInitService.getSystemStatus().subscribe( (res: InitStatus) => { switch (res.status) { // 未起Board且未更改cfg case InitStatusCode.InitStatusFirst: { this.configurationService.getConfig().subscribe( (resTmp: Configuration) => { this.config = new Configuration(resTmp); this.isEditable = true; this.ignoreStep1 = true; this.installStep = 2; this.installProgress = 50; this.submitBtnState = ClrLoadingState.DEFAULT; }, (err: HttpErrorResponse) => { // COMMON this.commonError(err, {}, 'INITIALIZATION.ALERTS.GET_CFG_FAILED'); } ); break; } // 未起Board但更改过cfg case InitStatusCode.InitStatusSecond: { this.installStep++; this.installProgress += 33; this.submitBtnState = ClrLoadingState.DEFAULT; break; } // Board已经运行 case InitStatusCode.InitStatusThird: { this.ignoreStep1 = true; this.ignoreStep2 = true; this.installStep = 3; this.installProgress = 100; this.messageService.showOnlyOkDialog('INITIALIZATION.ALERTS.ALREADY_START'); this.submitBtnState = ClrLoadingState.DEFAULT; break; } } }, (err: HttpErrorResponse) => { console.error(err.message); this.getSysStatusFailed(); } ); }, (err: HttpErrorResponse) => { console.error(err.message); this.messageService.showOnlyOkDialog('INITIALIZATION.ALERTS.VALIDATE_UUID_FAILED', 'ACCOUNT.ERROR'); this.refresh = true; this.submitBtnState = ClrLoadingState.DEFAULT; } ); } } onEditCfg() { // for test if (this.debugMode) { this.editBtnState = ClrLoadingState.LOADING; this.isEdit = true; setTimeout(() => { this.installStep++; this.installProgress += 33; this.config = new Configuration(); this.editBtnState = ClrLoadingState.DEFAULT; }, 5000); return; } this.editBtnState = ClrLoadingState.LOADING; this.isEdit = true; this.configurationService.getConfig().subscribe( (res: Configuration) => { this.config = new Configuration(res); if (this.config.tmpExist) { this.configurationService.getConfig('tmp').subscribe( (resTmp: Configuration) => { this.config = new Configuration(resTmp); this.newDate = new Date(this.config.k8s.imageBaselineTime); this.isEditable = this.config.isInit; this.installStep++; this.installProgress += 33; this.editBtnState = ClrLoadingState.DEFAULT; }, (err: HttpErrorResponse) => { if (err.status === 401) { this.tokenError(); } else { console.log('Can not read tmp file: ' + err.message); this.messageService.showOnlyOkDialog('INITIALIZATION.ALERTS.GET_TMP_FAILED'); this.newDate = new Date(this.config.k8s.imageBaselineTime); this.isEditable = this.config.isInit; this.installStep++; this.installProgress += 33; this.editBtnState = ClrLoadingState.DEFAULT; } } ); } else { this.newDate = new Date(this.config.k8s.imageBaselineTime); this.isEditable = this.config.isInit; this.installStep++; this.installProgress += 33; this.editBtnState = ClrLoadingState.DEFAULT; } }, (err: HttpErrorResponse) => { // COMMON this.isEdit = false; this.commonError(err, {}, 'INITIALIZATION.ALERTS.GET_CFG_FAILED'); }, ); } onStartBoard() { // for test if (this.debugMode) { this.startBtnState = ClrLoadingState.LOADING; this.submitBtnState = ClrLoadingState.LOADING; this.isStart = true; setTimeout(() => { this.openSSH = false; this.installStep += 2; this.ignoreStep2 = true; this.installProgress = 100; this.startBtnState = ClrLoadingState.DEFAULT; this.submitBtnState = ClrLoadingState.DEFAULT; }, 20000); return; } this.startBtnState = ClrLoadingState.LOADING; this.submitBtnState = ClrLoadingState.LOADING; this.isStart = true; this.boardService.start(this.user).subscribe( () => { this.openSSH = false; this.installStep += 2; this.ignoreStep2 = true; this.installProgress = 100; this.startBtnState = ClrLoadingState.DEFAULT; this.submitBtnState = ClrLoadingState.DEFAULT; }, (err: HttpErrorResponse) => { // COMMON this.openSSH = false; this.isStart = false; this.commonError(err, {}, 'INITIALIZATION.ALERTS.START_BOARD_FAILED'); }, ); } onUninstallBoard() { // for test if (this.debugMode) { this.uninstallBtnState = ClrLoadingState.LOADING; this.submitBtnState = ClrLoadingState.LOADING; this.isUninstall = true; setTimeout(() => { this.openSSH = false; this.installStep = 4; this.ignoreStep1 = true; this.ignoreStep2 = true; this.installProgress = 100; this.uninstallBtnState = ClrLoadingState.DEFAULT; this.submitBtnState = ClrLoadingState.DEFAULT; }, 20000); return; } this.uninstallBtnState = ClrLoadingState.LOADING; this.submitBtnState = ClrLoadingState.LOADING; this.isUninstall = true; this.boardService.shutdown(this.user, this.clearDate).subscribe( () => { this.openSSH = false; this.installStep = 4; this.ignoreStep1 = true; this.ignoreStep2 = true; this.installProgress = 100; this.uninstallBtnState = ClrLoadingState.DEFAULT; this.submitBtnState = ClrLoadingState.DEFAULT; }, (err: HttpErrorResponse) => { // COMMON this.openSSH = false; this.isUninstall = false; this.commonError(err, { 503: 'INITIALIZATION.ALERTS.ALREADY_UNINSTALL' }, 'INITIALIZATION.ALERTS.UNINSTALL_BOARD_FAILED'); }, ); } onApplyAndStartBoard() { // for test if (this.debugMode) { this.submitBtnState = ClrLoadingState.LOADING; let helloTime = 0; const outPutLog = setInterval(() => { this.startLog += `hello world! ${helloTime++}\n`; if (!this.modalSize) { this.modalSize = 'xl'; } }, 1000); setTimeout(() => { this.openSSH = false; this.installStep++; this.installProgress = 100; this.submitBtnState = ClrLoadingState.DEFAULT; this.modalSize = ''; clearInterval(outPutLog); }, 60 * 1000); return; } this.submitBtnState = ClrLoadingState.LOADING; let maxTry = 100; const installStepNow = this.installStep; this.configurationService.putConfig(this.config).subscribe( () => { this.boardService.applyCfg(this.user).subscribe( () => { const initProcess = setInterval(() => { this.appInitService.getSystemStatus().subscribe( (res: InitStatus) => { if (InitStatusCode.InitStatusThird === res.status) { if (this.installStep === installStepNow) { this.installStep++; } this.installProgress = 100; this.openSSH = false; this.submitBtnState = ClrLoadingState.DEFAULT; this.modalSize = ''; this.startLog = ''; clearInterval(initProcess); } else { this.startLog = res.log; if (!this.modalSize) { this.modalSize = 'xl'; } } }, (err: HttpErrorResponse) => { console.error(err.message); if (maxTry-- < 0) { this.getSysStatusFailed(); clearInterval(initProcess); } }, ); }, 5 * 1000); }, (err: HttpErrorResponse) => { // COMMON this.commonError(err, {}, 'INITIALIZATION.ALERTS.START_BOARD_FAILED'); }, ); }, (err: HttpErrorResponse) => { // COMMON this.commonError(err, {}, 'INITIALIZATION.ALERTS.POST_CFG_FAILED'); }, ); } goToBoard() { if (this.config) { const protocol = this.config.board.mode === 'normal' ? 'http' : 'https'; window.open(`${protocol}://${this.config.board.hostname}`); } else { const boardURL = window.location.hostname; window.open('http://' + boardURL); } } goToAdminserver() { window.sessionStorage.removeItem('token'); this.router.navigateByUrl('account/login'); } onFocusBaselineHelper() { this.showBaselineHelper = true; } onBlurBaselineHelper() { this.showBaselineHelper = false; const year = this.newDate.getFullYear(); const month = this.newDate.getMonth() + 1; const day = this.newDate.getDate(); this.config.k8s.imageBaselineTime = '' + year + '-' + month + '-' + day + ' 00:00:00'; } onCheckInput() { if (this.checkInput()) { this.openSSH = true; this.uninstallConfirm = false; this.user.password = ''; } } checkInput(): boolean { let result = true; for (const item of this.myInputTemplateComponents.toArray()) { item.checkSelf(); if (!item.disabled && !item.isValid) { item.element.nativeElement.scrollIntoView(); result = false; break; } } return result; } commonError(err: HttpErrorResponse, errorList: object, finnalError: string) { console.error(err.message); this.refresh = true; this.submitBtnState = ClrLoadingState.DEFAULT; this.editBtnState = ClrLoadingState.DEFAULT; this.startBtnState = ClrLoadingState.DEFAULT; this.uninstallBtnState = ClrLoadingState.DEFAULT; if (err.status === 401) { this.tokenError(); return; } for (const key in errorList) { if (err.status === Number(key)) { this.messageService.showOnlyOkDialog(String(errorList[key]), 'ACCOUNT.ERROR'); return; } } this.messageService.showOnlyOkDialog(finnalError, 'ACCOUNT.ERROR'); } getSysStatusFailed() { this.messageService.showOnlyOkDialogObservable('INITIALIZATION.ALERTS.GET_SYS_STATUS_FAILED', 'ACCOUNT.ERROR').subscribe( (msg: Message) => { if (msg.returnStatus === ReturnStatus.rsConfirm) { location.reload(); } } ); this.submitBtnState = ClrLoadingState.DEFAULT; } tokenError() { this.messageService.showOnlyOkDialogObservable('ACCOUNT.TOKEN_ERROR_TO_REFRESH', 'ACCOUNT.ERROR').subscribe( (msg: Message) => { if (msg.returnStatus === ReturnStatus.rsConfirm) { location.reload(); } } ); } }
the_stack
import {} from "jasmine"; import { Default } from "../../../src/Default/default"; import { ContainerWindow } from "../../../src/window"; import { Container } from "../../../src/container"; class MockWindow { public listener: any; public name: string = "Name"; public focus(): void { } public show(): void { } public close(): Promise<void> { return Promise.resolve(); } public open(url?: string, target?: string, features?: string, replace?: boolean): any { return new MockWindow(); } public addEventListener(type: string, listener: any): void { this.listener = listener; } public removeEventListener(type: string, listener: any): void { } public postMessage(message: string, origin: string): void { } public moveTo(x: number, y: number): void { } public resizeTo(width: number, height: number): void { } public getState(): Promise<any> { return Promise.resolve(undefined); } public setState(): Promise<void> { return Promise.resolve(); } public screenX: any = 0; public screenY: any = 1; public outerWidth: any = 2; public outerHeight: any = 3; location: any = { origin: "origin", replace(url: string) {} }; } describe("DefaultContainerWindow", () => { const mockWindow = new MockWindow(); let win: Default.DefaultContainerWindow; beforeEach(() => { win = new Default.DefaultContainerWindow(mockWindow); }); describe("focus", () => { it("Invokes underlying window focus and resolves promise", () => { spyOn(mockWindow, 'focus'); win.focus(); expect(mockWindow.focus).toHaveBeenCalled(); }); }); it ("load invokes underlying location.replace", async () => { spyOn(mockWindow.location, 'replace').and.callThrough(); await win.load("url"); expect(mockWindow.location.replace).toHaveBeenCalledWith("url"); }); it ("id returns underlying id", () => { mockWindow[Default.DefaultContainer.windowUuidPropertyKey] = "UUID"; expect(win.id).toEqual("UUID"); }); it ("name returns underlying name", () => { mockWindow[Default.DefaultContainer.windowNamePropertyKey] = "NAME"; expect(win.name).toEqual("NAME"); }); it("show throws no errors", () => { expect(win.show()).toBeDefined(); }); it("hide throws no errors", () => { expect(win.hide()).toBeDefined(); }); it("isShowing throws no errors", () => { expect(win.isShowing()).toBeDefined(); }); describe("getState", () => { it("getState undefined", async () => { const mockWindow = {}; const win = new Default.DefaultContainerWindow(mockWindow); const state = await win.getState(); expect(state).toBeUndefined(); }); it("getState defined", async () => { const mockState = { value: "Foo" }; spyOn(win.innerWindow, "getState").and.returnValue(Promise.resolve(mockState)); const state = await win.getState(); expect(win.innerWindow.getState).toHaveBeenCalled(); expect(state).toEqual(mockState); }); }); describe("setState", () => { it("setState undefined", async () => { const mockWindow = {}; const win = new Default.DefaultContainerWindow(mockWindow); await expectAsync(win.setState({})).toBeResolved(); }); it("setState defined", async () => { const mockState = { value: "Foo" }; spyOn(win.innerWindow, "setState").and.returnValue(Promise.resolve()); await win.setState(mockState); expect(win.innerWindow.setState).toHaveBeenCalledWith(mockState); }); }); it("getSnapshot rejects", async () => { await expectAsync(win.getSnapshot()).toBeRejected(); }); it("close", async () => { spyOn(win, "close").and.callThrough(); await win.close(); expect(win.close).toHaveBeenCalled(); }); it("minimize", async () => { const innerWindow = jasmine.createSpyObj("BrowserWindow", ["minimize"]); await new Default.DefaultContainerWindow(innerWindow).minimize(); expect(innerWindow.minimize).toHaveBeenCalledTimes(1); }); it("maximize", async () => { const innerWindow = jasmine.createSpyObj("BrowserWindow", ["maximize"]); await new Default.DefaultContainerWindow(innerWindow).maximize(); expect(innerWindow.maximize).toHaveBeenCalledTimes(1); }); it("restore", async () => { const innerWindow = jasmine.createSpyObj("BrowserWindow", ["restore"]); await new Default.DefaultContainerWindow(innerWindow).restore(); expect(innerWindow.restore).toHaveBeenCalledTimes(1); }); it("getBounds retrieves underlying window position", async () => { const bounds = await win.getBounds(); expect(bounds).toBeDefined(); expect(bounds.x).toEqual(0); expect(bounds.y).toEqual(1); expect(bounds.width).toEqual(2); expect(bounds.height).toEqual(3); }); it("setBounds sets underlying window position", async () => { spyOn(win.innerWindow, "moveTo").and.callThrough() spyOn(win.innerWindow, "resizeTo").and.callThrough(); await win.setBounds(<any>{ x: 0, y: 1, width: 2, height: 3 }); expect(win.innerWindow.moveTo).toHaveBeenCalledWith(0, 1); expect(win.innerWindow.resizeTo).toHaveBeenCalledWith(2, 3); }); it("flash resolves with not supported", async () => { await expectAsync(win.flash(true)).toBeRejectedWithError("Not supported"); }); it("getParent throws no errors", (done) => { expect(() => win.getParent().then(done)).not.toThrow(); }); it("setParent throws no errors", (done) => { expect(() => win.setParent(null).then(done)).not.toThrow(); }); it("getOptions", async () => { const win = await new Default.DefaultContainer(<any>new MockWindow()).createWindow("url", { a: "foo" }); const options = await win.getOptions(); expect(options).toBeDefined(); expect(options).toEqual({ a: "foo"}); }); describe("addListener", () => { it("addListener calls underlying window addEventListener with mapped event name", () => { spyOn(win.innerWindow, "addEventListener").and.callThrough() win.addListener("close", () => { }); expect(win.innerWindow.addEventListener).toHaveBeenCalledWith("unload", jasmine.any(Function)); }); it("addListener calls underlying window addEventListener with unmapped event name", () => { const unmappedEvent = "resize"; spyOn(win.innerWindow, "addEventListener").and.callThrough() win.addListener(unmappedEvent, () => { }); expect(win.innerWindow.addEventListener).toHaveBeenCalledWith(unmappedEvent, jasmine.any(Function)); }); }); describe("removeListener", () => { it("removeListener calls underlying window removeEventListener with mapped event name", () => { spyOn(win.innerWindow, "removeEventListener").and.callThrough() win.removeListener("close", () => { }); expect(win.innerWindow.removeEventListener).toHaveBeenCalledWith("unload", jasmine.any(Function)); }); it("removeListener calls underlying window removeEventListener with unmapped event name", () => { const unmappedEvent = "resize"; spyOn(win.innerWindow, "removeEventListener").and.callThrough() win.removeListener(unmappedEvent, () => { }); expect(win.innerWindow.removeEventListener).toHaveBeenCalledWith(unmappedEvent, jasmine.any(Function)); }); }); describe("window grouping", () => { it("allowGrouping is false", () => { expect(new Default.DefaultContainerWindow(null).allowGrouping).toEqual(false); }); it ("getGroup returns empty array", async () => { const windows = await new Default.DefaultContainerWindow(null).getGroup(); expect(windows).toBeDefined(); expect(windows.length).toEqual(0); }); it ("joinGroup not supported", async () => { await expectAsync(new Default.DefaultContainerWindow(null).joinGroup(null)).toBeRejectedWithError("Not supported"); }); it ("leaveGroup resolves", async () => { await expectAsync(new Default.DefaultContainerWindow(null).leaveGroup()).toBeResolved(); }); }); it("nativeWindow returns wrapped window", () => { const innerWindow = {}; const nativeWindow = new Default.DefaultContainerWindow(innerWindow).nativeWindow; expect(nativeWindow).toBeDefined(); expect(nativeWindow).toEqual(<any>innerWindow); }); }); describe("DefaultContainer", () => { let window: any; beforeEach(() => { window = new MockWindow(); }); it("hostType is Default", () => { const container: Default.DefaultContainer = new Default.DefaultContainer(); expect(container.hostType).toEqual("Default"); }); it ("getInfo returns underlying navigator appversion", async () => { const window = new MockWindow(); window["navigator"] = { appVersion: "useragent" }; const container: Default.DefaultContainer = new Default.DefaultContainer(<any>window); const info = await container.getInfo(); expect(info).toEqual("useragent"); }); it("getOptions returns autoStartOnLogin as false", async () => { const window = new MockWindow(); const container: Default.DefaultContainer = new Default.DefaultContainer(<any>window); const result = await container.getOptions(); expect(result.autoStartOnLogin).toBeUndefined(); }); describe("createWindow", () => { let container: Default.DefaultContainer; beforeEach(() => { window = new MockWindow(); container = new Default.DefaultContainer(window); }); it("Returns a DefaultContainerWindow and invokes underlying window.open", async () => { spyOn(window, "open").and.callThrough(); await container.createWindow("url"); expect(window.open).toHaveBeenCalledWith("url", "_blank", undefined); }); it("Options target property maps to open target parameter", async () => { spyOn(window, "open").and.callThrough(); await container.createWindow("url", { target: "MockTarget" }); expect(window.open).toHaveBeenCalledWith("url", "MockTarget", "target=MockTarget,"); }); it("Options parameters are converted to features", async () => { spyOn(window, "open").and.callThrough(); await container.createWindow("url", { x: "x0", y: "y0" }); expect(window.open).toHaveBeenCalledWith("url", "_blank", "left=x0,top=y0,"); }); it("Window is added to windows", async () => { const win = await container.createWindow("url"); const newWin = win.innerWindow; expect(newWin[Default.DefaultContainer.windowUuidPropertyKey]).toBeDefined(); expect(newWin[Default.DefaultContainer.windowsPropertyKey]).toBeDefined(); expect(newWin[Default.DefaultContainer.windowsPropertyKey][newWin[Default.DefaultContainer.windowUuidPropertyKey]]).toBeDefined(); }); it("Window is removed from windows on close", async () => { const win = await container.createWindow("url"); const newWin = win.innerWindow; expect(newWin[Default.DefaultContainer.windowsPropertyKey][newWin[Default.DefaultContainer.windowUuidPropertyKey]]).toBeDefined(); newWin.listener("beforeunload", {}); newWin.listener("unload", {}); expect(newWin[Default.DefaultContainer.windowsPropertyKey][newWin[Default.DefaultContainer.windowUuidPropertyKey]]).toBeUndefined(); }); it("Window from window.open is removed from windows on close", () => { const newWin = window.open("url"); expect(newWin[Default.DefaultContainer.windowsPropertyKey][newWin[Default.DefaultContainer.windowUuidPropertyKey]]).toBeDefined(); newWin.listener("beforeunload", {}); newWin.listener("unload", {}); expect(newWin[Default.DefaultContainer.windowsPropertyKey][newWin[Default.DefaultContainer.windowUuidPropertyKey]]).toBeUndefined(); }); it("createWindow fires window-created", (done) => { container.addListener("window-created", () => done()); container.createWindow("url"); }); it("createWindow warns when it cannot propagate properties to the new window", async () => { spyOn(container, "log"); spyOn(window, "open").and.callFake(() => { const mockWin = new MockWindow(); Object.defineProperty(mockWin, Container.windowOptionsPropertyKey, { writable: false }); return mockWin; }); const win = await container.createWindow("url"); expect(win).toBeDefined(); expect(container.log).toHaveBeenCalledWith("warn", jasmine.any(String)); }); }); it("window.open logs a warning when it cannot track the new window", () => { window = new MockWindow(); spyOn(window, 'open').and.callFake(() => { const win = new MockWindow(); Object.defineProperty(win, Default.DefaultContainer.windowsPropertyKey, { writable: false }); return win; }); const container = new Default.DefaultContainer(window); spyOn(container, "log"); window.open("url"); expect(container.log).toHaveBeenCalledWith("warn", jasmine.any(String)); }); it("getMainWindow returns DefaultContainerWindow wrapping scoped window", () => { const container: Default.DefaultContainer = new Default.DefaultContainer(window); const win: ContainerWindow = container.getMainWindow(); expect(win).toBeDefined(); expect(win.id).toEqual("root"); expect(win.innerWindow).toEqual(window); }); it("getCurrentWindow returns DefaultContainerWindow wrapping scoped window", () => { const container: Default.DefaultContainer = new Default.DefaultContainer(window); const win: ContainerWindow = container.getCurrentWindow(); expect(win).toBeDefined(); expect(win.innerWindow).toEqual(window); }); describe("Notifications", () => { it("showNotification warns about not being implemented", () => { const container: Default.DefaultContainer = new Default.DefaultContainer(window); spyOn(console, "warn"); container.showNotification("message", {}); expect(console.warn).toHaveBeenCalledWith("Notifications not supported"); }); it("showNotification warns about not being permitted", () => { const window = { Notification: { requestPermission(callback: (permission: string) => void) { callback("denied"); } } }; spyOn(console, "warn"); const container: Default.DefaultContainer = new Default.DefaultContainer(<any>window); container.showNotification("message", {}); expect(console.warn).toHaveBeenCalledWith("Notifications not permitted"); }); it("showNotification calls the Notification API if permitted", () => { const window = jasmine.createSpyObj('notificationWindow', ['Notification']); window.Notification.requestPermission = (callback: (permission: string) => void) => { callback("granted"); }; const container = new Default.DefaultContainer(<any>window); const options = {}; container.showNotification("message", options); expect(window.Notification).toHaveBeenCalledWith("message", options); }); }); describe("window management", () => { it("getAllWindows returns wrapped native windows", async () => { window[Default.DefaultContainer.windowsPropertyKey] = { "1": new MockWindow(), "2": new MockWindow() }; const container: Default.DefaultContainer = new Default.DefaultContainer(window); const wins = await container.getAllWindows() expect(wins).not.toBeNull(); expect(wins.length).toEqual(2); wins.forEach(win => expect(win instanceof Default.DefaultContainerWindow).toBeTruthy("Window is not of type DefaultContainerWindow")); }); describe("getWindow", () => { let container: Default.DefaultContainer; beforeEach(() => { container = new Default.DefaultContainer(window); }); it("getWindowById returns wrapped window", async () => { window[Default.DefaultContainer.windowsPropertyKey] = { "1": new MockWindow(), "2": new MockWindow(), "3": new MockWindow() }; const win = await container.getWindowById("1"); expect(win).toBeDefined(); expect(win.innerWindow).toEqual(window[Default.DefaultContainer.windowsPropertyKey]["1"]); }); it ("getWindowById with unknown id returns null", async () => { const win = await container.getWindowById("DoesNotExist"); expect(win).toBeNull(); }); it("getWindowByName returns wrapped window", async () => { window[Default.DefaultContainer.windowsPropertyKey] = { "1": new MockWindow(), "2": new MockWindow(), "3": new MockWindow() }; window[Default.DefaultContainer.windowsPropertyKey]["1"][Default.DefaultContainer.windowNamePropertyKey] = "Name"; const win = await container.getWindowByName("Name"); expect(win).toBeDefined(); expect(win.innerWindow).toEqual(window[Default.DefaultContainer.windowsPropertyKey]["1"]); }); it ("getWindowByName with unknown name returns null", async () => { const win = await container.getWindowByName("DoesNotExist"); expect(win).toBeNull(); }); }); it("closeAllWindows invokes window.close", async () => { const container: Default.DefaultContainer = new Default.DefaultContainer(window); spyOn(window, "close").and.callThrough(); await (<any>container).closeAllWindows(); expect(window.close).toHaveBeenCalled(); }); it("saveLayout invokes underlying saveLayoutToStorage", async () => { window[Default.DefaultContainer.windowsPropertyKey] = { "1": new MockWindow(), "2": new MockWindow() }; const container: Default.DefaultContainer = new Default.DefaultContainer(window); spyOn<any>(container, "saveLayoutToStorage").and.stub(); const layout = await container.saveLayout("Test"); expect(layout).toBeDefined(); expect((<any>container).saveLayoutToStorage).toHaveBeenCalledWith("Test", layout); }); describe("buildLayout", () => { let container: Default.DefaultContainer; beforeEach(() => { container = new Default.DefaultContainer(window); }); it("skips windows with persist false", async () => { window[Default.DefaultContainer.windowsPropertyKey] = { "1": new MockWindow(), "2": new MockWindow() }; window[Default.DefaultContainer.windowsPropertyKey]["1"][Default.DefaultContainer.windowNamePropertyKey] = "win1"; window[Default.DefaultContainer.windowsPropertyKey]["1"][Container.windowOptionsPropertyKey] = { persist: false }; window[Default.DefaultContainer.windowsPropertyKey]["2"][Default.DefaultContainer.windowNamePropertyKey] = "win2"; const layout = await container.buildLayout(); expect(layout).toBeDefined(); expect(layout.windows.length).toEqual(1); expect(layout.windows[0].name).toEqual("win2"); }); it("logs a warning when the options property is not accessible on the native window", async () => { window[Default.DefaultContainer.windowsPropertyKey] = { "1": new MockWindow() }; Object.defineProperty(window[Default.DefaultContainer.windowsPropertyKey]["1"], Container.windowOptionsPropertyKey, { get: () => { throw new Error('Access not allowed') } }); spyOn(<any>container, 'log'); await container.buildLayout(); expect((<any>container).log).toHaveBeenCalledWith("warn", jasmine.any(String)); }); it("skips the global window", async () => { window[Default.DefaultContainer.windowsPropertyKey] = { "1": new MockWindow(), "2": window }; const layout = await container.buildLayout(); expect(layout?.windows?.length).toBe(1); }); }); }); }); describe("DefaultMessageBus", () => { let container: Default.DefaultContainer; let mockWindow: any; let bus: Default.DefaultMessageBus; function callback() { } beforeEach(() => { mockWindow = new MockWindow(); container = new Default.DefaultContainer(mockWindow); bus = new Default.DefaultMessageBus(container); }); it("subscribe invokes underlying subscriber", async () => { spyOn(mockWindow, "addEventListener").and.callThrough(); const subscriber = await bus.subscribe("topic", callback); expect(subscriber.listener).toEqual(jasmine.any(Function)); expect(subscriber.topic).toEqual("topic"); expect(mockWindow.addEventListener).toHaveBeenCalledWith("message", jasmine.any(Function)); }); it("listener callback attached", async () => { const handler = jasmine.createSpy('handlerSpy', (e, data) => { expect(e.topic).toEqual("topic"); expect(data).toEqual("message"); }).and.callThrough(); const subscriber = await bus.subscribe("topic", handler); subscriber.listener({ origin: "origin", data: { source: "desktopJS", topic: "topic", message: "message" } }); expect(handler).toHaveBeenCalled(); }); it("subscriber does not call listener from a different origin", async () => { const handler = jasmine.createSpy('handlerSpy'); const subscriber = await bus.subscribe("topic", handler); subscriber.listener({ origin: "not-origin", data: { source: "desktopJS", topic: "topic", message: "message" } }); expect(handler).not.toHaveBeenCalled(); }); it("unsubscribe invokes underlying unsubscribe", async () => { spyOn(mockWindow, "removeEventListener").and.callThrough(); await bus.unsubscribe({ topic: "topic", listener: callback }); expect(mockWindow.removeEventListener).toHaveBeenCalledWith("message", jasmine.any(Function)); }); it("publish invokes underling publish", async () => { const message: any = { data: "data" }; spyOn(mockWindow, "postMessage").and.callThrough(); await bus.publish("topic", message); expect(mockWindow.postMessage).toHaveBeenCalledWith({ source: "desktopJS", topic: "topic", message: message }, "origin"); }); it("publish with non matching optional name does not invoke underling send", async () => { const message: any = {}; spyOn(mockWindow, "postMessage").and.callThrough(); await bus.publish("topic", message, { name: "target" }); expect(mockWindow.postMessage).not.toHaveBeenCalled(); }); }); describe("DefaultDisplayManager", () => { let window; let container; beforeEach(() => { window = {}; Object.defineProperty(window, "devicePixelRatio", { value: 1 }); Object.defineProperty(window, "screen", { value: {availLeft: 2, availTop: 3, availWidth: 4, availHeight: 5, width: 6, height: 7} }); Object.defineProperty(window, "event", { value: { screenX: 1, screenY: 2 }}); container = new Default.DefaultContainer(window); }); it("screen to be defined", () => { expect(container.screen).toBeDefined(); }); it("getPrimaryMonitor", async () => { const display = await container.screen.getPrimaryDisplay(); expect(display).toBeDefined(); expect(display.id).toBe("Current"); expect(display.scaleFactor).toBe(1); expect(display.bounds.x).toBe(2); expect(display.bounds.y).toBe(3); expect(display.bounds.width).toBe(6); expect(display.bounds.height).toBe(7); expect(display.workArea.x).toBe(2); expect(display.workArea.y).toBe(3); expect(display.workArea.width).toBe(4); expect(display.workArea.height).toBe(5); }); it ("getAllDisplays", async () => { const displays = await container.screen.getAllDisplays(); expect(displays).toBeDefined(); expect(displays.length).toBe(1); expect(displays[0].id).toBe("Current"); }); it ("getMousePosition", async () => { const point = await container.screen.getMousePosition(); expect(point).toEqual({ x: 1, y: 2}); }); });
the_stack
import * as jv from "jsverify" import * as assert from "./asserts" import * as inst from "./instances" import { hashCode, is, HK, Left, Right, Either, Option, EitherModule } from "../../src/" import { Equiv } from "funland-laws" import { setoidCheck, monadCheck } from "../../../../test-common" describe("Either", () => { describe("Either discrimination", () => { jv.property("isRight == !isLeft", inst.arbEitherNum, e => e.isRight() === !e.isLeft() ) }) describe("Either #get", () => { it("works for right", () => { assert.equal(Right(10).get(), 10) }) it("works for left", () => { assert.throws(() => Left(10).get()) }) }) describe("Either #contains", () => { jv.property("left.contains(elem) == false", inst.arbEitherNum, jv.number, (e, b) => e.isRight() || !e.contains(b) ) jv.property("right(e).contains(e) == true", inst.arbAny, b => Either.right(b).contains(b) ) }) describe("Either #exists", () => { jv.property("left.exists(any) == false", inst.arbEitherNum, jv.fn(jv.bool), (e, p) => e.isRight() || !e.exists(p) ) jv.property("right.exists(x => true) == true", inst.arbEitherNum, (e) => e.isLeft() || e.exists(x => true) ) jv.property("right.exists(x => false) == false", inst.arbEitherNum, e => e.isLeft() || !e.exists(x => false) ) }) describe("Either #forAll", () => { jv.property("left.forAll(x => true) == true", inst.arbEitherNum, e => e.isRight() || e.forAll(x => true) ) jv.property("left.forAll(x => false) == true", inst.arbEitherNum, e => e.isRight() || e.forAll(x => false) ) jv.property("right.forAll(x => true) == true", inst.arbEitherNum, e => e.isLeft() || e.forAll(x => true) ) jv.property("right.forAll(x => false) == false", inst.arbEitherNum, e => e.isLeft() || !e.forAll(x => false) ) }) describe("Either #filterOrElse", () => { jv.property("right.filterOrElse(x => true, ???) == right", inst.arbEitherNum, e => e.isLeft() || e.filterOrElse(b => true, () => 0).equals(e) ) jv.property("right.filterOrElse(x => false, zero) == left(zero)", inst.arbEitherNum, e => e.isLeft() || is(e.filterOrElse(b => false, () => 0), Either.left(0)) ) jv.property("left.filterOrElse(any) == left", inst.arbEitherNum, jv.fn(jv.bool), jv.number, (e, p, z) => e.isRight() || e.filterOrElse(p, () => z).equals(e) ) }) describe("Either #flatMap", () => { jv.property("right(n).flatMap(f) == f(n)", jv.number, jv.fn(inst.arbEitherNum), (n, f) => Either.right(n).flatMap(f).equals(f(n)) ) jv.property("left identity", jv.number, jv.fn(inst.arbEitherNum), (n, f) => Either.right(n).flatMap(f).equals(f(n)) ) jv.property("right identity", inst.arbEitherNum, opt => opt.flatMap(Either.right).equals(opt) ) jv.property("left.flatMap(f) == left", inst.arbEitherNum, jv.fn(inst.arbEitherNum), (e, f) => e.isRight() || e.flatMap(f) === e ) }) describe("Either #map", () => { jv.property("right(n).map(f) == right(f(n))", jv.number, jv.fn(jv.number), (n, f) => is(Either.right(n).map(f), Either.right(f(n))) ) jv.property("covariant identity", inst.arbEitherNum, opt => opt.map(x => x).equals(opt) ) jv.property("covariant composition", inst.arbEitherNum, jv.fn(jv.number), jv.fn(jv.number), (opt, f, g) => opt.map(f).map(g).equals(opt.map(x => g(f(x)))) ) }) describe("Either #fold", () => { jv.property("right(b).fold(???, f) == f(b)", inst.arbAny, jv.fn(inst.arbAny), (b, f) => is(Either.right(b).fold(x => x, f), f(b)) ) jv.property("left(a).fold(f, ???) == f(a)", inst.arbAny, jv.fn(inst.arbAny), (a, f) => is(Either.left(a).fold(f, x => x), f(a)) ) }) describe("Either #getOrElse", () => { jv.property("right(b).getOrElse(???) == b", inst.arbAny, b => is(Either.right(b).getOrElse(null), b) ) jv.property("left(a).getOrElse(b) == b", inst.arbAny, jv.string, (a, b) => is(Either.left(a).getOrElse(b), b) ) }) describe("Either #getOrElseL", () => { jv.property("right(b).getOrElseL(???) == b", inst.arbAny, b => is(Either.right(b).getOrElseL(() => null), b) ) jv.property("left(a).getOrElseL(() => b) == b", inst.arbAny, jv.string, (a, b) => { const e = Either.left<any, string>(a) return is(e.getOrElseL(() => b), b) } ) }) describe("Either #swap", () => { jv.property("right(b).swap() == left(b)", inst.arbAny, b => is(Either.right(b).swap(), Either.left(b)) ) jv.property("left(b).swap() == right(b)", inst.arbAny, b => is(Either.left(b).swap(), Either.right(b)) ) }) describe("Either #toOption", () => { jv.property("right(b).toOption == some(b)", inst.arbAny, b => is(Either.right(b).toOption(), Option.some(b)) ) jv.property("left(a).toOption == none()", inst.arbAny, a => is(Either.left(a).toOption(), Option.none()) ) }) describe("Either #equals", () => { jv.property("should yield true for self.equals(self)", inst.arbEitherNum, opt => opt.equals(opt) ) jv.property("should yield true for equals(self, self)", inst.arbEitherNum, opt => is(opt, opt) ) jv.property("self.hashCode() === self.hashCode() === hashCode(self)", inst.arbEitherNum, opt => opt.hashCode() === opt.hashCode() && opt.hashCode() === hashCode(opt) ) jv.property("Either.right(v).hashCode() === Either.right(v).hashCode()", jv.number, n => Either.right(n).hashCode() === Either.right(n).hashCode() ) jv.property("Either.left(v).hashCode() === Either.left(v).hashCode()", jv.number, n => Either.left(n).hashCode() === Either.left(n).hashCode() ) it("should have structural equality", () => { const opt1 = Either.right("hello1") const opt2 = Either.right("hello1") const opt3 = Either.right("hello2") assert.equal(opt1, opt2) assert.equal(opt2, opt1) assert.notEqual(opt1, opt3) assert.notEqual(opt3, opt1) assert.equal(Either.right(opt1), Either.right(opt2)) assert.notEqual(Either.right(opt1), Either.right(opt3)) assert.notEqual(Either.right<any,any>(opt1), Either.left(1)) }) jv.property("protects against other ref being null", inst.arbEitherNum, fa => fa.equals(null as any) === false ) }) describe("Either #forEach", () => { it("works for right", () => { let effect = 0 Right(10).forEach(() => effect = 10) assert.equal(effect, 10) }) it("does nothing for left", () => { let effect = 0 Left(10).forEach(() => effect = 10) assert.equal(effect, 0) }) }) describe("Either map2, map3, map4, map5, map6", () => { jv.property("map2 equivalence with flatMap", inst.arbEitherNum, inst.arbEitherNum, jv.fn(jv.number), (o1, o2, fn) => { const f = (...args: any[]) => fn(args) return is(Either.map2(o1, o2, f), o1.flatMap(a1 => o2.map(a2 => f(a1, a2)))) } ) jv.property("map3 equivalence with flatMap", inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, jv.fn(jv.number), (o1, o2, o3, fn) => { const f = (...args: any[]) => fn(args) return is( Either.map3(o1, o2, o3, f), o1.flatMap(a1 => o2.flatMap(a2 => o3.map(a3 => f(a1, a2, a3)))) ) } ) jv.property("map4 equivalence with flatMap", inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, jv.fn(jv.number), (o1, o2, o3, o4, fn) => { const f = (...args: any[]) => fn(args) return is( Either.map4(o1, o2, o3, o4, f), o1.flatMap(a1 => o2.flatMap(a2 => o3.flatMap(a3 => o4.map(a4 => f(a1, a2, a3, a4))))) ) } ) jv.property("map5 equivalence with flatMap", inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, jv.fn(jv.number), (o1, o2, o3, o4, o5, fn) => { const f = (...args: any[]) => fn(args) return is( Either.map5(o1, o2, o3, o4, o5, f), o1.flatMap(a1 => o2.flatMap(a2 => o3.flatMap(a3 => o4.flatMap(a4 => o5.map(a5 => f(a1, a2, a3, a4, a5)))))) ) } ) jv.property("map6 equivalence with flatMap", inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, inst.arbEitherNum, jv.fn(jv.number), (o1, o2, o3, o4, o5, o6, fn) => { const f = (...args: any[]) => fn(args) return is( Either.map6(o1, o2, o3, o4, o5, o6, f), o1.flatMap(a1 => o2.flatMap(a2 => o3.flatMap(a3 => o4.flatMap(a4 => o5.flatMap(a5 => o6.map(a6 => f(a1, a2, a3, a4, a5, a6))))))) ) } ) }) describe("Either.tailRecM", () => { it("is stack safe", () => { const fa = Either.tailRecM(0, a => Right(a < 1000 ? Left(a + 1) : Right(a))) assert.equal(fa.get(), 1000) }) it("Left interrupts the loop", () => { const fa = Either.tailRecM(0, a => Left("value")) assert.equal(fa.swap().get(), "value") }) }) describe("Setoid<Either> (static-land)", () => { setoidCheck(inst.arbEitherNum, EitherModule) it("protects against null", () => { assert.ok(EitherModule.equals(null as any, null as any)) assert.not(EitherModule.equals(null as any, Either.right(1))) assert.not(EitherModule.equals(Either.right(1), null as any)) }) }) describe("Setoid<Either> (fantasy-land)", () => { setoidCheck(inst.arbEitherNum, { equals: (x, y) => (x as any)["fantasy-land/equals"](y) }) }) describe("Monad<Either> (static-land)", () => { const check = (e: Equiv<HK<"funfix/either", any>>) => (e.lh as Either<any, any>).equals(e.rh as Either<any, any>) const arbFA = inst.arbEither(jv.int32) const arbFB = inst.arbEither(jv.string) const arbFC = inst.arbEither(jv.int16) const arbFAtoB = inst.arbEither(jv.fun(jv.string)) const arbFBtoC = inst.arbEither(jv.fun(jv.int16)) monadCheck( arbFA, arbFB, arbFC, jv.fun(jv.string), jv.fun(jv.int16), arbFAtoB, arbFBtoC, jv.int32, check, EitherModule) }) describe("Monad<Either> (fantasy-land)", () => { const check = (e: Equiv<HK<"funfix/either", any>>) => (e.lh as Either<any, any>).equals(e.rh as Either<any, any>) const arbFA = inst.arbEither(jv.int32) const arbFB = inst.arbEither(jv.string) const arbFC = inst.arbEither(jv.int16) const arbFAtoB = inst.arbEither(jv.fun(jv.string)) const arbFBtoC = inst.arbEither(jv.fun(jv.int16)) monadCheck( arbFA, arbFB, arbFC, jv.fun(jv.string), jv.fun(jv.int16), arbFAtoB, arbFBtoC, jv.int32, check, { map: (f, fa) => (fa as any)["fantasy-land/map"](f), ap: (ff, fa) => (fa as any)["fantasy-land/ap"](ff), chain: (f, fa) => (fa as any)["fantasy-land/chain"](f), chainRec: (f, a) => (Either as any)["fantasy-land/chainRec"](f, a), of: a => (Either as any)["fantasy-land/of"](a) }) }) })
the_stack
export default class Sprite { width: number; height: number; all: any = {}; backup: any = []; backup_position: number; copy_sprite: any = {}; sprite_name_counter: number; constructor(public config) { this.config = config; this.width = config.sprite_x; this.height = config.sprite_y; this.all = {}; this.all.version = this.config.version; // current version number this.all.colors = { 0: 11, 2: 8, 3: 6 }; // 0 = transparent, 2 = mc1, 3 = mc2 this.all.sprites = []; this.all.current_sprite = 0; this.all.pen = 1; // can be individual = i, transparent = t, multicolor_1 = m1, multicolor_2 = m2 this.backup = []; this.backup_position = -1; this.copy_sprite = {}; this.sprite_name_counter = 0; // increments for every new sprite regardless of deleted sprites. Used for the default name } new_sprite(color = 1, multicolor = false): void { const sprite = { name: "sprite_" + this.sprite_name_counter, color: color, multicolor: multicolor, double_x: false, double_y: false, overlay: false, pixels: [], }; for (let i = 0; i < this.height; i++) { const line = [] as any; for (let j = 0; j < this.width; j++) line.push(0); (sprite.pixels as any).push(line); } this.all.sprites.push(sprite); this.all.current_sprite = this.all.sprites.length - 1; this.sprite_name_counter++; if (!multicolor && this.is_pen_multicolor()) this.set_pen(1); this.save_backup(); } clear(): void { // fills the sprite data with the default color // generate a bitmap array const pixels = [] as any; for (let i = 0; i < this.height; i++) { const line = [] as any; for (let j = 0; j < this.width; j++) line.push(0); pixels.push(line); } this.all.sprites[this.all.current_sprite].pixels = pixels; this.save_backup(); } fill(): void { // fills the sprite data with the default color // generate a bitmap array const pixels = [] as any; for (let i = 0; i < this.height; i++) { const line = [] as any; for (let j = 0; j < this.width; j++) line.push(this.all.pen); pixels.push(line); } this.all.sprites[this.all.current_sprite].pixels = pixels; this.save_backup(); } flip_vertical(): void { this.all.sprites[this.all.current_sprite].pixels.reverse(); this.save_backup(); } flip_horizontal(): void { const s = this.all.sprites[this.all.current_sprite]; for (let i = 0; i < this.height; i++) s.pixels[i].reverse(); if (s.multicolor) { for (let i = 0; i < this.height; i++) s.pixels[i].push(s.pixels[i].shift()); } this.all.sprites[this.all.current_sprite] = s; this.save_backup(); } shift_vertical(direction: string): void { const s = this.all.sprites[this.all.current_sprite]; if (direction == "down") { s.pixels.unshift(s.pixels.pop()); } else { s.pixels.push(s.pixels.shift()); } this.all.sprites[this.all.current_sprite] = s; this.save_backup(); } shift_horizontal(direction: string): void { const s = this.all.sprites[this.all.current_sprite]; for (let i = 0; i < this.height; i++) { if (direction == "right") { if (s.multicolor) { s.pixels[i].unshift(s.pixels[i].pop()); s.pixels[i].unshift(s.pixels[i].pop()); } else { s.pixels[i].unshift(s.pixels[i].pop()); } } else { if (s.multicolor) { s.pixels[i].push(s.pixels[i].shift()); s.pixels[i].push(s.pixels[i].shift()); } else { s.pixels[i].push(s.pixels[i].shift()); } } } this.all.sprites[this.all.current_sprite] = s; this.save_backup(); } get_colors() { // used to update the palette with the right colors const sprite_colors = { 0: this.all.colors[0], 1: this.all.sprites[this.all.current_sprite].color, 2: this.all.colors[2], 3: this.all.colors[3], }; return sprite_colors; } get_name(): string { return this.all.sprites[this.all.current_sprite].name; } is_multicolor(): boolean { return this.all.sprites[this.all.current_sprite].multicolor; } toggle_double_x(): void { this.all.sprites[this.all.current_sprite].double_x = !this.all.sprites[ this.all.current_sprite ].double_x; this.save_backup(); } toggle_double_y(): void { this.all.sprites[this.all.current_sprite].double_y = !this.all.sprites[ this.all.current_sprite ].double_y; this.save_backup(); } toggle_multicolor(): void { if (this.all.sprites[this.all.current_sprite].multicolor) { this.all.sprites[this.all.current_sprite].multicolor = false; if (this.is_pen_multicolor()) this.set_pen(1); } else { this.all.sprites[this.all.current_sprite].multicolor = true; } this.save_backup(); } set_pixel(pos, shiftkey): void { // writes a pixel to the sprite pixel array // multicolor check if (this.all.sprites[this.all.current_sprite].multicolor && pos.x % 2 !== 0) pos.x = pos.x - 1; if (!shiftkey) { // draw with selected pen this.all.sprites[this.all.current_sprite].pixels[pos.y][ pos.x ] = this.all.pen; } else { // shift is hold down, so we delete with transparent color this.all.sprites[this.all.current_sprite].pixels[pos.y][pos.x] = 0; } } get_current_sprite() { return this.all.sprites[this.all.current_sprite]; } get_current_sprite_number(): number { return this.all.current_sprite; } get_number_of_sprites(): number { return this.all.sprites.length; } only_one_sprite(): boolean { return this.all.sprites.length == 1 ? true : false; } get_pen() { return this.all.pen; } is_pen_multicolor(): boolean { return this.all.pen === 2 || this.all.pen === 3; } set_pen(pen): void { this.all.pen = pen; } set_pen_color(pencolor): void { if (this.all.pen == 1) { this.all.sprites[this.all.current_sprite].color = pencolor; } else { this.all.colors[this.all.pen] = pencolor; } this.save_backup(); } get_all() { return this.all; } set_all(all): void { this.all = all; this.save_backup(); } sort_spritelist(sprite_order_from_dom): void { const sorted_list = sprite_order_from_dom.map(function (x) { return parseInt(x); }); const new_sprite_list = [] as any; let temp_current_sprite = 0; for (let i = 0; i < sorted_list.length; i++) { new_sprite_list.push(this.all.sprites[sorted_list[i]]); if (sorted_list[i] == this.all.current_sprite) temp_current_sprite = i; } this.all.sprites = new_sprite_list; this.all.current_sprite = temp_current_sprite; this.save_backup(); } set_current_sprite(spritenumber: string | number): void { if (spritenumber == "right") spritenumber = this.all.current_sprite + 1; if (spritenumber == "left") spritenumber = this.all.current_sprite - 1; // cycle through the list if (spritenumber < 0) spritenumber = this.all.sprites.length - 1; if (spritenumber > this.all.sprites.length - 1) spritenumber = 0; if (typeof spritenumber == "number") this.all.current_sprite = spritenumber; this.save_backup(); } delete(): void { if (this.all.sprites.length > 1) { this.all.sprites.splice(this.all.current_sprite, 1); if (this.all.current_sprite == this.all.sprites.length) this.all.current_sprite--; this.save_backup(); } } save_backup(): void { this.backup_position++; this.backup[this.backup_position] = JSON.parse(JSON.stringify(this.all)); //$.extend(true, {}, this.all); } undo(): void { if (this.backup_position > 0) { this.backup_position--; this.all = JSON.parse(JSON.stringify(this.backup[this.backup_position])); // $.extend(true, {}, this.backup[this.backup_position]); } } redo(): void { if (this.backup_position < this.backup.length - 1) { this.backup_position++; this.all = JSON.parse(JSON.stringify(this.backup[this.backup_position])); // $.extend(true, {}, this.backup[this.backup_position]); } } floodfill(pos): void { // https://stackoverflow.com/questions/22053759/multidimensional-array-fill // get target value let x = pos.x; const y = pos.y; const data = this.all.sprites[this.all.current_sprite].pixels; // multicolor check let stepping = 1; const is_multi = this.all.sprites[this.all.current_sprite].multicolor; if (is_multi) stepping = 2; if (is_multi && x % 2 !== 0) x = x - 1; const target = data[y][x]; function flow(x, y, pen) { // bounds check what we were passed if (y >= 0 && y < data.length && x >= 0 && x < data[y].length) { if (is_multi && x % 2 !== 0) x = x - 1; if (data[y][x] === target && data[y][x] != pen) { data[y][x] = pen; flow(x - stepping, y, pen); // check up flow(x + stepping, y, pen); // check down flow(x, y - 1, pen); // check left flow(x, y + 1, pen); // check right } } } flow(x, y, this.all.pen); this.all.sprites[this.all.current_sprite].pixels = data; } is_copy_empty(): boolean { return Object.keys(this.copy_sprite).length === 0; } copy(): void { this.copy_sprite = JSON.parse( JSON.stringify(this.all.sprites[this.all.current_sprite]) ); //$.extend(true,{},this.all.sprites[this.all.current_sprite]); } paste(): void { this.all.sprites[this.all.current_sprite] = JSON.parse( JSON.stringify(this.copy_sprite) ); //$.extend(true,{},this.copy_sprite); this.save_backup(); } duplicate(): void { this.copy(); this.new_sprite(); this.paste(); } can_undo(): boolean { return this.backup_position > 0; } can_redo(): boolean { return this.backup_position < this.backup.length - 1; } toggle_overlay(): void { this.all.sprites[this.all.current_sprite].overlay = !this.all.sprites[ this.all.current_sprite ].overlay; } is_overlay(): boolean { return this.all.sprites[this.all.current_sprite].overlay; } is_double_x(): boolean { return this.all.sprites[this.all.current_sprite].double_x; } is_double_y(): boolean { return this.all.sprites[this.all.current_sprite].double_y; } set_sprite_name(sprite_name: string): void { this.all.sprites[this.all.current_sprite].name = sprite_name; } invert(): void { // inverts the sprite // prevent too much data to be inverted in multicolor mode let stepping: number; if (this.is_multicolor()) { stepping = 1; } else { stepping = 1; } for (let y = 0; y < this.height; y++) { for (let x = 0; x < this.width; x = x + stepping) { const pixel = this.all.sprites[this.all.current_sprite].pixels[y][x]; let pixel_inverted; if (pixel == 0) pixel_inverted = 1; if (pixel == 1) pixel_inverted = 0; if (pixel == 2) pixel_inverted = 3; if (pixel == 3) pixel_inverted = 2; this.all.sprites[this.all.current_sprite].pixels[y][x] = pixel_inverted; } } this.save_backup(); } }
the_stack
import { ApplicationDataListResponse, ErrorResponse, ApplicationData, AttachmentListResponse, Attachment, BoundaryListResponse, CascadeDeleteJob, Boundary, BoundaryOverlapResponse, CropListResponse, Crop, CropVarietyListResponse, CropVariety, FarmerListResponse, Farmer, FarmOperationDataIngestionJob, FarmListResponse, Farm, FieldListResponse, Field, HarvestDataListResponse, HarvestData, ImageProcessingRasterizeJob, OAuthProviderListResponse, OAuthProvider, OAuthTokenListResponse, PlantingDataListResponse, PlantingData, SceneListResponse, SatelliteDataIngestionJob, SeasonalFieldListResponse, SeasonalField, SeasonListResponse, Season, TillageDataListResponse, TillageData, WeatherDataListResponse, WeatherDataIngestionJob, WeatherDataDeleteJob, } from "./models"; import { HttpResponse } from "@azure-rest/core-client"; /** Returns a paginated list of application data resources under a particular farm. */ export interface ApplicationDataListByFarmerId200Response extends HttpResponse { status: "200"; body: ApplicationDataListResponse; } /** Returns a paginated list of application data resources under a particular farm. */ export interface ApplicationDataListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of application data resources across all farmers. */ export interface ApplicationDataList200Response extends HttpResponse { status: "200"; body: ApplicationDataListResponse; } /** Returns a paginated list of application data resources across all farmers. */ export interface ApplicationDataListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a specified application data resource under a particular farmer. */ export interface ApplicationDataGet200Response extends HttpResponse { status: "200"; body: ApplicationData; } /** Get a specified application data resource under a particular farmer. */ export interface ApplicationDataGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates an application data resource under a particular farmer. */ export interface ApplicationDataCreateOrUpdate200Response extends HttpResponse { status: "200"; body: ApplicationData; } /** Creates or updates an application data resource under a particular farmer. */ export interface ApplicationDataCreateOrUpdate201Response extends HttpResponse { status: "201"; body: ApplicationData; } /** Creates or updates an application data resource under a particular farmer. */ export interface ApplicationDataCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified application data resource under a particular farmer. */ export interface ApplicationDataDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified application data resource under a particular farmer. */ export interface ApplicationDataDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of attachment resources under a particular farmer. */ export interface AttachmentsListByFarmerId200Response extends HttpResponse { status: "200"; body: AttachmentListResponse; } /** Returns a paginated list of attachment resources under a particular farmer. */ export interface AttachmentsListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified attachment resource under a particular farmer. */ export interface AttachmentsGet200Response extends HttpResponse { status: "200"; body: Attachment; } /** Gets a specified attachment resource under a particular farmer. */ export interface AttachmentsGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates an attachment resource under a particular farmer. */ export interface AttachmentsCreateOrUpdate200Response extends HttpResponse { status: "200"; body: Attachment; } /** Creates or updates an attachment resource under a particular farmer. */ export interface AttachmentsCreateOrUpdate201Response extends HttpResponse { status: "201"; body: Attachment; } /** Creates or updates an attachment resource under a particular farmer. */ export interface AttachmentsCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified attachment resource under a particular farmer. */ export interface AttachmentsDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified attachment resource under a particular farmer. */ export interface AttachmentsDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Downloads and returns attachment as response for the given input filePath. */ export interface AttachmentsDownload200Response extends HttpResponse { status: "200"; } /** Downloads and returns attachment as response for the given input filePath. */ export interface AttachmentsDownloaddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of boundary resources under a particular farmer. */ export interface BoundariesListByFarmerId200Response extends HttpResponse { status: "200"; body: BoundaryListResponse; } /** Returns a paginated list of boundary resources under a particular farmer. */ export interface BoundariesListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Search for boundaries by fields and intersecting geometry. */ export interface BoundariesSearchByFarmerId200Response extends HttpResponse { status: "200"; body: BoundaryListResponse; } /** Search for boundaries by fields and intersecting geometry. */ export interface BoundariesSearchByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of boundary resources across all farmers. */ export interface BoundariesList200Response extends HttpResponse { status: "200"; body: BoundaryListResponse; } /** Returns a paginated list of boundary resources across all farmers. */ export interface BoundariesListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Search for boundaries across all farmers by fields and intersecting geometry. */ export interface BoundariesSearch200Response extends HttpResponse { status: "200"; body: BoundaryListResponse; } /** Search for boundaries across all farmers by fields and intersecting geometry. */ export interface BoundariesSearchdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get cascade delete job for specified boundary. */ export interface BoundariesGetCascadeDeleteJobDetails200Response extends HttpResponse { status: "200"; body: CascadeDeleteJob; } /** Get cascade delete job for specified boundary. */ export interface BoundariesGetCascadeDeleteJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a cascade delete job for specified boundary. */ export interface BoundariesCreateCascadeDeleteJob202Response extends HttpResponse { status: "202"; body: CascadeDeleteJob; } /** Create a cascade delete job for specified boundary. */ export interface BoundariesCreateCascadeDeleteJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified boundary resource under a particular farmer. */ export interface BoundariesGet200Response extends HttpResponse { status: "200"; body: Boundary; } /** Gets a specified boundary resource under a particular farmer. */ export interface BoundariesGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates a boundary resource. */ export interface BoundariesCreateOrUpdate200Response extends HttpResponse { status: "200"; body: Boundary; } /** Creates or updates a boundary resource. */ export interface BoundariesCreateOrUpdate201Response extends HttpResponse { status: "201"; body: Boundary; } /** Creates or updates a boundary resource. */ export interface BoundariesCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified boundary resource under a particular farmer. */ export interface BoundariesDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified boundary resource under a particular farmer. */ export interface BoundariesDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns overlapping acreage between two boundary Ids. */ export interface BoundariesGetOverlap200Response extends HttpResponse { status: "200"; body: BoundaryOverlapResponse; } /** Returns overlapping acreage between two boundary Ids. */ export interface BoundariesGetOverlapdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of crop resources. */ export interface CropsList200Response extends HttpResponse { status: "200"; body: CropListResponse; } /** Returns a paginated list of crop resources. */ export interface CropsListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified crop resource. */ export interface CropsGet200Response extends HttpResponse { status: "200"; body: Crop; } /** Gets a specified crop resource. */ export interface CropsGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates a crop resource. */ export interface CropsCreateOrUpdate200Response extends HttpResponse { status: "200"; body: Crop; } /** Creates or updates a crop resource. */ export interface CropsCreateOrUpdate201Response extends HttpResponse { status: "201"; body: Crop; } /** Creates or updates a crop resource. */ export interface CropsCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes Crop for given crop id. */ export interface CropsDelete204Response extends HttpResponse { status: "204"; } /** Deletes Crop for given crop id. */ export interface CropsDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of crop variety resources under a particular crop. */ export interface CropVarietiesListByCropId200Response extends HttpResponse { status: "200"; body: CropVarietyListResponse; } /** Returns a paginated list of crop variety resources under a particular crop. */ export interface CropVarietiesListByCropIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of crop variety resources across all crops. */ export interface CropVarietiesList200Response extends HttpResponse { status: "200"; body: CropVarietyListResponse; } /** Returns a paginated list of crop variety resources across all crops. */ export interface CropVarietiesListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified crop variety resource under a particular crop. */ export interface CropVarietiesGet200Response extends HttpResponse { status: "200"; body: CropVariety; } /** Gets a specified crop variety resource under a particular crop. */ export interface CropVarietiesGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates a crop variety resource. */ export interface CropVarietiesCreateOrUpdate200Response extends HttpResponse { status: "200"; body: CropVariety; } /** Creates or updates a crop variety resource. */ export interface CropVarietiesCreateOrUpdate201Response extends HttpResponse { status: "201"; body: CropVariety; } /** Creates or updates a crop variety resource. */ export interface CropVarietiesCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified crop variety resource under a particular crop. */ export interface CropVarietiesDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified crop variety resource under a particular crop. */ export interface CropVarietiesDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of farmer resources. */ export interface FarmersList200Response extends HttpResponse { status: "200"; body: FarmerListResponse; } /** Returns a paginated list of farmer resources. */ export interface FarmersListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified farmer resource. */ export interface FarmersGet200Response extends HttpResponse { status: "200"; body: Farmer; } /** Gets a specified farmer resource. */ export interface FarmersGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates a farmer resource. */ export interface FarmersCreateOrUpdate200Response extends HttpResponse { status: "200"; body: Farmer; } /** Creates or updates a farmer resource. */ export interface FarmersCreateOrUpdate201Response extends HttpResponse { status: "201"; body: Farmer; } /** Creates or updates a farmer resource. */ export interface FarmersCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified farmer resource. */ export interface FarmersDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified farmer resource. */ export interface FarmersDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a cascade delete job for specified farmer. */ export interface FarmersGetCascadeDeleteJobDetails200Response extends HttpResponse { status: "200"; body: CascadeDeleteJob; } /** Get a cascade delete job for specified farmer. */ export interface FarmersGetCascadeDeleteJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a cascade delete job for specified farmer. */ export interface FarmersCreateCascadeDeleteJob202Response extends HttpResponse { status: "202"; body: CascadeDeleteJob; } /** Create a cascade delete job for specified farmer. */ export interface FarmersCreateCascadeDeleteJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a farm operation data ingestion job. */ export interface FarmOperationsCreateDataIngestionJob202Response extends HttpResponse { status: "202"; body: FarmOperationDataIngestionJob; } /** Create a farm operation data ingestion job. */ export interface FarmOperationsCreateDataIngestionJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a farm operation data ingestion job. */ export interface FarmOperationsGetDataIngestionJobDetails200Response extends HttpResponse { status: "200"; body: FarmOperationDataIngestionJob; } /** Get a farm operation data ingestion job. */ export interface FarmOperationsGetDataIngestionJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of farm resources under a particular farmer. */ export interface FarmsListByFarmerId200Response extends HttpResponse { status: "200"; body: FarmListResponse; } /** Returns a paginated list of farm resources under a particular farmer. */ export interface FarmsListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of farm resources across all farmers. */ export interface FarmsList200Response extends HttpResponse { status: "200"; body: FarmListResponse; } /** Returns a paginated list of farm resources across all farmers. */ export interface FarmsListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified farm resource under a particular farmer. */ export interface FarmsGet200Response extends HttpResponse { status: "200"; body: Farm; } /** Gets a specified farm resource under a particular farmer. */ export interface FarmsGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates a farm resource under a particular farmer. */ export interface FarmsCreateOrUpdate200Response extends HttpResponse { status: "200"; body: Farm; } /** Creates or updates a farm resource under a particular farmer. */ export interface FarmsCreateOrUpdate201Response extends HttpResponse { status: "201"; body: Farm; } /** Creates or updates a farm resource under a particular farmer. */ export interface FarmsCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified farm resource under a particular farmer. */ export interface FarmsDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified farm resource under a particular farmer. */ export interface FarmsDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a cascade delete job for specified farm. */ export interface FarmsGetCascadeDeleteJobDetails200Response extends HttpResponse { status: "200"; body: CascadeDeleteJob; } /** Get a cascade delete job for specified farm. */ export interface FarmsGetCascadeDeleteJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a cascade delete job for specified farm. */ export interface FarmsCreateCascadeDeleteJob202Response extends HttpResponse { status: "202"; body: CascadeDeleteJob; } /** Create a cascade delete job for specified farm. */ export interface FarmsCreateCascadeDeleteJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of field resources under a particular farmer. */ export interface FieldsListByFarmerId200Response extends HttpResponse { status: "200"; body: FieldListResponse; } /** Returns a paginated list of field resources under a particular farmer. */ export interface FieldsListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of field resources across all farmers. */ export interface FieldsList200Response extends HttpResponse { status: "200"; body: FieldListResponse; } /** Returns a paginated list of field resources across all farmers. */ export interface FieldsListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified field resource under a particular farmer. */ export interface FieldsGet200Response extends HttpResponse { status: "200"; body: Field; } /** Gets a specified field resource under a particular farmer. */ export interface FieldsGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or Updates a field resource under a particular farmer. */ export interface FieldsCreateOrUpdate200Response extends HttpResponse { status: "200"; body: Field; } /** Creates or Updates a field resource under a particular farmer. */ export interface FieldsCreateOrUpdate201Response extends HttpResponse { status: "201"; body: Field; } /** Creates or Updates a field resource under a particular farmer. */ export interface FieldsCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified field resource under a particular farmer. */ export interface FieldsDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified field resource under a particular farmer. */ export interface FieldsDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a cascade delete job for specified field. */ export interface FieldsGetCascadeDeleteJobDetails200Response extends HttpResponse { status: "200"; body: CascadeDeleteJob; } /** Get a cascade delete job for specified field. */ export interface FieldsGetCascadeDeleteJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a cascade delete job for specified field. */ export interface FieldsCreateCascadeDeleteJob202Response extends HttpResponse { status: "202"; body: CascadeDeleteJob; } /** Create a cascade delete job for specified field. */ export interface FieldsCreateCascadeDeleteJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of harvest data resources under a particular farm. */ export interface HarvestDataListByFarmerId200Response extends HttpResponse { status: "200"; body: HarvestDataListResponse; } /** Returns a paginated list of harvest data resources under a particular farm. */ export interface HarvestDataListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of harvest data resources across all farmers. */ export interface HarvestDataList200Response extends HttpResponse { status: "200"; body: HarvestDataListResponse; } /** Returns a paginated list of harvest data resources across all farmers. */ export interface HarvestDataListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a specified harvest data resource under a particular farmer. */ export interface HarvestDataGet200Response extends HttpResponse { status: "200"; body: HarvestData; } /** Get a specified harvest data resource under a particular farmer. */ export interface HarvestDataGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates harvest data resource under a particular farmer. */ export interface HarvestDataCreateOrUpdate200Response extends HttpResponse { status: "200"; body: HarvestData; } /** Creates or updates harvest data resource under a particular farmer. */ export interface HarvestDataCreateOrUpdate201Response extends HttpResponse { status: "201"; body: HarvestData; } /** Creates or updates harvest data resource under a particular farmer. */ export interface HarvestDataCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified harvest data resource under a particular farmer. */ export interface HarvestDataDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified harvest data resource under a particular farmer. */ export interface HarvestDataDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a ImageProcessing Rasterize job. */ export interface ImageProcessingCreateRasterizeJob202Response extends HttpResponse { status: "202"; body: ImageProcessingRasterizeJob; } /** Create a ImageProcessing Rasterize job. */ export interface ImageProcessingCreateRasterizeJobdefaultResponse extends HttpResponse { status: "500"; } /** Get ImageProcessing Rasterize job's details. */ export interface ImageProcessingGetRasterizeJob200Response extends HttpResponse { status: "200"; body: ImageProcessingRasterizeJob; } /** Returns a paginated list of oauthProvider resources. */ export interface OAuthProvidersList200Response extends HttpResponse { status: "200"; body: OAuthProviderListResponse; } /** Returns a paginated list of oauthProvider resources. */ export interface OAuthProvidersListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a specified oauthProvider resource. */ export interface OAuthProvidersGet200Response extends HttpResponse { status: "200"; body: OAuthProvider; } /** Get a specified oauthProvider resource. */ export interface OAuthProvidersGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates an oauthProvider resource. */ export interface OAuthProvidersCreateOrUpdate200Response extends HttpResponse { status: "200"; body: OAuthProvider; } /** Creates or updates an oauthProvider resource. */ export interface OAuthProvidersCreateOrUpdate201Response extends HttpResponse { status: "201"; body: OAuthProvider; } /** Creates or updates an oauthProvider resource. */ export interface OAuthProvidersCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes an specified oauthProvider resource. */ export interface OAuthProvidersDelete204Response extends HttpResponse { status: "204"; } /** Deletes an specified oauthProvider resource. */ export interface OAuthProvidersDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a list of OAuthToken documents. */ export interface OAuthTokensList200Response extends HttpResponse { status: "200"; body: OAuthTokenListResponse; } /** Returns a list of OAuthToken documents. */ export interface OAuthTokensListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns Connection link needed in the OAuth flow. */ export interface OAuthTokensGetOAuthConnectionLink200Response extends HttpResponse { status: "200"; body: string; } /** Returns Connection link needed in the OAuth flow. */ export interface OAuthTokensGetOAuthConnectionLinkdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get cascade delete job details for OAuth tokens for specified job ID. */ export interface OAuthTokensGetCascadeDeleteJobDetails200Response extends HttpResponse { status: "200"; body: CascadeDeleteJob; } /** Get cascade delete job details for OAuth tokens for specified job ID. */ export interface OAuthTokensGetCascadeDeleteJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a cascade delete job for OAuth tokens. */ export interface OAuthTokensCreateCascadeDeleteJob202Response extends HttpResponse { status: "202"; body: CascadeDeleteJob; } /** Create a cascade delete job for OAuth tokens. */ export interface OAuthTokensCreateCascadeDeleteJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of planting data resources under a particular farm. */ export interface PlantingDataListByFarmerId200Response extends HttpResponse { status: "200"; body: PlantingDataListResponse; } /** Returns a paginated list of planting data resources under a particular farm. */ export interface PlantingDataListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of planting data resources across all farmers. */ export interface PlantingDataList200Response extends HttpResponse { status: "200"; body: PlantingDataListResponse; } /** Returns a paginated list of planting data resources across all farmers. */ export interface PlantingDataListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a specified planting data resource under a particular farmer. */ export interface PlantingDataGet200Response extends HttpResponse { status: "200"; body: PlantingData; } /** Get a specified planting data resource under a particular farmer. */ export interface PlantingDataGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates an planting data resource under a particular farmer. */ export interface PlantingDataCreateOrUpdate200Response extends HttpResponse { status: "200"; body: PlantingData; } /** Creates or updates an planting data resource under a particular farmer. */ export interface PlantingDataCreateOrUpdate201Response extends HttpResponse { status: "201"; body: PlantingData; } /** Creates or updates an planting data resource under a particular farmer. */ export interface PlantingDataCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified planting data resource under a particular farmer. */ export interface PlantingDataDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified planting data resource under a particular farmer. */ export interface PlantingDataDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of scene resources. */ export interface ScenesList200Response extends HttpResponse { status: "200"; body: SceneListResponse; } /** Returns a paginated list of scene resources. */ export interface ScenesListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a satellite data ingestion job. */ export interface ScenesCreateSatelliteDataIngestionJob202Response extends HttpResponse { status: "202"; body: SatelliteDataIngestionJob; } /** Create a satellite data ingestion job. */ export interface ScenesCreateSatelliteDataIngestionJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a satellite data ingestion job. */ export interface ScenesGetSatelliteDataIngestionJobDetails200Response extends HttpResponse { status: "200"; body: SatelliteDataIngestionJob; } /** Get a satellite data ingestion job. */ export interface ScenesGetSatelliteDataIngestionJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Downloads and returns file stream as response for the given input filePath. */ export interface ScenesDownload200Response extends HttpResponse { status: "200"; } /** Downloads and returns file stream as response for the given input filePath. */ export interface ScenesDownloaddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of seasonal field resources under a particular farmer. */ export interface SeasonalFieldsListByFarmerId200Response extends HttpResponse { status: "200"; body: SeasonalFieldListResponse; } /** Returns a paginated list of seasonal field resources under a particular farmer. */ export interface SeasonalFieldsListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of seasonal field resources across all farmers. */ export interface SeasonalFieldsList200Response extends HttpResponse { status: "200"; body: SeasonalFieldListResponse; } /** Returns a paginated list of seasonal field resources across all farmers. */ export interface SeasonalFieldsListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified seasonal field resource under a particular farmer. */ export interface SeasonalFieldsGet200Response extends HttpResponse { status: "200"; body: SeasonalField; } /** Gets a specified seasonal field resource under a particular farmer. */ export interface SeasonalFieldsGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or Updates a seasonal field resource under a particular farmer. */ export interface SeasonalFieldsCreateOrUpdate200Response extends HttpResponse { status: "200"; body: SeasonalField; } /** Creates or Updates a seasonal field resource under a particular farmer. */ export interface SeasonalFieldsCreateOrUpdate201Response extends HttpResponse { status: "201"; body: SeasonalField; } /** Creates or Updates a seasonal field resource under a particular farmer. */ export interface SeasonalFieldsCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified seasonal-field resource under a particular farmer. */ export interface SeasonalFieldsDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified seasonal-field resource under a particular farmer. */ export interface SeasonalFieldsDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get cascade delete job for specified seasonal field. */ export interface SeasonalFieldsGetCascadeDeleteJobDetails200Response extends HttpResponse { status: "200"; body: CascadeDeleteJob; } /** Get cascade delete job for specified seasonal field. */ export interface SeasonalFieldsGetCascadeDeleteJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a cascade delete job for specified seasonal field. */ export interface SeasonalFieldsCreateCascadeDeleteJob202Response extends HttpResponse { status: "202"; body: CascadeDeleteJob; } /** Create a cascade delete job for specified seasonal field. */ export interface SeasonalFieldsCreateCascadeDeleteJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of season resources. */ export interface SeasonsList200Response extends HttpResponse { status: "200"; body: SeasonListResponse; } /** Returns a paginated list of season resources. */ export interface SeasonsListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Gets a specified season resource. */ export interface SeasonsGet200Response extends HttpResponse { status: "200"; body: Season; } /** Gets a specified season resource. */ export interface SeasonsGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates a season resource. */ export interface SeasonsCreateOrUpdate200Response extends HttpResponse { status: "200"; body: Season; } /** Creates or updates a season resource. */ export interface SeasonsCreateOrUpdate201Response extends HttpResponse { status: "201"; body: Season; } /** Creates or updates a season resource. */ export interface SeasonsCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified season resource. */ export interface SeasonsDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified season resource. */ export interface SeasonsDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of tillage data resources under a particular farm. */ export interface TillageDataListByFarmerId200Response extends HttpResponse { status: "200"; body: TillageDataListResponse; } /** Returns a paginated list of tillage data resources under a particular farm. */ export interface TillageDataListByFarmerIddefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of tillage data resources across all farmers. */ export interface TillageDataList200Response extends HttpResponse { status: "200"; body: TillageDataListResponse; } /** Returns a paginated list of tillage data resources across all farmers. */ export interface TillageDataListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get a specified tillage data resource under a particular farmer. */ export interface TillageDataGet200Response extends HttpResponse { status: "200"; body: TillageData; } /** Get a specified tillage data resource under a particular farmer. */ export interface TillageDataGetdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Creates or updates an tillage data resource under a particular farmer. */ export interface TillageDataCreateOrUpdate200Response extends HttpResponse { status: "200"; body: TillageData; } /** Creates or updates an tillage data resource under a particular farmer. */ export interface TillageDataCreateOrUpdate201Response extends HttpResponse { status: "201"; body: TillageData; } /** Creates or updates an tillage data resource under a particular farmer. */ export interface TillageDataCreateOrUpdatedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Deletes a specified tillage data resource under a particular farmer. */ export interface TillageDataDelete204Response extends HttpResponse { status: "204"; } /** Deletes a specified tillage data resource under a particular farmer. */ export interface TillageDataDeletedefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Returns a paginated list of weather data. */ export interface WeatherList200Response extends HttpResponse { status: "200"; body: WeatherDataListResponse; } /** Returns a paginated list of weather data. */ export interface WeatherListdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get weather ingestion job. */ export interface WeatherGetDataIngestionJobDetails200Response extends HttpResponse { status: "200"; body: WeatherDataIngestionJob; } /** Get weather ingestion job. */ export interface WeatherGetDataIngestionJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a weather data ingestion job. */ export interface WeatherCreateDataIngestionJob202Response extends HttpResponse { status: "202"; body: WeatherDataIngestionJob; } /** Create a weather data ingestion job. */ export interface WeatherCreateDataIngestionJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Get weather data delete job. */ export interface WeatherGetDataDeleteJobDetails200Response extends HttpResponse { status: "200"; body: WeatherDataDeleteJob; } /** Get weather data delete job. */ export interface WeatherGetDataDeleteJobDetailsdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; } /** Create a weather data delete job. */ export interface WeatherCreateDataDeleteJob202Response extends HttpResponse { status: "202"; body: WeatherDataDeleteJob; } /** Create a weather data delete job. */ export interface WeatherCreateDataDeleteJobdefaultResponse extends HttpResponse { status: "500"; body: ErrorResponse; }
the_stack
import { Injectable } from '@angular/core'; import { CoreSites } from '@services/sites'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; import { CoreError } from '@classes/errors/error'; const ROOT_CACHE_KEY = 'CoreTag:'; /** * Service to handle tags. */ @Injectable({ providedIn: 'root' }) export class CoreTagProvider { static readonly SEARCH_LIMIT = 150; /** * Check whether tags are available in a certain site. * * @param siteId Site Id. If not defined, use current site. * @return Promise resolved with true if available, resolved with false otherwise. * @since 3.7 */ async areTagsAvailable(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); return this.areTagsAvailableInSite(site); } /** * Check whether tags are available in a certain site. * * @param site Site. If not defined, use current site. * @return True if available. * @since 3.7 */ areTagsAvailableInSite(site?: CoreSite): boolean { site = site || CoreSites.getCurrentSite(); return !!site && site.wsAvailable('core_tag_get_tagindex_per_area') && site.wsAvailable('core_tag_get_tag_cloud') && site.wsAvailable('core_tag_get_tag_collections') && !site.isFeatureDisabled('NoDelegate_CoreTag'); } /** * Fetch the tag cloud. * * @param collectionId Tag collection ID. * @param isStandard Whether to return only standard tags. * @param sort Sort order for display (id, name, rawname, count, flag, isstandard, tagcollid). * @param search Search string. * @param fromContextId Context ID where this tag cloud is displayed. * @param contextId Only retrieve tag instances in this context. * @param recursive Retrieve tag instances in the context and its children. * @param limit Maximum number of tags to retrieve. Defaults to SEARCH_LIMIT. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the tag cloud. * @since 3.7 */ async getTagCloud( collectionId: number = 0, isStandard: boolean = false, sort: string = 'name', search: string = '', fromContextId: number = 0, contextId: number = 0, recursive: boolean = true, limit?: number, siteId?: string, ): Promise<CoreTagCloud> { limit = limit || CoreTagProvider.SEARCH_LIMIT; const site = await CoreSites.getSite(siteId); const params: CoreTagGetTagCloudWSParams = { tagcollid: collectionId, isstandard: isStandard, limit, sort, search, fromctx: fromContextId, ctx: contextId, rec: recursive, }; const preSets: CoreSiteWSPreSets = { updateFrequency: CoreSite.FREQUENCY_SOMETIMES, cacheKey: this.getTagCloudKey(collectionId, isStandard, sort, search, fromContextId, contextId, recursive), getFromCache: search != '', // Try to get updated data when searching. }; return site.read('core_tag_get_tag_cloud', params, preSets); } /** * Fetch the tag collections. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the tag collections. * @since 3.7 */ async getTagCollections(siteId?: string): Promise<CoreTagCollection[]> { const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { updateFrequency: CoreSite.FREQUENCY_RARELY, cacheKey: this.getTagCollectionsKey(), }; const response: CoreTagCollections = await site.read('core_tag_get_tag_collections', null, preSets); if (!response || !response.collections) { throw new CoreError('Cannot fetch tag collections'); } return response.collections; } /** * Fetch the tag index. * * @param id Tag ID. * @param name Tag name. * @param collectionId Tag collection ID. * @param areaId Tag area ID. * @param fromContextId Context ID where the link was displayed. * @param contextId Context ID where to search for items. * @param recursive Search in the context and its children. * @param page Page number. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the tag index per area. * @since 3.7 */ async getTagIndexPerArea( id: number, name: string = '', collectionId: number = 0, areaId: number = 0, fromContextId: number = 0, contextId: number = 0, recursive: boolean = true, page: number = 0, siteId?: string, ): Promise<CoreTagIndex[]> { const site = await CoreSites.getSite(siteId); const params: CoreTagGetTagindexPerAreaWSParams = { tagindex: { id, tag: name, tc: collectionId, ta: areaId, excl: true, from: fromContextId, ctx: contextId, rec: recursive, page, }, }; const preSets: CoreSiteWSPreSets = { updateFrequency: CoreSite.FREQUENCY_OFTEN, cacheKey: this.getTagIndexPerAreaKey(id, name, collectionId, areaId, fromContextId, contextId, recursive), }; let response: CoreTagIndex[]; try { response = await site.read('core_tag_get_tagindex_per_area', params, preSets); } catch (error) { // Workaround for WS not passing parameter to error string. if (error && error.errorcode == 'notagsfound') { error.message = Translate.instant('core.tag.notagsfound', { $a: name || id || '' }); } throw error; } if (!response) { throw new CoreError('Cannot fetch tag index per area'); } return response; } /** * Invalidate tag cloud. * * @param collectionId Tag collection ID. * @param isStandard Whether to return only standard tags. * @param sort Sort order for display (id, name, rawname, count, flag, isstandard, tagcollid). * @param search Search string. * @param fromContextId Context ID where this tag cloud is displayed. * @param contextId Only retrieve tag instances in this context. * @param recursive Retrieve tag instances in the context and its children. * @return Promise resolved when the data is invalidated. */ async invalidateTagCloud( collectionId: number = 0, isStandard: boolean = false, sort: string = 'name', search: string = '', fromContextId: number = 0, contextId: number = 0, recursive: boolean = true, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const key = this.getTagCloudKey(collectionId, isStandard, sort, search, fromContextId, contextId, recursive); return site.invalidateWsCacheForKey(key); } /** * Invalidate tag collections. * * @return Promise resolved when the data is invalidated. */ async invalidateTagCollections(siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const key = this.getTagCollectionsKey(); return site.invalidateWsCacheForKey(key); } /** * Invalidate tag index. * * @param id Tag ID. * @param name Tag name. * @param collectionId Tag collection ID. * @param areaId Tag area ID. * @param fromContextId Context ID where the link was displayed. * @param contextId Context ID where to search for items. * @param recursive Search in the context and its children. * @return Promise resolved when the data is invalidated. */ async invalidateTagIndexPerArea( id: number, name: string = '', collectionId: number = 0, areaId: number = 0, fromContextId: number = 0, contextId: number = 0, recursive: boolean = true, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const key = this.getTagIndexPerAreaKey(id, name, collectionId, areaId, fromContextId, contextId, recursive); return site.invalidateWsCacheForKey(key); } /** * Get cache key for tag cloud. * * @param collectionId Tag collection ID. * @param isStandard Whether to return only standard tags. * @param sort Sort order for display (id, name, rawname, count, flag, isstandard, tagcollid). * @param search Search string. * @param fromContextId Context ID where this tag cloud is displayed. * @param contextId Only retrieve tag instances in this context. * @param recursive Retrieve tag instances in the context and it's children. * @return Cache key. */ protected getTagCloudKey( collectionId: number, isStandard: boolean, sort: string, search: string, fromContextId: number, contextId: number, recursive: boolean, ): string { return ROOT_CACHE_KEY + 'cloud:' + collectionId + ':' + (isStandard ? 1 : 0) + ':' + sort + ':' + search + ':' + fromContextId + ':' + contextId + ':' + (recursive ? 1 : 0); } /** * Get cache key for tag collections. * * @return Cache key. */ protected getTagCollectionsKey(): string { return ROOT_CACHE_KEY + 'collections'; } /** * Get cache key for tag index. * * @param id Tag ID. * @param name Tag name. * @param collectionId Tag collection ID. * @param areaId Tag area ID. * @param fromContextId Context ID where the link was displayed. * @param contextId Context ID where to search for items. * @param recursive Search in the context and its children. * @return Cache key. */ protected getTagIndexPerAreaKey( id: number, name: string, collectionId: number, areaId: number, fromContextId: number, contextId: number, recursive: boolean, ): string { return ROOT_CACHE_KEY + 'index:' + id + ':' + name + ':' + collectionId + ':' + areaId + ':' + fromContextId + ':' + contextId + ':' + (recursive ? 1 : 0); } } export const CoreTag = makeSingleton(CoreTagProvider); /** * Params of core_tag_get_tag_cloud WS. */ export type CoreTagGetTagCloudWSParams = { tagcollid?: number; // Tag collection id. isstandard?: boolean; // Whether to return only standard tags. limit?: number; // Maximum number of tags to retrieve. sort?: string; // Sort order for display (id, name, rawname, count, flag, isstandard, tagcollid). search?: string; // Search string. fromctx?: number; // Context id where this tag cloud is displayed. ctx?: number; // Only retrieve tag instances in this context. rec?: boolean; // Retrieve tag instances in the $ctx context and it's children. }; /** * Structure of a tag cloud returned by WS. */ export type CoreTagCloud = { tags: CoreTagCloudTag[]; tagscount: number; totalcount: number; }; /** * Structure of a tag cloud tag returned by WS. */ export type CoreTagCloudTag = { name: string; viewurl: string; flag: boolean; isstandard: boolean; count: number; size: number; }; /** * Structure of a tag collection returned by WS. */ export type CoreTagCollection = { id: number; // Collection id. name: string; // Collection name. isdefault: boolean; // Whether is the default collection. component: string; // Component the collection is related to. sortorder: number; // Collection ordering in the list. searchable: boolean; // Whether the tag collection is searchable. customurl: string; // Custom URL for the tag page instead of /tag/index.php. }; /** * Structure of tag collections returned by WS. */ export type CoreTagCollections = { collections: CoreTagCollection[]; warnings?: CoreWSExternalWarning[]; }; /** * Params of core_tag_get_tagindex_per_area WS. */ export type CoreTagGetTagindexPerAreaWSParams = { tagindex: { id?: number; // Tag id. tag?: string; // Tag name. tc?: number; // Tag collection id. ta?: number; // Tag area id. excl?: boolean; // Exlusive mode for this tag area. from?: number; // Context id where the link was displayed. ctx?: number; // Context id where to search for items. rec?: boolean; // Search in the context recursive. page?: number; // Page number (0-based). }; // Parameters. }; /** * Structure of a tag index returned by WS. */ export type CoreTagIndex = { tagid: number; ta: number; component: string; itemtype: string; nextpageurl: string; prevpageurl: string; exclusiveurl: string; exclusivetext: string; title: string; content: string; hascontent: number; anchor: string; }; /** * Structure of a tag item returned by WS. */ export type CoreTagItem = { id: number; // Tag id. name: string; // Tag name. rawname: string; // The raw, unnormalised name for the tag as entered by users. isstandard: boolean; // Whether this tag is standard. tagcollid: number; // Tag collection id. taginstanceid: number; // Tag instance id. taginstancecontextid: number; // Context the tag instance belongs to. itemid: number; // Id of the record tagged. ordering: number; // Tag ordering. flag: number; // Whether the tag is flagged as inappropriate. };
the_stack
import { RouteInfo, RouteManagerContext, StackContext, StackContextState, ViewItem, generateId, getConfig, } from '@ionic/react'; import React from 'react'; import { matchPath } from 'react-router-dom'; import { clonePageElement } from './clonePageElement'; interface StackManagerProps { routeInfo: RouteInfo; } interface StackManagerState {} const isViewVisible = (el: HTMLElement) => !el.classList.contains('ion-page-invisible') && !el.classList.contains('ion-page-hidden'); export class StackManager extends React.PureComponent<StackManagerProps, StackManagerState> { id: string; context!: React.ContextType<typeof RouteManagerContext>; ionRouterOutlet?: React.ReactElement; routerOutletElement: HTMLIonRouterOutletElement | undefined; stackContextValue: StackContextState = { registerIonPage: this.registerIonPage.bind(this), isInOutlet: () => true, }; private pendingPageTransition = false; constructor(props: StackManagerProps) { super(props); this.registerIonPage = this.registerIonPage.bind(this); this.transitionPage = this.transitionPage.bind(this); this.handlePageTransition = this.handlePageTransition.bind(this); this.id = generateId('routerOutlet'); } componentDidMount() { if (this.routerOutletElement) { this.setupRouterOutlet(this.routerOutletElement); // console.log(`SM Mount - ${this.routerOutletElement.id} (${this.id})`); this.handlePageTransition(this.props.routeInfo); } } componentDidUpdate(prevProps: StackManagerProps) { if (this.props.routeInfo.pathname !== prevProps.routeInfo.pathname || this.pendingPageTransition) { this.handlePageTransition(this.props.routeInfo); this.pendingPageTransition = false; } } componentWillUnmount() { // console.log(`SM UNMount - ${(this.routerOutletElement?.id as any).id} (${this.id})`); this.context.clearOutlet(this.id); } async handlePageTransition(routeInfo: RouteInfo) { if (!this.routerOutletElement || !this.routerOutletElement.commit) { /** * The route outlet has not mounted yet. We need to wait for it to render * before we can transition the page. * * Set a flag to indicate that we should transition the page after * the component has updated. */ this.pendingPageTransition = true; } else { let enteringViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id); let leavingViewItem = this.context.findLeavingViewItemByRouteInfo(routeInfo, this.id); if (!leavingViewItem && routeInfo.prevRouteLastPathname) { leavingViewItem = this.context.findViewItemByPathname( routeInfo.prevRouteLastPathname, this.id ); } // Check if leavingViewItem should be unmounted if (leavingViewItem) { if (routeInfo.routeAction === 'replace') { leavingViewItem.mount = false; } else if (!(routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'forward')) { if (routeInfo.routeDirection !== 'none' && enteringViewItem !== leavingViewItem) { leavingViewItem.mount = false; } } else if (routeInfo.routeOptions?.unmount) { leavingViewItem.mount = false; } } const enteringRoute = matchRoute( this.ionRouterOutlet?.props.children, routeInfo ) as React.ReactElement; if (enteringViewItem) { enteringViewItem.reactElement = enteringRoute; } else if (enteringRoute) { enteringViewItem = this.context.createViewItem(this.id, enteringRoute, routeInfo); this.context.addViewItem(enteringViewItem); } if (enteringViewItem && enteringViewItem.ionPageElement) { /** * If the entering view item is the same as the leaving view item, * then we don't need to transition. */ if (enteringViewItem === leavingViewItem) { /** * If the entering view item is the same as the leaving view item, * we are either transitioning using parameterized routes to the same view * or a parent router outlet is re-rendering as a result of React props changing. * * If the route data does not match the current path, the parent router outlet * is attempting to transition and we cancel the operation. */ if (enteringViewItem.routeData.match.url !== routeInfo.pathname) { return; } } /** * If there isn't a leaving view item, but the route info indicates * that the user has routed from a previous path, then we need * to find the leaving view item to transition between. */ if (!leavingViewItem && this.props.routeInfo.prevRouteLastPathname) { leavingViewItem = this.context.findViewItemByPathname(this.props.routeInfo.prevRouteLastPathname, this.id); } /** * If the entering view is already visible and the leaving view is not, the transition does not need to occur. */ if (isViewVisible(enteringViewItem.ionPageElement) && leavingViewItem !== undefined && !isViewVisible(leavingViewItem.ionPageElement!)) { return; } /** * The view should only be transitioned in the following cases: * 1. Performing a replace or pop action, such as a swipe to go back gesture * to animation the leaving view off the screen. * * 2. Navigating between top-level router outlets, such as /page-1 to /page-2; * or navigating within a nested outlet, such as /tabs/tab-1 to /tabs/tab-2. * * 3. The entering view is an ion-router-outlet containing a page * matching the current route and that hasn't already transitioned in. * * This should only happen when navigating directly to a nested router outlet * route or on an initial page load (i.e. refreshing). In cases when loading * /tabs/tab-1, we need to transition the /tabs page element into the view. */ this.transitionPage(routeInfo, enteringViewItem, leavingViewItem); } else if (leavingViewItem && !enteringRoute && !enteringViewItem) { // If we have a leavingView but no entering view/route, we are probably leaving to // another outlet, so hide this leavingView. We do it in a timeout to give time for a // transition to finish. // setTimeout(() => { if (leavingViewItem.ionPageElement) { leavingViewItem.ionPageElement.classList.add('ion-page-hidden'); leavingViewItem.ionPageElement.setAttribute('aria-hidden', 'true'); } // }, 250); } this.forceUpdate(); } } registerIonPage(page: HTMLElement, routeInfo: RouteInfo) { const foundView = this.context.findViewItemByRouteInfo(routeInfo, this.id); if (foundView) { foundView.ionPageElement = page; foundView.ionRoute = true; } this.handlePageTransition(routeInfo); } async setupRouterOutlet(routerOutlet: HTMLIonRouterOutletElement) { const canStart = () => { const config = getConfig(); const swipeEnabled = config && config.get('swipeBackEnabled', routerOutlet.mode === 'ios'); if (swipeEnabled) { return this.context.canGoBack(); } else { return false; } }; const onStart = () => { this.context.goBack(); }; routerOutlet.swipeHandler = { canStart, onStart, onEnd: (_shouldContinue) => true, }; } async transitionPage( routeInfo: RouteInfo, enteringViewItem: ViewItem, leavingViewItem?: ViewItem ) { const routerOutlet = this.routerOutletElement!; const direction = routeInfo.routeDirection === 'none' || routeInfo.routeDirection === 'root' ? undefined : routeInfo.routeDirection; if (enteringViewItem && enteringViewItem.ionPageElement && this.routerOutletElement) { if ( leavingViewItem && leavingViewItem.ionPageElement && enteringViewItem === leavingViewItem ) { // If a page is transitioning to another version of itself // we clone it so we can have an animation to show const match = matchComponent(leavingViewItem.reactElement, routeInfo.pathname, true); if (match) { const newLeavingElement = clonePageElement(leavingViewItem.ionPageElement.outerHTML); if (newLeavingElement) { this.routerOutletElement.appendChild(newLeavingElement); await runCommit(enteringViewItem.ionPageElement, newLeavingElement); this.routerOutletElement.removeChild(newLeavingElement); } } else { await runCommit(enteringViewItem.ionPageElement, undefined); } } else { await runCommit(enteringViewItem.ionPageElement, leavingViewItem?.ionPageElement); if (leavingViewItem && leavingViewItem.ionPageElement) { leavingViewItem.ionPageElement.classList.add('ion-page-hidden'); leavingViewItem.ionPageElement.setAttribute('aria-hidden', 'true'); } } } async function runCommit(enteringEl: HTMLElement, leavingEl?: HTMLElement) { enteringEl.classList.add('ion-page'); enteringEl.classList.add('ion-page-invisible'); await routerOutlet.commit(enteringEl, leavingEl, { deepWait: true, duration: direction === undefined ? 0 : undefined, direction: direction as any, showGoBack: !!routeInfo.pushedByRoute, progressAnimation: false, animationBuilder: routeInfo.routeAnimation, }); } } render() { const { children } = this.props; const ionRouterOutlet = React.Children.only(children) as React.ReactElement; this.ionRouterOutlet = ionRouterOutlet; const components = this.context.getChildrenToRender( this.id, this.ionRouterOutlet, this.props.routeInfo, () => { this.forceUpdate(); } ); return ( <StackContext.Provider value={this.stackContextValue}> {React.cloneElement( ionRouterOutlet as any, { ref: (node: HTMLIonRouterOutletElement) => { if (ionRouterOutlet.props.setRef) { ionRouterOutlet.props.setRef(node); } if (ionRouterOutlet.props.forwardedRef) { ionRouterOutlet.props.forwardedRef.current = node; } this.routerOutletElement = node; const { ref } = ionRouterOutlet as any; if (typeof ref === 'function') { ref(node); } }, }, components )} </StackContext.Provider> ); } static get contextType() { return RouteManagerContext; } } export default StackManager; function matchRoute(node: React.ReactNode, routeInfo: RouteInfo) { let matchedNode: React.ReactNode; React.Children.forEach(node as React.ReactElement, (child: React.ReactElement) => { const matchProps = { exact: child.props.exact, path: child.props.path || child.props.from, component: child.props.component, }; const match = matchPath(routeInfo.pathname, matchProps); if (match) { matchedNode = child; } }); if (matchedNode) { return matchedNode; } // If we haven't found a node // try to find one that doesn't have a path or from prop, that will be our not found route React.Children.forEach(node as React.ReactElement, (child: React.ReactElement) => { if (!(child.props.path || child.props.from)) { matchedNode = child; } }); return matchedNode; } function matchComponent(node: React.ReactElement, pathname: string, forceExact?: boolean) { const matchProps = { exact: forceExact ? true : node.props.exact, path: node.props.path || node.props.from, component: node.props.component, }; const match = matchPath(pathname, matchProps); return match; }
the_stack
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, InjectionToken, Optional } from '@angular/core'; import { APIClientInterface } from './api-client.interface'; import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from './types'; import * as models from './models'; export const USE_DOMAIN = new InjectionToken<string>('APIClient_USE_DOMAIN'); export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('APIClient_USE_HTTP_OPTIONS'); type APIHttpOptions = HttpOptions & { headers: HttpHeaders; params: HttpParams; }; @Injectable() export class APIClient implements APIClientInterface { readonly options: APIHttpOptions; readonly domain: string = `https://virtserver.swaggerhub.com/Esquare/EsquareAPI/1.0.0`; constructor( private readonly http: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { if (domain != null) { this.domain = domain; } this.options = { headers: new HttpHeaders(options && options.headers ? options.headers : {}), params: new HttpParams(options && options.params ? options.params : {}), ...(options && options.reportProgress ? { reportProgress: options.reportProgress } : {}), ...(options && options.withCredentials ? { withCredentials: options.withCredentials } : {}) }; } /** * Response generated for [ 200 ] HTTP response code. */ auth( args: Exclude<APIClientInterface['authParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; auth( args: Exclude<APIClientInterface['authParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; auth( args: Exclude<APIClientInterface['authParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; auth( args: Exclude<APIClientInterface['authParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/auth`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<object>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Response generated for [ 200 ] HTTP response code. */ authRef( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; authRef( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; authRef( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; authRef( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/auth/refresh`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<object>(`${this.domain}${path}`, null, options); } /** * Response generated for [ 200 ] HTTP response code. */ passwordRestoreRequest( args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; passwordRestoreRequest( args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; passwordRestoreRequest( args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; passwordRestoreRequest( args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/restore`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<object>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Response generated for [ 200 ] HTTP response code. */ passwordRestoreEmailRequest( args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; passwordRestoreEmailRequest( args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; passwordRestoreEmailRequest( args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; passwordRestoreEmailRequest( args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/restore/request`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<object>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Response generated for [ 200 ] HTTP response code. */ passwordRestoreCheckRestoreGuid( args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; passwordRestoreCheckRestoreGuid( args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; passwordRestoreCheckRestoreGuid( args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; passwordRestoreCheckRestoreGuid( args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/restore/checkGuid`; const options = { ...this.options, ...requestHttpOptions, observe, }; const formData = new FormData(); if (args.restoreGuid != undefined) { formData.append('restoreGuid', args.restoreGuid); } return this.http.post<object>(`${this.domain}${path}`, formData, options); } /** * Get list of roles to permissions mapping * Response generated for [ 200 ] HTTP response code. */ getAclList( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.AclItem[]>; getAclList( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.AclItem[]>>; getAclList( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.AclItem[]>>; getAclList( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.AclItem[] | HttpResponse<models.AclItem[]> | HttpEvent<models.AclItem[]>> { const path = `/acl`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.AclItem[]>(`${this.domain}${path}`, options); } /** * Get structure entities list * Response generated for [ 200 ] HTTP response code. */ getStructureEntitiesList( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Structure[]>; getStructureEntitiesList( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Structure[]>>; getStructureEntitiesList( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Structure[]>>; getStructureEntitiesList( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Structure[] | HttpResponse<models.Structure[]> | HttpEvent<models.Structure[]>> { const path = `/structure`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.Structure[]>(`${this.domain}${path}`, options); } /** * Add a new structure entity * Response generated for [ 200 ] HTTP response code. */ addStructureEntity( args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Structure>; addStructureEntity( args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Structure>>; addStructureEntity( args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Structure>>; addStructureEntity( args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Structure | HttpResponse<models.Structure> | HttpEvent<models.Structure>> { const path = `/structure`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<models.Structure>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Update an existing structure entity * Response generated for [ 200 ] HTTP response code. */ updateStructureEntity( args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Structure>; updateStructureEntity( args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Structure>>; updateStructureEntity( args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Structure>>; updateStructureEntity( args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Structure | HttpResponse<models.Structure> | HttpEvent<models.Structure>> { const path = `/structure/${args.structureId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<models.Structure>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Deletes a structure entity * Response generated for [ 200 ] HTTP response code. */ deleteStructureEntity( args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteStructureEntity( args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteStructureEntity( args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteStructureEntity( args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/structure/${args.structureId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Get reports list * [Screenshot from design](http://prntscr.com/hy4z8d) * * Response generated for [ 200 ] HTTP response code. */ getReportsList( args: Exclude<APIClientInterface['getReportsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; getReportsList( args: Exclude<APIClientInterface['getReportsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; getReportsList( args: Exclude<APIClientInterface['getReportsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; getReportsList( args: Exclude<APIClientInterface['getReportsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/report`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('status' in args) { options.params = options.params.set('status', String(args.status)); } if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('page' in args) { options.params = options.params.set('page', String(args.page)); } if ('orderBy' in args) { options.params = options.params.set('orderBy', String(args.orderBy)); } if ('order' in args) { options.params = options.params.set('order', String(args.order)); } return this.http.get<object>(`${this.domain}${path}`, options); } /** * Get report details * [Screenshot from design](http://prntscr.com/hywkd5) * * Response generated for [ 200 ] HTTP response code. */ getReportDetails( args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ReportItem[]>; getReportDetails( args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ReportItem[]>>; getReportDetails( args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ReportItem[]>>; getReportDetails( args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ReportItem[] | HttpResponse<models.ReportItem[]> | HttpEvent<models.ReportItem[]>> { const path = `/report/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.ReportItem[]>(`${this.domain}${path}`, options); } /** * Get report preview * [Screenshot from design](http://prntscr.com/i3z8zb) * * Response generated for [ 200 ] HTTP response code. */ getReportPreview( args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; getReportPreview( args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; getReportPreview( args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; getReportPreview( args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/report/preview/${args.templateId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('page' in args) { options.params = options.params.set('page', String(args.page)); } if ('orderBy' in args) { options.params = options.params.set('orderBy', String(args.orderBy)); } if ('order' in args) { options.params = options.params.set('order', String(args.order)); } return this.http.get<object>(`${this.domain}${path}`, options); } /** * Get import history * [Screenshot from design](http://prntscr.com/i3ym4j) * * Response generated for [ 200 ] HTTP response code. */ getImportHistory( args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ImportHistoryItem[]>; getImportHistory( args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ImportHistoryItem[]>>; getImportHistory( args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ImportHistoryItem[]>>; getImportHistory( args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ImportHistoryItem[] | HttpResponse<models.ImportHistoryItem[]> | HttpEvent<models.ImportHistoryItem[]>> { const path = `/report/history/${args.templateId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.ImportHistoryItem[]>(`${this.domain}${path}`, options); } /** * Upload a completed template * [Screenshot from design](http://prntscr.com/hy521p) * * Response generated for [ 200 ] HTTP response code. */ uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<number>; uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<number>>; uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<number>>; uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<number | HttpResponse<number> | HttpEvent<number>> { const path = `/report/wizard/uploadfile/${args.templateId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; const formData = new FormData(); if (args.file != undefined) { formData.append('file', args.file); } return this.http.post<number>(`${this.domain}${path}`, formData, options); } /** * Get list of current Import template columns * [Screenshot from design](http://prntscr.com/hy52hi) * * Response generated for [ 200 ] HTTP response code. */ listTemplateColumns( args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Column[]>; listTemplateColumns( args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Column[]>>; listTemplateColumns( args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Column[]>>; listTemplateColumns( args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Column[] | HttpResponse<models.Column[]> | HttpEvent<models.Column[]>> { const path = `/report/wizard/${args.templateId}/templateColumns`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.Column[]>(`${this.domain}${path}`, options); } /** * Get list of current Import template columns * [Screenshot from design](http://prntscr.com/hy52zr) * * Response generated for [ 200 ] HTTP response code. */ listReportColumns( args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Column[]>; listReportColumns( args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Column[]>>; listReportColumns( args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Column[]>>; listReportColumns( args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Column[] | HttpResponse<models.Column[]> | HttpEvent<models.Column[]>> { const path = `/report/wizard/${args.id}/reportColumns`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.Column[]>(`${this.domain}${path}`, options); } /** * Save columns mapping * [Screenshot from design](http://prntscr.com/hy53jt) * * Response generated for [ 200 ] HTTP response code. */ saveColumnsMapping( args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Table>; saveColumnsMapping( args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Table>>; saveColumnsMapping( args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Table>>; saveColumnsMapping( args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Table | HttpResponse<models.Table> | HttpEvent<models.Table>> { const path = `/report/wizard/${args.id}/mapping`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<models.Table>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Get validation table * [Screenshot from design](http://prntscr.com/hy5fct) * * Response generated for [ 200 ] HTTP response code. */ getValidationTable( args: Exclude<APIClientInterface['getValidationTableParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ValidatedTable>; getValidationTable( args: Exclude<APIClientInterface['getValidationTableParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ValidatedTable>>; getValidationTable( args: Exclude<APIClientInterface['getValidationTableParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ValidatedTable>>; getValidationTable( args: Exclude<APIClientInterface['getValidationTableParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ValidatedTable | HttpResponse<models.ValidatedTable> | HttpEvent<models.ValidatedTable>> { const path = `/report/wizard/${args.id}/validationTable`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.ValidatedTable>(`${this.domain}${path}`, options); } /** * Download imported data * [Screenshot from design](http://prntscr.com/hy55ga) * * Response generated for [ 200 ] HTTP response code. */ downloadImportedFile( args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<File>; downloadImportedFile( args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<File>>; downloadImportedFile( args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<File>>; downloadImportedFile( args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<File | HttpResponse<File> | HttpEvent<File>> { const path = `/report/wizard/${args.id}/downloadImported`; const options = { ...this.options, ...requestHttpOptions, observe, responseType: 'blob' as 'json', }; if ('all' in args) { options.params = options.params.set('all', String(args.all)); } return this.http.get<File>(`${this.domain}${path}`, options); } /** * Confirm final import * [Screenshot from design](http://prntscr.com/hy57nj) * * Response generated for [ 200 ] HTTP response code. */ importConfirmation( args: Exclude<APIClientInterface['importConfirmationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ImportResponse>; importConfirmation( args: Exclude<APIClientInterface['importConfirmationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ImportResponse>>; importConfirmation( args: Exclude<APIClientInterface['importConfirmationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ImportResponse>>; importConfirmation( args: Exclude<APIClientInterface['importConfirmationParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ImportResponse | HttpResponse<models.ImportResponse> | HttpEvent<models.ImportResponse>> { const path = `/report/wizard/${args.id}/import`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<models.ImportResponse>(`${this.domain}${path}`, null, options); } /** * Download original file * [Screenshot from design](http://prntscr.com/hy5a54) * * Response generated for [ 200 ] HTTP response code. */ downloadImportOriginalFile( args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<File>; downloadImportOriginalFile( args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<File>>; downloadImportOriginalFile( args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<File>>; downloadImportOriginalFile( args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<File | HttpResponse<File> | HttpEvent<File>> { const path = `/report/wizard/${args.id}/downloadOriginal`; const options = { ...this.options, ...requestHttpOptions, observe, responseType: 'blob' as 'json', }; return this.http.get<File>(`${this.domain}${path}`, options); } /** * Download skipped rows file * [Screenshot from design](http://prntscr.com/hy5ae7) * * Response generated for [ 200 ] HTTP response code. */ downloadImportSkippedFile( args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<File>; downloadImportSkippedFile( args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<File>>; downloadImportSkippedFile( args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<File>>; downloadImportSkippedFile( args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<File | HttpResponse<File> | HttpEvent<File>> { const path = `/report/wizard/${args.id}/downloadSkipped`; const options = { ...this.options, ...requestHttpOptions, observe, responseType: 'blob' as 'json', }; return this.http.get<File>(`${this.domain}${path}`, options); } /** * Cancel current import * [Screenshot from design](http://prntscr.com/hy5aqq) * * Response generated for [ 200 ] HTTP response code. */ cancelImport( args: Exclude<APIClientInterface['cancelImportParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; cancelImport( args: Exclude<APIClientInterface['cancelImportParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; cancelImport( args: Exclude<APIClientInterface['cancelImportParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; cancelImport( args: Exclude<APIClientInterface['cancelImportParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/report/wizard/${args.id}/cancelImport`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<void>(`${this.domain}${path}`, null, options); } /** * Request override data for import * [Screenshot from design](http://prntscr.com/hy5bi6) * * Response generated for [ 200 ] HTTP response code. */ overrideImport( args: Exclude<APIClientInterface['overrideImportParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; overrideImport( args: Exclude<APIClientInterface['overrideImportParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; overrideImport( args: Exclude<APIClientInterface['overrideImportParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; overrideImport( args: Exclude<APIClientInterface['overrideImportParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/report/wizard/${args.id}/override`; const options = { ...this.options, ...requestHttpOptions, observe, }; const formData = new FormData(); if (args.description != undefined) { formData.append('description', args.description); } if (args.file != undefined) { formData.append('file', args.file); } return this.http.post<void>(`${this.domain}${path}`, formData, options); } /** * Get import stats * [Screenshot from design](http://prntscr.com/i4052r) * * Response generated for [ 200 ] HTTP response code. */ geImportStats( args?: APIClientInterface['geImportStatsParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.TotalImportStats>; geImportStats( args?: APIClientInterface['geImportStatsParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.TotalImportStats>>; geImportStats( args?: APIClientInterface['geImportStatsParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.TotalImportStats>>; geImportStats( args: APIClientInterface['geImportStatsParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.TotalImportStats | HttpResponse<models.TotalImportStats> | HttpEvent<models.TotalImportStats>> { const path = `/report/ministry/statistic`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('period' in args) { options.params = options.params.set('period', String(args.period)); } return this.http.get<models.TotalImportStats>(`${this.domain}${path}`, options); } /** * Get issues list * [Screenshot from design](http://prntscr.com/i40s18) * * Response generated for [ 200 ] HTTP response code. */ getIssuesList( args: Exclude<APIClientInterface['getIssuesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; getIssuesList( args: Exclude<APIClientInterface['getIssuesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; getIssuesList( args: Exclude<APIClientInterface['getIssuesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; getIssuesList( args: Exclude<APIClientInterface['getIssuesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/report/ministry/issues`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('period' in args) { options.params = options.params.set('period', String(args.period)); } if ('status' in args) { options.params = options.params.set('status', String(args.status)); } if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('page' in args) { options.params = options.params.set('page', String(args.page)); } if ('orderBy' in args) { options.params = options.params.set('orderBy', String(args.orderBy)); } if ('order' in args) { options.params = options.params.set('order', String(args.order)); } return this.http.get<object>(`${this.domain}${path}`, options); } /** * Get import statuses list * [Screenshot from design](http://prntscr.com/i4byyx) * * Response generated for [ 200 ] HTTP response code. */ getStatusesList( args: Exclude<APIClientInterface['getStatusesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; getStatusesList( args: Exclude<APIClientInterface['getStatusesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; getStatusesList( args: Exclude<APIClientInterface['getStatusesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; getStatusesList( args: Exclude<APIClientInterface['getStatusesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/report/ministry/statuses`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('period' in args) { options.params = options.params.set('period', String(args.period)); } if ('status' in args) { options.params = options.params.set('status', String(args.status)); } if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('page' in args) { options.params = options.params.set('page', String(args.page)); } if ('orderBy' in args) { options.params = options.params.set('orderBy', String(args.orderBy)); } if ('order' in args) { options.params = options.params.set('order', String(args.order)); } return this.http.get<object>(`${this.domain}${path}`, options); } /** * Get users list * Response generated for [ 200 ] HTTP response code. */ getUsersList( args: Exclude<APIClientInterface['getUsersListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; getUsersList( args: Exclude<APIClientInterface['getUsersListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; getUsersList( args: Exclude<APIClientInterface['getUsersListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; getUsersList( args: Exclude<APIClientInterface['getUsersListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/users`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('period' in args) { options.params = options.params.set('period', String(args.period)); } if ('status' in args) { options.params = options.params.set('status', String(args.status)); } if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('page' in args) { options.params = options.params.set('page', String(args.page)); } if ('orderBy' in args) { options.params = options.params.set('orderBy', String(args.orderBy)); } if ('order' in args) { options.params = options.params.set('order', String(args.order)); } if ('assignedToRole' in args) { options.params = options.params.set('assignedToRole', String(args.assignedToRole)); } if ('unassignedFromRole' in args) { options.params = options.params.set('unassignedFromRole', String(args.unassignedFromRole)); } return this.http.get<object>(`${this.domain}${path}`, options); } /** * Create user * Response generated for [ 200 ] HTTP response code. */ createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserDetails>; createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserDetails>>; createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserDetails>>; createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.UserDetails | HttpResponse<models.UserDetails> | HttpEvent<models.UserDetails>> { const path = `/users`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<models.UserDetails>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Get acl structure * Response generated for [ 200 ] HTTP response code. */ getAclStructure( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Acl[]>; getAclStructure( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Acl[]>>; getAclStructure( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Acl[]>>; getAclStructure( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Acl[] | HttpResponse<models.Acl[]> | HttpEvent<models.Acl[]>> { const path = `/users/acl`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.Acl[]>(`${this.domain}${path}`, options); } /** * getUserDetails * Response generated for [ 200 ] HTTP response code. */ getUserDetails( args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserDetails[]>; getUserDetails( args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserDetails[]>>; getUserDetails( args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserDetails[]>>; getUserDetails( args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.UserDetails[] | HttpResponse<models.UserDetails[]> | HttpEvent<models.UserDetails[]>> { const path = `/users/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.UserDetails[]>(`${this.domain}${path}`, options); } /** * update user by id * Response generated for [ 200 ] HTTP response code. */ updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserDetails>; updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserDetails>>; updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserDetails>>; updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.UserDetails | HttpResponse<models.UserDetails> | HttpEvent<models.UserDetails>> { const path = `/users/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<models.UserDetails>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * delete user by id * Response generated for [ 200 ] HTTP response code. */ deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Get roles list * [Screenshot from design](http://prntscr.com/i93q0s) * * Response generated for [ 200 ] HTTP response code. */ getRolesList( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RoleListItem[]>; getRolesList( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RoleListItem[]>>; getRolesList( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RoleListItem[]>>; getRolesList( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.RoleListItem[] | HttpResponse<models.RoleListItem[]> | HttpEvent<models.RoleListItem[]>> { const path = `/users/roles`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.RoleListItem[]>(`${this.domain}${path}`, options); } /** * Create role * Response generated for [ 200 ] HTTP response code. */ createRole( args: Exclude<APIClientInterface['createRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RoleDetailsItem>; createRole( args: Exclude<APIClientInterface['createRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RoleDetailsItem>>; createRole( args: Exclude<APIClientInterface['createRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RoleDetailsItem>>; createRole( args: Exclude<APIClientInterface['createRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.RoleDetailsItem | HttpResponse<models.RoleDetailsItem> | HttpEvent<models.RoleDetailsItem>> { const path = `/users/roles`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<models.RoleDetailsItem>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Get privileges list * [Screenshot from design](http://prntscr.com/i947a3) * * Response generated for [ 200 ] HTTP response code. */ getList( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PrivilegeTreeItem[]>; getList( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PrivilegeTreeItem[]>>; getList( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PrivilegeTreeItem[]>>; getList( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.PrivilegeTreeItem[] | HttpResponse<models.PrivilegeTreeItem[]> | HttpEvent<models.PrivilegeTreeItem[]>> { const path = `/users/privileges`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.PrivilegeTreeItem[]>(`${this.domain}${path}`, options); } /** * Get role details * Response generated for [ 200 ] HTTP response code. */ getRoleDetails( args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RoleDetailsItem[]>; getRoleDetails( args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RoleDetailsItem[]>>; getRoleDetails( args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RoleDetailsItem[]>>; getRoleDetails( args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.RoleDetailsItem[] | HttpResponse<models.RoleDetailsItem[]> | HttpEvent<models.RoleDetailsItem[]>> { const path = `/users/roles/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.RoleDetailsItem[]>(`${this.domain}${path}`, options); } /** * Update role by id * Response generated for [ 200 ] HTTP response code. */ updateRole( args: Exclude<APIClientInterface['updateRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RoleDetailsItem>; updateRole( args: Exclude<APIClientInterface['updateRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RoleDetailsItem>>; updateRole( args: Exclude<APIClientInterface['updateRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RoleDetailsItem>>; updateRole( args: Exclude<APIClientInterface['updateRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.RoleDetailsItem | HttpResponse<models.RoleDetailsItem> | HttpEvent<models.RoleDetailsItem>> { const path = `/users/roles/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<models.RoleDetailsItem>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Ddelete role by id * Response generated for [ 200 ] HTTP response code. */ deleteRole( args: Exclude<APIClientInterface['deleteRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteRole( args: Exclude<APIClientInterface['deleteRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteRole( args: Exclude<APIClientInterface['deleteRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteRole( args: Exclude<APIClientInterface['deleteRoleParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/roles/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Get unviewed notifications list * [Screenshot from design](http://prntscr.com/iba7xr) * * Response generated for [ 200 ] HTTP response code. */ getNewNotificationsList( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.NotificationListItem[]>; getNewNotificationsList( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.NotificationListItem[]>>; getNewNotificationsList( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.NotificationListItem[]>>; getNewNotificationsList( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.NotificationListItem[] | HttpResponse<models.NotificationListItem[]> | HttpEvent<models.NotificationListItem[]>> { const path = `/notifications/new`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.NotificationListItem[]>(`${this.domain}${path}`, options); } /** * Mark notifications as viewed * Response generated for [ 200 ] HTTP response code. */ markViewedNotifications( args?: APIClientInterface['markViewedNotificationsParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; markViewedNotifications( args?: APIClientInterface['markViewedNotificationsParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; markViewedNotifications( args?: APIClientInterface['markViewedNotificationsParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; markViewedNotifications( args: APIClientInterface['markViewedNotificationsParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/notifications/markAsViewed`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<void>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Get user's notifications list * [Screenshot from design](http://prntscr.com/iba8tq) * * Response generated for [ 200 ] HTTP response code. */ getNotificationsList( args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; getNotificationsList( args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; getNotificationsList( args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; getNotificationsList( args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/notifications/all`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('page' in args) { options.params = options.params.set('page', String(args.page)); } if ('orderBy' in args) { options.params = options.params.set('orderBy', String(args.orderBy)); } if ('order' in args) { options.params = options.params.set('order', String(args.order)); } return this.http.get<object>(`${this.domain}${path}`, options); } /** * Get modules list * [Screenshot from design](http://prntscr.com/ibac47) | * [Screenshot from design](http://prntscr.com/ibacgu) * * Response generated for [ 200 ] HTTP response code. */ getModulesList( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.NotificationModule[]>; getModulesList( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.NotificationModule[]>>; getModulesList( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.NotificationModule[]>>; getModulesList( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.NotificationModule[] | HttpResponse<models.NotificationModule[]> | HttpEvent<models.NotificationModule[]>> { const path = `/notifications/modules`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.NotificationModule[]>(`${this.domain}${path}`, options); } /** * Get triggers list * [Screenshot from design](http://prntscr.com/ibad9m) * * Response generated for [ 200 ] HTTP response code. */ getTriggersList( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.NotificationTrigger[]>; getTriggersList( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.NotificationTrigger[]>>; getTriggersList( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.NotificationTrigger[]>>; getTriggersList( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.NotificationTrigger[] | HttpResponse<models.NotificationTrigger[]> | HttpEvent<models.NotificationTrigger[]>> { const path = `/notifications/triggers`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.NotificationTrigger[]>(`${this.domain}${path}`, options); } /** * Get module's notifications list * [Screenshot from design](http://prntscr.com/iba8tq) * * Response generated for [ 200 ] HTTP response code. */ getModuleNotificationsList( args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<object>; getModuleNotificationsList( args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<object>>; getModuleNotificationsList( args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<object>>; getModuleNotificationsList( args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<object | HttpResponse<object> | HttpEvent<object>> { const path = `/notifications/modules/${args.moduleId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('page' in args) { options.params = options.params.set('page', String(args.page)); } if ('orderBy' in args) { options.params = options.params.set('orderBy', String(args.orderBy)); } if ('order' in args) { options.params = options.params.set('order', String(args.order)); } return this.http.get<object>(`${this.domain}${path}`, options); } /** * Enable notification * Response generated for [ 200 ] HTTP response code. */ enableNotification( args: Exclude<APIClientInterface['enableNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; enableNotification( args: Exclude<APIClientInterface['enableNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; enableNotification( args: Exclude<APIClientInterface['enableNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; enableNotification( args: Exclude<APIClientInterface['enableNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/notifications/enable/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<void>(`${this.domain}${path}`, null, options); } /** * Disable notification * Response generated for [ 200 ] HTTP response code. */ disableNotification( args: Exclude<APIClientInterface['disableNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; disableNotification( args: Exclude<APIClientInterface['disableNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; disableNotification( args: Exclude<APIClientInterface['disableNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; disableNotification( args: Exclude<APIClientInterface['disableNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/notifications/disable/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<void>(`${this.domain}${path}`, null, options); } /** * Get notification details * Response generated for [ 200 ] HTTP response code. */ getNotification( args: Exclude<APIClientInterface['getNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.NotificationEditableListItem>; getNotification( args: Exclude<APIClientInterface['getNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.NotificationEditableListItem>>; getNotification( args: Exclude<APIClientInterface['getNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.NotificationEditableListItem>>; getNotification( args: Exclude<APIClientInterface['getNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.NotificationEditableListItem | HttpResponse<models.NotificationEditableListItem> | HttpEvent<models.NotificationEditableListItem>> { const path = `/notifications/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.NotificationEditableListItem>(`${this.domain}${path}`, options); } /** * Update notification * Response generated for [ 200 ] HTTP response code. */ updateNotification( args: Exclude<APIClientInterface['updateNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; updateNotification( args: Exclude<APIClientInterface['updateNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; updateNotification( args: Exclude<APIClientInterface['updateNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; updateNotification( args: Exclude<APIClientInterface['updateNotificationParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/notifications/${args.id}`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<void>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Create notification * Response generated for [ 200 ] HTTP response code. */ createNotification( args?: APIClientInterface['createNotificationParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<number>; createNotification( args?: APIClientInterface['createNotificationParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<number>>; createNotification( args?: APIClientInterface['createNotificationParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<number>>; createNotification( args: APIClientInterface['createNotificationParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<number | HttpResponse<number> | HttpEvent<number>> { const path = `/notifications`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.post<number>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Get password verefication settings * [Screenshot from design](http://prntscr.com/ijzt2b) * * Response generated for [ 200 ] HTTP response code. */ getPassVerificationPolicies( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PasswordVerificationPolicies>; getPassVerificationPolicies( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PasswordVerificationPolicies>>; getPassVerificationPolicies( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PasswordVerificationPolicies>>; getPassVerificationPolicies( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.PasswordVerificationPolicies | HttpResponse<models.PasswordVerificationPolicies> | HttpEvent<models.PasswordVerificationPolicies>> { const path = `/security-policy/password-verification`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.PasswordVerificationPolicies>(`${this.domain}${path}`, options); } /** * Update password verefication settings * [Screenshot from design](http://prntscr.com/ijzt2b) * * Response generated for [ 200 ] HTTP response code. */ udatePassVerificationPolicies( args?: APIClientInterface['udatePassVerificationPoliciesParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PasswordVerificationPolicies>; udatePassVerificationPolicies( args?: APIClientInterface['udatePassVerificationPoliciesParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PasswordVerificationPolicies>>; udatePassVerificationPolicies( args?: APIClientInterface['udatePassVerificationPoliciesParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PasswordVerificationPolicies>>; udatePassVerificationPolicies( args: APIClientInterface['udatePassVerificationPoliciesParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.PasswordVerificationPolicies | HttpResponse<models.PasswordVerificationPolicies> | HttpEvent<models.PasswordVerificationPolicies>> { const path = `/security-policy/password-verification`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<models.PasswordVerificationPolicies>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Get password creation settings * [Screenshot from design](http://prntscr.com/ijzuv3) * * Response generated for [ 200 ] HTTP response code. */ getPassCreationPolicies( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PasswordCreationPolicies>; getPassCreationPolicies( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PasswordCreationPolicies>>; getPassCreationPolicies( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PasswordCreationPolicies>>; getPassCreationPolicies( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.PasswordCreationPolicies | HttpResponse<models.PasswordCreationPolicies> | HttpEvent<models.PasswordCreationPolicies>> { const path = `/security-policy/password-creation`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.PasswordCreationPolicies>(`${this.domain}${path}`, options); } /** * Update password creation settings * [Screenshot from design](http://prntscr.com/ijzuv3) * * Response generated for [ 200 ] HTTP response code. */ udatePassCreationPolicies( args?: APIClientInterface['udatePassCreationPoliciesParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PasswordCreationPolicies>; udatePassCreationPolicies( args?: APIClientInterface['udatePassCreationPoliciesParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PasswordCreationPolicies>>; udatePassCreationPolicies( args?: APIClientInterface['udatePassCreationPoliciesParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PasswordCreationPolicies>>; udatePassCreationPolicies( args: APIClientInterface['udatePassCreationPoliciesParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.PasswordCreationPolicies | HttpResponse<models.PasswordCreationPolicies> | HttpEvent<models.PasswordCreationPolicies>> { const path = `/security-policy/password-creation`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<models.PasswordCreationPolicies>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Get other security settings settings * [Screenshot from design](http://prntscr.com/ijzvo3) * * Response generated for [ 200 ] HTTP response code. */ getOtherSecuritySettings( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.OtherSecuritySettings>; getOtherSecuritySettings( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.OtherSecuritySettings>>; getOtherSecuritySettings( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.OtherSecuritySettings>>; getOtherSecuritySettings( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.OtherSecuritySettings | HttpResponse<models.OtherSecuritySettings> | HttpEvent<models.OtherSecuritySettings>> { const path = `/security-policy/other-settings`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.get<models.OtherSecuritySettings>(`${this.domain}${path}`, options); } /** * Update other security settings settings * [Screenshot from design](http://prntscr.com/ijzvo3) * * Response generated for [ 200 ] HTTP response code. */ udateOtherSecuritySettings( args?: APIClientInterface['udateOtherSecuritySettingsParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.OtherSecuritySettings>; udateOtherSecuritySettings( args?: APIClientInterface['udateOtherSecuritySettingsParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.OtherSecuritySettings>>; udateOtherSecuritySettings( args?: APIClientInterface['udateOtherSecuritySettingsParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.OtherSecuritySettings>>; udateOtherSecuritySettings( args: APIClientInterface['udateOtherSecuritySettingsParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.OtherSecuritySettings | HttpResponse<models.OtherSecuritySettings> | HttpEvent<models.OtherSecuritySettings>> { const path = `/security-policy/other-settings`; const options = { ...this.options, ...requestHttpOptions, observe, }; return this.http.put<models.OtherSecuritySettings>(`${this.domain}${path}`, JSON.stringify(args.body), options); } }
the_stack
import * as EE from 'events'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); type NodeV8MessageType = 'request' | 'response' | 'event'; export class NodeV8Message { seq: number; type: NodeV8MessageType; public constructor(type: NodeV8MessageType) { this.seq = 0; this.type = type; } } export class NodeV8Response extends NodeV8Message { request_seq: number; success: boolean; running: boolean; command: string; message: string; body: any; refs: V8Object[]; public constructor(request: NodeV8Response, message?: string) { super('response'); this.request_seq = request.seq; this.command = request.command; if (message) { this.success = false; this.message = message; } else { this.success = true; } } } export class NodeV8Event extends NodeV8Message { event: string; body: V8EventBody; public constructor(event: string, body?: any) { super('event'); this.event = event; if (body) { this.body = body; } } } // response types export interface V8Handle { handle: number; type: 'undefined' | 'null' | 'boolean' | 'number' | 'string' | 'object' | 'function' | 'frame' | 'set' | 'map' | 'regexp' | 'promise' | 'generator' | 'error'; } export interface V8Simple extends V8Handle { value?: boolean | number | string; } export interface V8Object extends V8Simple { vscode_indexedCnt?: number; vscode_namedCnt?: number; className?: string; constructorFunction?: V8Ref; protoObject?: V8Ref; prototypeObject?: V8Ref; properties?: V8Property[]; text?: string; status?: string; } export interface V8Function extends V8Object { name?: string; inferredName?: string; } export interface V8Script extends V8Handle { name: string; id: number; source: string; } export interface V8Ref { ref: number; // if resolved, then a value exists value?: boolean | number | string; handle?: number; } export interface V8Property extends V8Ref { name: number | string; } export interface V8Frame { index: number; line: number; column: number; script: V8Ref; func: V8Ref; receiver: V8Ref; } export interface V8Scope { type: number; frameIndex : number; index: number; object: V8Ref; } type BreakpointType = 'function' | 'script' | 'scriptId' | 'scriptRegExp'; export interface V8Breakpoint { type: BreakpointType; script_id: number; number: number; script_regexp: string; } // responses export interface V8ScopeResponse extends NodeV8Response { body: { vscode_locals?: number; scopes: V8Scope[]; }; } export interface V8EvaluateResponse extends NodeV8Response { body: V8Object; } export interface V8BacktraceResponse extends NodeV8Response { body: { fromFrame: number; toFrame: number; totalFrames: number; frames: V8Frame[]; }; } export interface V8ScriptsResponse extends NodeV8Response { body: V8Script[]; } export interface V8SetVariableValueResponse extends NodeV8Response { body: { newValue: V8Handle; }; } export interface V8FrameResponse extends NodeV8Response { body: V8Frame; } export interface V8ListBreakpointsResponse extends NodeV8Response { body: { breakpoints: V8Breakpoint[]; }; } export interface V8SetBreakpointResponse extends NodeV8Response { body: { type: string; breakpoint: number; script_id: number; actual_locations: { line: number; column: number; }[]; }; } type ExceptionType = 'all' | 'uncaught'; export interface V8SetExceptionBreakResponse extends NodeV8Response { body: { type: ExceptionType; enabled: boolean; }; } export interface V8RestartFrameResponse extends NodeV8Response { body: { result: boolean; }; } // events export interface V8EventBody { script: V8Script; sourceLine: number; sourceColumn: number; sourceLineText: string; } export interface V8BreakEventBody extends V8EventBody { breakpoints: any[]; } export interface V8ExceptionEventBody extends V8EventBody { exception: V8Object; uncaught: boolean; } // arguments export interface V8BacktraceArgs { fromFrame: number; toFrame: number; } export interface V8RestartFrameArgs { frame: number | undefined; } export interface V8EvaluateArgs { expression: string; disable_break?: boolean; maxStringLength?: number; global?: boolean; frame?: number; additional_context?: { name: string; handle: number; }[]; } export interface V8ScriptsArgs { types: number; includeSource?: boolean; ids?: number[]; filter?: string; } export interface V8SetVariableValueArgs { scope: { frameNumber: number; number: number; }; name: string; newValue: { type?: string; value?: boolean | number | string; handle?: number; }; } export interface V8FrameArgs { } export interface V8ClearBreakpointArgs { breakpoint: number; } export interface V8SetBreakpointArgs { type: BreakpointType; target: number | string; line?: number; column?: number; condition?: string; } export interface V8SetExceptionBreakArgs { type: ExceptionType; enabled?: boolean; } //---- the protocol implementation export class NodeV8Protocol extends EE.EventEmitter { private static TIMEOUT = 10000; private static TWO_CRLF = '\r\n\r\n'; private _rawData: Buffer; private _contentLength: number; private _sequence: number; private _writableStream: NodeJS.WritableStream; private _pendingRequests = new Map<number, (response: NodeV8Response) => void>(); private _unresponsiveMode: boolean; private _responseHook: ((response: NodeV8Response) => void) | undefined; public hostVersion: string | undefined; public embeddedHostVersion: number = -1; public v8Version: string | undefined; public constructor(responseHook?: (response: NodeV8Response) => void) { super(); this._responseHook = responseHook; } public startDispatch(inStream: NodeJS.ReadableStream, outStream: NodeJS.WritableStream) : void { this._sequence = 1; this._writableStream = outStream; inStream.on('data', (data: Buffer) => this.execute(data)); inStream.on('close', () => { this.emitEvent(new NodeV8Event('close')); }); inStream.on('error', (error) => { this.emitEvent(new NodeV8Event('error')); }); outStream.on('error', (error) => { this.emitEvent(new NodeV8Event('error')); }); inStream.resume(); } public stop() : void { if (this._writableStream) { this._writableStream.end(); } } public command(command: string, args?: any, cb?: (response: NodeV8Response) => void) : void { this._command(command, args, NodeV8Protocol.TIMEOUT, cb); } public command2(command: string, args?: any, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<NodeV8Response> { return new Promise((resolve, reject) => { this._command(command, args, timeout, response => { if (response.success) { resolve(response); } else { if (!response.command) { // some responses don't have the 'command' attribute. response.command = command; } reject(response); } }); }); } public backtrace(args: V8BacktraceArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8BacktraceResponse> { return this.command2('backtrace', args); } public restartFrame(args: V8RestartFrameArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8RestartFrameResponse> { return this.command2('restartframe', args); } public evaluate(args: V8EvaluateArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8EvaluateResponse> { return this.command2('evaluate', args); } public scripts(args: V8ScriptsArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8ScriptsResponse> { return this.command2('scripts', args); } public setVariableValue(args: V8SetVariableValueArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8SetVariableValueResponse> { return this.command2('setvariablevalue', args); } public frame(args: V8FrameArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8FrameResponse> { return this.command2('frame', args); } public setBreakpoint(args: V8SetBreakpointArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8SetBreakpointResponse> { return this.command2('setbreakpoint', args); } public setExceptionBreak(args: V8SetExceptionBreakArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8SetExceptionBreakResponse> { return this.command2('setexceptionbreak', args); } public clearBreakpoint(args: V8ClearBreakpointArgs, timeout: number = NodeV8Protocol.TIMEOUT) : Promise<NodeV8Response> { return this.command2('clearbreakpoint', args); } public listBreakpoints(timeout: number = NodeV8Protocol.TIMEOUT) : Promise<V8ListBreakpointsResponse> { return this.command2('listbreakpoints'); } public sendEvent(event: NodeV8Event) : void { this.send('event', event); } public sendResponse(response: NodeV8Response) : void { if (response.seq > 0) { // console.error('attempt to send more than one response for command {0}', response.command); } else { this.send('response', response); } } // ---- private ------------------------------------------------------------ private _command(command: string, args: any, timeout: number, cb?: (response: NodeV8Response) => void) : void { const request: any = { command: command }; if (args && Object.keys(args).length > 0) { request.arguments = args; } if (!this._writableStream) { if (cb) { cb(new NodeV8Response(request, localize('not.connected', "not connected to runtime"))); } return; } if (this._unresponsiveMode) { if (cb) { cb(new NodeV8Response(request, localize('runtime.unresponsive', "cancelled because Node.js is unresponsive"))); } return; } this.send('request', request); if (cb) { this._pendingRequests.set(request.seq, cb); const timer = setTimeout(() => { clearTimeout(timer); const clb = this._pendingRequests.get(request.seq); if (clb) { this._pendingRequests.delete(request.seq); clb(new NodeV8Response(request, localize('runtime.timeout', "timeout after {0} ms", timeout))); this._unresponsiveMode = true; this.emitEvent(new NodeV8Event('diagnostic', { reason: `request '${command}' timed out'`})); } }, timeout); } } private emitEvent(event: NodeV8Event) { this.emit(event.event, event); } private send(typ: NodeV8MessageType, message: NodeV8Message) : void { message.type = typ; message.seq = this._sequence++; const json = JSON.stringify(message); const data = 'Content-Length: ' + Buffer.byteLength(json, 'utf8') + '\r\n\r\n' + json; if (this._writableStream) { this._writableStream.write(data); } } private internalDispatch(message: NodeV8Message) : void { switch (message.type) { case 'event': const e = <NodeV8Event> message; this.emitEvent(e); break; case 'response': if (this._unresponsiveMode) { this._unresponsiveMode = false; this.emitEvent(new NodeV8Event('diagnostic', { reason: 'responsive' })); } const response = <NodeV8Response> message; const clb = this._pendingRequests.get(response.request_seq); if (clb) { this._pendingRequests.delete(response.request_seq); if (this._responseHook) { this._responseHook(response); } clb(response); } break; default: break; } } private execute(data: Buffer): void { this._rawData = this._rawData ? Buffer.concat([this._rawData, data]) : data; while (true) { if (this._contentLength >= 0) { if (this._rawData.length >= this._contentLength) { const message = this._rawData.toString('utf8', 0, this._contentLength); this._rawData = this._rawData.slice(this._contentLength); this._contentLength = -1; if (message.length > 0) { try { this.internalDispatch(JSON.parse(message)); } catch (e) { } } continue; // there may be more complete messages to process } } else { const idx = this._rawData.indexOf(NodeV8Protocol.TWO_CRLF); if (idx !== -1) { const header = this._rawData.toString('utf8', 0, idx); const lines = header.split('\r\n'); for (let i = 0; i < lines.length; i++) { const pair = lines[i].split(/: +/); switch (pair[0]) { case 'V8-Version': const match0 = pair[1].match(/(\d+(?:\.\d+)+)/); if (match0 && match0.length === 2) { this.v8Version = match0[1]; } break; case 'Embedding-Host': const match = pair[1].match(/node\sv(\d+)\.(\d+)\.(\d+)/); if (match && match.length === 4) { this.embeddedHostVersion = (parseInt(match[1])*100 + parseInt(match[2]))*100 + parseInt(match[3]); } else if (pair[1] === 'Electron') { this.embeddedHostVersion = 60500; // TODO this needs to be detected in a smarter way by looking at the V8 version in Electron } const match1 = pair[1].match(/node\s(v\d+\.\d+\.\d+)/); if (match1 && match1.length === 2) { this.hostVersion = match1[1]; } break; case 'Content-Length': this._contentLength = +pair[1]; break; } } this._rawData = this._rawData.slice(idx + NodeV8Protocol.TWO_CRLF.length); continue; // try to handle a complete message } } break; } } }
the_stack
import {html} from '@polymer/polymer'; import './styles'; export const template = html` <style include="vz-projector-styles"></style> <style> :host { transition: height 0.2s; } .ink-button { border: none; border-radius: 2px; font-size: 13px; padding: 10px; min-width: 88px; flex-shrink: 0; background: #e3e3e3; } .ink-panel-buttons { margin-bottom: 10px; } .two-way-toggle { display: flex; flex-direction: row; } .two-way-toggle span { padding-right: 7px; } .has-border { border: 1px solid rgba(0, 0, 0, 0.1); } .toggle { min-width: 0px; font-size: 12px; width: 17px; min-height: 0px; height: 21px; padding: 0; margin: 0px; } .toggle[active] { background-color: #880e4f; color: white; } .two-columns { display: flex; justify-content: space-between; } .two-columns > :first-child { margin-right: 15px; } .two-columns > div { width: 50%; } .dropdown-item { justify-content: space-between; min-height: 35px; } .tsne-supervise-factor { margin-bottom: -8px; } #z-container { display: flex; align-items: center; width: 50%; } #z-checkbox { margin: 27px 0 0 5px; width: 18px; } #z-dropdown { flex-grow: 1; } .notice { color: #880e4f; } .container { padding: 20px; } .book-icon { height: 20px; color: rgba(0, 0, 0, 0.7); } .item-details { color: gray; font-size: 12px; margin-left: 5px; } .pca-dropdown { width: 100%; } .pca-dropdown paper-listbox { width: 135px; } .dropdown-item.header { border-bottom: 1px solid #aaa; color: #333; font-weight: bold; } #total-variance { color: rgba(0, 0, 0, 0.7); } </style> <div id="main"> <div class="ink-panel-header"> <div class="ink-tab-group"> <div data-tab="umap" id="umap-tab" class="ink-tab projection-tab"> UMAP </div> <paper-tooltip for="umap-tab" position="bottom" animation-delay="0" fit-to-visible-bounds > uniform manifold approximation and projection </paper-tooltip> <div data-tab="tsne" id="tsne-tab" class="ink-tab projection-tab"> t-SNE </div> <paper-tooltip for="tsne-tab" position="bottom" animation-delay="0" fit-to-visible-bounds > t-distributed stochastic neighbor embedding </paper-tooltip> <div data-tab="pca" id="pca-tab" class="ink-tab projection-tab"> PCA </div> <paper-tooltip for="pca-tab" position="bottom" animation-delay="0" fit-to-visible-bounds > Principal component analysis </paper-tooltip> <div data-tab="custom" id="custom-tab" class="ink-tab projection-tab" title="Linear projection of two custom vectors" > Custom </div> <paper-tooltip for="custom-tab" position="bottom" animation-delay="0" fit-to-visible-bounds > Search for two vectors upon which to project all points. </paper-tooltip> </div> </div> <div class="container"> <!-- UMAP Controls --> <div data-panel="umap" class="ink-panel-content"> <div class="slider"> <label>Dimension</label> <div class="two-way-toggle"> <span>2D</span> <paper-toggle-button id="umap-toggle" checked="{{umapIs3d}}" >3D</paper-toggle-button > </div> </div> <div class="slider umap-neighbors"> <label> Neighbors <paper-icon-button icon="help" class="help-icon" ></paper-icon-button> <paper-tooltip position="right" animation-delay="0" fit-to-visible-bounds > The number of nearest neighbors used to compute the fuzzy simplicial set, which is used to approximate the overall shape of the manifold. The default value is 15. </paper-tooltip> </label> <paper-slider id="umap-neighbors-slider" value="{{umapNeighbors}}" pin min="5" max="50" ></paper-slider> <span>[[umapNeighbors]]</span> </div> <p> <button id="run-umap" class="ink-button" title="Run UMAP" on-tap="runUmap" > Run </button> </p> <p id="umap-sampling" class="notice"> For faster results, the data will be sampled down to [[getUmapSampleSizeText()]] points. </p> <p> <iron-icon icon="book" class="book-icon"></iron-icon> <a target="_blank" rel="noopener" href="https://umap-learn.readthedocs.io/en/latest/how_umap_works.html" > Learn more about UMAP. </a> </p> </div> <!-- TSNE Controls --> <div data-panel="tsne" class="ink-panel-content"> <div class="slider"> <label>Dimension</label> <div class="two-way-toggle"> <span>2D</span> <paper-toggle-button id="tsne-toggle" checked="{{tSNEis3d}}" >3D</paper-toggle-button > </div> </div> <div class="slider tsne-perplexity"> <label> Perplexity <paper-icon-button icon="help" class="help-icon" ></paper-icon-button> <paper-tooltip position="right" animation-delay="0" fit-to-visible-bounds > The most appropriate perplexity value depends on the density of the data. Loosely speaking, a larger / denser dataset requires a larger perplexity. Typical values for perplexity range between 5 and 50. </paper-tooltip> </label> <paper-slider id="perplexity-slider" pin min="2" max="100" value="30" ></paper-slider> <span></span> </div> <div class="slider tsne-learning-rate"> <label> Learning rate <paper-icon-button icon="help" class="help-icon" ></paper-icon-button> <paper-tooltip position="right" animation-delay="0" fit-to-visible-bounds > The ideal learning rate often depends on the size of the data, with smaller datasets requiring smaller learning rates. </paper-tooltip> </label> <paper-slider id="learning-rate-slider" snaps min="-3" max="2" step="1" value="1" max-markers="6" > </paper-slider> <span></span> </div> <div class="slider tsne-supervise-factor"> <label> Supervise <paper-icon-button icon="help" class="help-icon" ></paper-icon-button> <paper-tooltip position="right" animation-delay="0" fit-to-visible-bounds > The label importance used for supervision, from 0 (disabled) to 100 (full importance). </paper-tooltip> </label> <paper-slider id="supervise-factor-slider" min="0" max="100" pin value="{{superviseFactor}}" > </paper-slider> <span></span> </div> <p> <button class="run-tsne ink-button" title="Re-run t-SNE"> Run </button> <button class="pause-tsne ink-button" title="Pause t-SNE"> Pause </button> <button class="perturb-tsne ink-button" title="Perturb t-SNE"> Perturb </button> </p> <p>Iteration: <span class="run-tsne-iter">0</span></p> <p id="tsne-sampling" class="notice"> For faster results, the data will be sampled down to [[getTsneSampleSizeText()]] points. </p> <p> <iron-icon icon="book" class="book-icon"></iron-icon> <a target="_blank" href="http://distill.pub/2016/misread-tsne/" rel="noopener noreferrer" > How to use t-SNE effectively. </a> </p> </div> <!-- PCA Controls --> <div data-panel="pca" class="ink-panel-content"> <div class="two-columns"> <div> <!-- Left column --> <paper-dropdown-menu class="pca-dropdown" vertical-align="bottom" no-animations label="X" > <paper-listbox attr-for-selected="value" class="dropdown-content" selected="{{pcaX}}" slot="dropdown-content" > <paper-item disabled class="dropdown-item header"> <div>#</div> <div>Variance (%)</div> </paper-item> <template is="dom-repeat" items="[[pcaComponents]]"> <paper-item class="dropdown-item" value="[[item.id]]" label="Component #[[item.componentNumber]]" > <div>[[item.componentNumber]]</div> <div class="item-details">[[item.percVariance]]</div> </paper-item> </template> </paper-listbox> </paper-dropdown-menu> <paper-dropdown-menu class="pca-dropdown" no-animations vertical-align="bottom" label="Z" disabled="[[!hasPcaZ]]" id="z-dropdown" > <paper-listbox attr-for-selected="value" class="dropdown-content" selected="{{pcaZ}}" slot="dropdown-content" > <paper-item disabled class="dropdown-item header"> <div>#</div> <div>Variance (%)</div> </paper-item> <template is="dom-repeat" items="[[pcaComponents]]"> <paper-item class="dropdown-item" value="[[item.id]]" label="Component #[[item.componentNumber]]" > <div>[[item.componentNumber]]</div> <div class="item-details">[[item.percVariance]]</div> </paper-item> </template> </paper-listbox> </paper-dropdown-menu> </div> <div> <!-- Right column --> <paper-dropdown-menu class="pca-dropdown" vertical-align="bottom" no-animations label="Y" > <paper-listbox attr-for-selected="value" class="dropdown-content" selected="{{pcaY}}" slot="dropdown-content" > <paper-item disabled class="dropdown-item header"> <div>#</div> <div>Variance (%)</div> </paper-item> <template is="dom-repeat" items="[[pcaComponents]]"> <paper-item class="dropdown-item" value="[[item.id]]" label="Component #[[item.componentNumber]]" > <div>[[item.componentNumber]]</div> <div class="item-details">[[item.percVariance]]</div> </paper-item> </template> </paper-listbox> </paper-dropdown-menu> <paper-checkbox id="z-checkbox" checked="{{pcaIs3d}}" ></paper-checkbox> </div> </div> <p id="pca-sampling" class="notice"> PCA is approximate. <paper-icon-button icon="help" class="help-icon" ></paper-icon-button> </p> <div id="total-variance">Total variance</div> <paper-tooltip for="pca-sampling" position="top" animation-delay="0" fit-to-visible-bounds > For fast results, the data was sampled to [[getPcaSampleSizeText()]] points and randomly projected down to [[getPcaSampledDimText()]] dimensions. </paper-tooltip> </div> <!-- Custom Controls --> <div data-panel="custom" class="ink-panel-content"> <paper-dropdown-menu style="width: 100%" no-animations label="Search by" > <paper-listbox attr-for-selected="value" class="dropdown-content" selected="{{customSelectedSearchByMetadataOption}}" slot="dropdown-content" > <template is="dom-repeat" items="[[searchByMetadataOptions]]"> <paper-item class="dropdown-item" value="[[item]]" label="[[item]]" > [[item]] </paper-item> </template> </paper-listbox> </paper-dropdown-menu> <div class="two-columns"> <vz-projector-input id="xLeft" label="Left"></vz-projector-input> <vz-projector-input id="xRight" label="Right"></vz-projector-input> </div> <div class="two-columns"> <vz-projector-input id="yUp" label="Up"></vz-projector-input> <vz-projector-input id="yDown" label="Down"></vz-projector-input> </div> </div> </div> </div> </template> <script src="vz-projector-projections-panel.js"></script> </dom-module> `;
the_stack
import crypto from 'crypto'; import { EventEmitter } from 'events'; import invariant from 'invariant'; import pProps from 'p-props'; import warning from 'warning'; import { JsonObject } from 'type-fest'; import { SlackOAuthClient } from 'messaging-api-slack'; import { camelcaseKeysDeep } from 'messaging-api-common'; import Session from '../session/Session'; import { Connector } from '../bot/Connector'; import { RequestContext } from '../types'; import SlackContext from './SlackContext'; import SlackEvent from './SlackEvent'; import { BlockActionEvent, CommandEvent, InteractiveMessageEvent, Message, SlackRawEvent, SlackRequestBody, UIEvent, } from './SlackTypes'; type CommonConnectorOptions = { skipLegacyProfile?: boolean; verificationToken?: string; signingSecret?: string; includeBotMessages?: boolean; }; type ConnectorOptionsWithoutClient = { accessToken: string; origin?: string; } & CommonConnectorOptions; type ConnectorOptionsWithClient = { client: SlackOAuthClient; } & CommonConnectorOptions; export type SlackConnectorOptions = | ConnectorOptionsWithoutClient | ConnectorOptionsWithClient; export default class SlackConnector implements Connector<SlackRequestBody, SlackOAuthClient> { _client: SlackOAuthClient; _verificationToken: string; _signingSecret: string; _skipLegacyProfile: boolean; _includeBotMessages: boolean; constructor(options: SlackConnectorOptions) { const { verificationToken, skipLegacyProfile, includeBotMessages, signingSecret, } = options; if ('client' in options) { this._client = options.client; } else { const { accessToken, origin } = options; invariant( accessToken, 'Slack access token is required. Please make sure you have filled it correctly in `bottender.config.js` or `.env` file.' ); this._client = new SlackOAuthClient({ accessToken, origin, }); } this._signingSecret = signingSecret || ''; this._verificationToken = verificationToken || ''; if (!this._signingSecret) { if (!this._verificationToken) { warning( false, 'Both `signingSecret` and `verificationToken` is not set. Will bypass Slack event verification.\nPass in `signingSecret` to perform Slack event verification.' ); } else { warning( false, "It's deprecated to use `verificationToken` here, use `signingSecret` instead." ); } } this._skipLegacyProfile = typeof skipLegacyProfile === 'boolean' ? skipLegacyProfile : true; this._includeBotMessages = includeBotMessages || false; } _getRawEventFromRequest(body: SlackRequestBody): SlackRawEvent { if ('event' in body) { return body.event as Message; } if (body.payload && typeof body.payload === 'string') { const payload = camelcaseKeysDeep(JSON.parse(body.payload)); if (payload.type === 'interactive_message') { return payload as InteractiveMessageEvent; } return payload as BlockActionEvent; } // for RTM WebSocket messages and Slash Command messages return body as any as Message; } _isBotEventRequest(body: SlackRequestBody): boolean { const rawEvent = this._getRawEventFromRequest(body); return !!( (rawEvent as Message).botId || ('subtype' in rawEvent && rawEvent.subtype === 'bot_message') ); } get platform(): 'slack' { return 'slack'; } get client(): SlackOAuthClient { return this._client; } // FIXME: define types for every slack events _getChannelId(rawEvent: any): string | null { // For interactive_message format if ( rawEvent.channel && typeof rawEvent.channel === 'object' && rawEvent.channel.id ) { return rawEvent.channel.id; } // For pin_added format if (rawEvent.channelId) { return rawEvent.channelId; } // For slack modal if (rawEvent.view && rawEvent.view.privateMetadata) { const channelId = JSON.parse(rawEvent.view.privateMetadata).channelId; if (channelId) { return channelId; } } // For reaction_added format if ( rawEvent.item && typeof rawEvent.item === 'object' && typeof rawEvent.item.channel === 'string' ) { return rawEvent.item.channel; } return ( (rawEvent as Message).channel || (rawEvent as CommandEvent).channelId ); } _getUserId(rawEvent: SlackRawEvent): string | null { if ( rawEvent.type === 'interactive_message' || rawEvent.type === 'block_actions' || rawEvent.type === 'view_submission' || rawEvent.type === 'view_closed' ) { return (rawEvent as UIEvent).user.id; } return ( (rawEvent as Message).user || (rawEvent as CommandEvent).userId || (rawEvent as UIEvent).user?.id ); } getUniqueSessionKey(body: SlackRequestBody): string | null { const rawEvent = this._getRawEventFromRequest(body); return this._getChannelId(rawEvent) || this._getUserId(rawEvent); } async updateSession(session: Session, body: SlackRequestBody): Promise<void> { if (this._isBotEventRequest(body)) { return; } const rawEvent = this._getRawEventFromRequest(body); const userId = this._getUserId(rawEvent); const channelId = this._getChannelId(rawEvent); if ( typeof session.user === 'object' && session.user && session.user.id && session.user.id === userId ) { return; } if (!userId) { return; } if (this._skipLegacyProfile) { session.user = { id: userId, _updatedAt: new Date().toISOString(), }; session.channel = { id: channelId, _updatedAt: new Date().toISOString(), }; Object.freeze(session.user); Object.defineProperty(session, 'user', { configurable: false, enumerable: true, writable: false, value: session.user, }); Object.freeze(session.channel); Object.defineProperty(session, 'channel', { configurable: false, enumerable: true, writable: false, value: session.channel, }); return; } const promises: Record<string, any> = { sender: this._client.getUserInfo(userId), }; // TODO: check join or leave events? if ( !session.channel || (session.channel.members && Array.isArray(session.channel.members) && session.channel.members.indexOf(userId) < 0) ) { if (channelId) { promises.channel = this._client.getConversationInfo(channelId); promises.channelMembers = this._client.getAllConversationMembers(channelId); } } // TODO: how to know if user leave team? // TODO: team info shared by all channels? if ( !session.team || (session.team.members && Array.isArray(session.team.members) && session.team.members.indexOf(userId) < 0) ) { promises.allUsers = this._client.getAllUserList(); } const results = await pProps(promises); // FIXME: refine user session.user = { id: userId, _updatedAt: new Date().toISOString(), ...results.sender, }; Object.freeze(session.user); Object.defineProperty(session, 'user', { configurable: false, enumerable: true, writable: false, value: session.user, }); if (promises.channel) { session.channel = { ...results.channel, members: results.channelMembers, _updatedAt: new Date().toISOString(), }; Object.freeze(session.channel); Object.defineProperty(session, 'channel', { configurable: false, enumerable: true, writable: false, value: session.channel, }); } if (promises.allUsers) { session.team = { members: results.allUsers, _updatedAt: new Date().toISOString(), }; Object.freeze(session.team); Object.defineProperty(session, 'team', { configurable: false, enumerable: true, writable: false, value: session.team, }); } } mapRequestToEvents(body: SlackRequestBody): SlackEvent[] { const rawEvent = this._getRawEventFromRequest(body); if (!this._includeBotMessages && this._isBotEventRequest(body)) { return []; } return [new SlackEvent(rawEvent)]; } createContext(params: { event: SlackEvent; session: Session | null; initialState?: JsonObject | null; requestContext?: RequestContext; emitter?: EventEmitter | null; }): SlackContext { return new SlackContext({ ...params, client: this._client, }); } verifySignature(tokenFromBody: string): boolean { const bufferFromBot = Buffer.from(this._verificationToken); const bufferFromBody = Buffer.from(tokenFromBody); // return early here if buffer lengths are not equal since timingSafeEqual // will throw if buffer lengths are not equal if (bufferFromBot.length !== bufferFromBody.length) { return false; } return crypto.timingSafeEqual(bufferFromBot, bufferFromBody); } verifySignatureBySigningSecret({ rawBody, signature, timestamp, }: { rawBody: string; signature: string; timestamp: string; }): boolean { // ignore this request if the timestamp is 5 more minutes away from now const FIVE_MINUTES_IN_MILLISECONDS = 5 * 1000 * 60; if ( Math.abs(Date.now() - Number(timestamp) * 1000) > FIVE_MINUTES_IN_MILLISECONDS ) { return false; } const SIGNATURE_VERSION = 'v0'; // currently it's always 'v0' const signatureBaseString = `${SIGNATURE_VERSION}:${timestamp}:${rawBody}`; const digest = crypto .createHmac('sha256', this._signingSecret) .update(signatureBaseString, 'utf8') .digest('hex'); const calculatedSignature = `${SIGNATURE_VERSION}=${digest}`; return crypto.timingSafeEqual( Buffer.from(signature, 'utf8'), Buffer.from(calculatedSignature, 'utf8') ); } preprocess({ method, headers, body, rawBody, }: { method: string; headers: Record<string, string>; query: Record<string, string>; rawBody: string; body: Record<string, any>; }) { if (method.toLowerCase() !== 'post') { return { shouldNext: true, }; } const timestamp = headers['x-slack-request-timestamp']; const signature = headers['x-slack-signature']; if ( this._signingSecret && !this.verifySignatureBySigningSecret({ rawBody, timestamp, signature, }) ) { const error = { message: 'Slack Signing Secret Validation Failed!', request: { body, }, }; return { shouldNext: false, response: { status: 400, body: { error }, }, }; } const token = !body.token && body.payload && typeof body.payload === 'string' ? JSON.parse(body.payload).token : body.token; if (this._verificationToken && !this.verifySignature(token)) { const error = { message: 'Slack Verification Token Validation Failed!', request: { body, }, }; return { shouldNext: false, response: { status: 400, body: { error }, }, }; } if (body.type === 'url_verification') { return { shouldNext: false, response: { status: 200, body: body.challenge, }, }; } return { shouldNext: true, }; } }
the_stack
import { fakeAsync, tick } from '@angular/core/testing'; import { IonContent } from '@ionic/angular'; import { Spectator } from '@ngneat/spectator'; import { KirbyAnimation } from '../../../animation/kirby-animation'; import { TestHelper } from '../../../testing/test-helper'; import { IconComponent } from '../../icon/icon.component'; import { ModalWrapperComponent } from './modal-wrapper.component'; import { DynamicFooterEmbeddedComponent, DynamicPageProgressEmbeddedComponent, ModalWrapperTestBuilder, } from './modal-wrapper.testbuilder'; describe('ModalWrapperComponent', () => { const modalWrapperTestBuilder = new ModalWrapperTestBuilder(); let spectator: Spectator<ModalWrapperComponent>; it('should create', () => { spectator = modalWrapperTestBuilder.build(); expect(spectator.component).toBeTruthy(); // Ensure any observers are destroyed: spectator.fixture.destroy(); }); describe('title', () => { beforeEach(() => { spectator = modalWrapperTestBuilder .title('Test title') .flavor('modal') .build(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should render', () => { expect(spectator.component.config.title).toEqual('Test title'); }); it('should have css class "drawer" when drawer flavor is used', () => { spectator.component.config.flavor = 'drawer'; spectator.detectChanges(); const rootElement: HTMLElement = spectator.element; expect(rootElement.classList).toContain('drawer'); }); it('should have font size "m" when drawer flavor is used', () => { spectator.component.config.flavor = 'drawer'; spectator.detectChanges(); const rootElement: HTMLElement = spectator.element; const title = rootElement.querySelector('ion-title'); expect(window.getComputedStyle(title).fontSize).toEqual('18px'); }); }); describe('sizing', () => { beforeEach(() => { spectator = modalWrapperTestBuilder .flavor('modal') .withEmbeddedInputComponent() .build(); }); afterEach(() => { spectator.fixture.destroy(); }); it('should observe Ionic modal-wrapper intersecting with viewport after ion-modal has been presented', async () => { const observeSpy = spyOn(spectator.component['intersectionObserver'], 'observe'); spectator.component['ionModalDidPresent'].complete(); await TestHelper.waitForTimeout(); const dummyWrapper = spectator.element.closest('.modal-wrapper'); expect(observeSpy).toHaveBeenCalledWith(dummyWrapper); }); it('should clean up intersection observer of Ionic modal-wrapper on destroy', async () => { const disconnectSpy = spyOn(spectator.component['intersectionObserver'], 'disconnect'); spectator.component['ionModalDidPresent'].complete(); await TestHelper.waitForTimeout(); spectator.component.ngOnDestroy(); expect(disconnectSpy).toHaveBeenCalled(); }); }); describe('viewportResize', () => { it('should emit when viewport is resized', async () => { spectator = modalWrapperTestBuilder.build(); await TestHelper.whenTrue(() => !!spectator.component['initialViewportHeight']); const viewportResizeSpy = spyOn(spectator.component['viewportResize'], 'next'); await TestHelper.resizeTestWindow(TestHelper.screensize.tablet); await TestHelper.whenTrue(() => spectator.component['viewportResized']); expect(viewportResizeSpy).toHaveBeenCalled(); }); afterAll(() => { TestHelper.resetTestWindow(); }); }); describe('with interact with background', () => { const elementHeight = 500; const elementWidth = 300; const screenSize = TestHelper.screensize.desktop; let scrollbarWidth = 0; beforeAll(async () => { await TestHelper.resizeTestWindow(screenSize); scrollbarWidth = window.innerWidth - document.documentElement.clientWidth; }); afterAll(() => { TestHelper.resetTestWindow(); }); describe('when flavor is modal', () => { beforeEach(() => { spectator = modalWrapperTestBuilder .flavor('modal') .interactWithBackground() .build(); spectator.element.style.height = `${elementHeight}px`; spectator.element.style.width = `${elementWidth}px`; spectator.element.style.overflow = 'hidden'; spectator.element.style.position = 'fixed'; // Use 'fixed' instead of 'absolute' to prevent test breaking if test window is scrolled spectator.element.style.bottom = '0'; spectator.element.style.left = `calc(50% - ${elementWidth / 2}px)`; // Simulate horizontally centered modal spectator.element.style.backgroundColor = 'charrtreuse'; // Add some background for easier debugging of test }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should NOT resize ion-modal to wrapper size after ion-modal has been presented', fakeAsync(() => { spectator.component['ionModalDidPresent'].next(); spectator.component['ionModalDidPresent'].complete(); tick(); const ionModalElement = spectator.component['ionModalElement']; expect(ionModalElement.style.top).toBe(''); expect(ionModalElement.style.left).toBe(''); expect(ionModalElement.style.right).toBe(''); })); it('should NOT resize ion-modal to wrapper size on viewport resize', fakeAsync(() => { spectator.component['viewportResize'].next(); spectator.component['viewportResize'].complete(); tick(); const ionModalElement = spectator.component['ionModalElement']; expect(ionModalElement.style.top).toBe(''); expect(ionModalElement.style.left).toBe(''); expect(ionModalElement.style.right).toBe(''); })); }); describe('when flavor is drawer', () => { beforeEach(() => { spectator = modalWrapperTestBuilder .flavor('drawer') .interactWithBackground() .build(); spectator.element.style.height = `${elementHeight}px`; spectator.element.style.width = `${elementWidth}px`; spectator.element.style.overflow = 'hidden'; spectator.element.style.position = 'fixed'; // Use 'fixed' instead of 'absolute' to prevent test breaking if test window is scrolled spectator.element.style.bottom = '0'; spectator.element.style.left = `calc(50% - ${elementWidth / 2}px)`; // Simulate horizontally centered modal spectator.element.style.backgroundColor = 'charrtreuse'; // Add some background for easier debugging of test }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should resize ion-modal to wrapper size after ion-modal has been presented', fakeAsync(() => { spectator.component['ionModalDidPresent'].next(); spectator.component['ionModalDidPresent'].complete(); tick(); const elementRect = spectator.element.getBoundingClientRect(); const expectedPosition = { top: parseInt(screenSize.height) - elementHeight, left: elementRect.left, right: parseInt(screenSize.width) - scrollbarWidth - elementRect.right, }; const ionModalElement = spectator.component['ionModalElement']; expect(ionModalElement.style.top).toBe(`${expectedPosition.top}px`); expect(ionModalElement.style.left).toBe(`${expectedPosition.left}px`); expect(ionModalElement.style.right).toBe(`${expectedPosition.right}px`); })); it('should resize ion-modal to wrapper size on viewport resize', fakeAsync(() => { spectator.component['viewportResize'].next(); spectator.component['viewportResize'].complete(); tick(); const elementRect = spectator.element.getBoundingClientRect(); const expectedPosition = { top: parseInt(screenSize.height) - elementHeight, left: elementRect.left, right: parseInt(screenSize.width) - scrollbarWidth - elementRect.right, }; const ionModalElement = spectator.component['ionModalElement']; expect(ionModalElement.style.top).toBe(`${expectedPosition.top}px`); expect(ionModalElement.style.left).toBe(`${expectedPosition.left}px`); expect(ionModalElement.style.right).toBe(`${expectedPosition.right}px`); })); }); }); describe('close button', () => { beforeEach(() => { spectator = modalWrapperTestBuilder.build(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should render as a close icon by default', () => { spectator.component.config.flavor = 'modal'; spectator.detectChanges(); var el = spectator.query(IconComponent); expect(el.name).toBe('close'); }); it("should render arrow-down when flavor is set to 'drawer'", () => { spectator.component.config.flavor = 'drawer'; spectator.detectChanges(); var el = spectator.query(IconComponent); expect(el.name).toBe('arrow-down'); }); }); describe('supplementary button', () => { beforeEach(() => { spectator = modalWrapperTestBuilder.build(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should not render if an icon was provided, but the flavor is modal', () => { spectator.component.config.flavor = 'modal'; spectator.component.config.drawerSupplementaryAction = { iconName: 'qr', action: undefined }; spectator.detectChanges(); const elements = spectator.queryAll(IconComponent); expect(elements.length).toBe(1); expect(elements[0].name).toBe('close'); }); it('should render as the provided icon when flavor is drawer', () => { spectator.component.config.flavor = 'drawer'; spectator.component.config.drawerSupplementaryAction = { iconName: 'qr', action: undefined }; spectator.detectChanges(); const elements = spectator.queryAll(IconComponent); expect(elements.length).toBe(2); expect(elements[0].name).toBe('arrow-down'); expect(elements[1].name).toBe('qr'); }); it('should invoke the provided callback on select', () => { spectator.component.config.flavor = 'drawer'; spectator.component.config.drawerSupplementaryAction = { iconName: 'qr', action: (_: any) => {}, }; spyOn(spectator.component.config.drawerSupplementaryAction, 'action'); spectator.detectChanges(); spectator.dispatchMouseEvent('ion-buttons[slot="end"] button[kirby-button]', 'click'); expect(spectator.component.config.drawerSupplementaryAction.action).toHaveBeenCalled(); }); }); describe('scrollToTop', () => { beforeEach(() => { spectator = modalWrapperTestBuilder.build(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should scroll to top with no scroll animation duration', () => { const ionContent: IonContent = spectator.query(IonContent); spyOn(ionContent, 'scrollToTop'); spectator.component.scrollToTop(); expect(ionContent.scrollToTop).toHaveBeenCalledWith(0); }); it('should scroll to top with provided scroll animation duration', () => { const animationDuration = KirbyAnimation.Duration.LONG; const ionContent: IonContent = spectator.query(IonContent); spyOn(ionContent, 'scrollToTop'); spectator.component.scrollToTop(animationDuration); expect(ionContent.scrollToTop).toHaveBeenCalledWith(animationDuration); }); }); describe('scrollToBottom', () => { beforeEach(() => { spectator = modalWrapperTestBuilder.build(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should scroll to bottom with no scroll animation duration', () => { const ionContent: IonContent = spectator.query(IonContent); spyOn(ionContent, 'scrollToBottom'); spectator.component.scrollToBottom(); expect(ionContent.scrollToBottom).toHaveBeenCalledWith(0); }); it('should scroll to bottom with provided scroll animation duration', () => { const animationDuration = KirbyAnimation.Duration.LONG; const ionContent: IonContent = spectator.query(IonContent); spyOn(ionContent, 'scrollToBottom'); spectator.component.scrollToBottom(animationDuration); expect(ionContent.scrollToBottom).toHaveBeenCalledWith(animationDuration); }); }); describe('disable scroll Y', () => { beforeEach(() => { spectator = modalWrapperTestBuilder.build(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should disable scroll Y', () => { const ionContent: IonContent = spectator.query(IonContent); spectator.component.scrollDisabled = true; expect(ionContent.scrollY).toBeFalse(); }); }); describe('with embedded page progress component', () => { describe('with static page progress', () => { beforeEach(() => { spectator = modalWrapperTestBuilder .flavor('modal') .withStaticPageProgress() .build(); spectator.detectComponentChanges(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should move embedded page progress to wrapper component', () => { const ionContentElement = spectator.query('ion-content'); const ionToolbarElement = spectator.query('ion-toolbar'); const embeddedComponentElement = ionContentElement.firstElementChild; const embeddedPageProgress = embeddedComponentElement.querySelector('kirby-page-progress'); const pageProgressAsIonToolbarChild = ionToolbarElement.querySelector( 'kirby-page-progress' ); expect(embeddedPageProgress).toBeNull(); expect(pageProgressAsIonToolbarChild).not.toBeNull(); }); }); describe('with dynamic page progress', () => { beforeEach(() => { spectator = modalWrapperTestBuilder .flavor('modal') .withDynamicPageProgress() .build(); spectator.detectComponentChanges(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should move embedded page progress to wrapper component when rendered', async () => { const pageProgressContent = spectator.element.querySelector('kirby-page-progress'); expect(pageProgressContent).toBeNull(); const embeddedComponent = spectator.query(DynamicPageProgressEmbeddedComponent); embeddedComponent.showPageProgress = true; spectator.detectChanges(); await TestHelper.waitForResizeObserver(); const ionContentElement = spectator.query('ion-content'); const ionToolbarElement = spectator.query('ion-toolbar'); const embeddedComponentElement = ionContentElement.firstElementChild; const embeddedPageProgress = embeddedComponentElement.querySelector('kirby-page-progress'); const pageProgressAsIonToolbarChild = ionToolbarElement.querySelector( 'kirby-page-progress' ); expect(embeddedPageProgress).toBeNull(); expect(pageProgressAsIonToolbarChild).not.toBeNull(); }); it('should remove embedded page progress content from wrapper component when not rendered', async () => { let pageProgress = spectator.element.querySelector('kirby-page-progress'); expect(pageProgress).toBeNull(); const embeddedComponent = spectator.query(DynamicPageProgressEmbeddedComponent); embeddedComponent.showPageProgress = true; spectator.detectChanges(); await TestHelper.waitForResizeObserver(); const ionToolbarElement = spectator.query('ion-toolbar'); let pageProgressAsIonToolbarChild = ionToolbarElement.querySelector('kirby-page-progress'); expect(pageProgressAsIonToolbarChild).not.toBeNull(); embeddedComponent.showPageProgress = false; spectator.detectChanges(); pageProgressAsIonToolbarChild = ionToolbarElement.querySelector('kirby-page-progress'); expect(pageProgressAsIonToolbarChild).toBeNull(); }); }); }); describe('with embedded component with static footer', () => { beforeEach(() => { spectator = modalWrapperTestBuilder.withStaticFooter().build(); spectator.detectChanges(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should move embedded footer to wrapper component', () => { const ionContentElement = spectator.query('ion-content'); const embeddedComponentElement = ionContentElement.firstElementChild; const embeddedFooter = embeddedComponentElement.querySelector('kirby-modal-footer'); expect(embeddedFooter).toBeNull(); const footerAsWrapperChild = spectator.element.querySelector(':scope > kirby-modal-footer'); expect(footerAsWrapperChild).not.toBeNull(); }); describe(`should set custom CSS property '--keyboard-offset' on embedded footer`, () => { const keyboardHeight = 400; it('to a value', () => { const kirbyModalFooter = spectator.element.querySelector<HTMLElement>( ':scope > kirby-modal-footer' ); spectator.component._onKeyboardShow(keyboardHeight); expect(kirbyModalFooter.style.getPropertyValue('--keyboard-offset')).toBeDefined(); }); it('to 0 when no keyboard overlap', () => { const kirbyModalFooter = spectator.element.querySelector(':scope > kirby-modal-footer'); spectator.element.style.position = 'fixed'; spectator.element.style.bottom = `${keyboardHeight + 200}px`; spectator.component._onKeyboardShow(keyboardHeight); const keyboardOverlap = 0; expect(kirbyModalFooter).toHaveStyle({ '--keyboard-offset': `${keyboardOverlap}px`, }); }); it('to value of overlap when keyboard overlaps partially', () => { const kirbyModalFooter = spectator.element.querySelector(':scope > kirby-modal-footer'); spectator.element.style.position = 'fixed'; spectator.element.style.bottom = `${keyboardHeight - 200}px`; spectator.component._onKeyboardShow(keyboardHeight); const keyboardOverlap = 200; expect(kirbyModalFooter).toHaveStyle({ '--keyboard-offset': `${keyboardOverlap}px`, }); }); it('to keyboard height when keyboard overlaps completely', () => { const kirbyModalFooter = spectator.element.querySelector(':scope > kirby-modal-footer'); spectator.element.style.position = 'fixed'; spectator.element.style.bottom = '0px'; spectator.component._onKeyboardShow(keyboardHeight); const keyboardOverlap = keyboardHeight; expect(kirbyModalFooter).toHaveStyle({ '--keyboard-offset': `${keyboardOverlap}px`, }); }); }); }); describe('with embedded component with dynamic footer', () => { beforeEach(() => { spectator = modalWrapperTestBuilder .flavor('modal') .withDynamicFooter() .build(); spectator.detectComponentChanges(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should move embedded footer to wrapper component when rendered', async () => { const footer = spectator.element.querySelector('kirby-modal-footer'); expect(footer).toBeNull(); const embeddedComponent = spectator.query(DynamicFooterEmbeddedComponent); embeddedComponent.showFooter = true; spectator.detectChanges(); await TestHelper.waitForResizeObserver(); const ionContentElement = spectator.query('ion-content'); const embeddedComponentElement = ionContentElement.firstElementChild; const embeddedFooter = embeddedComponentElement.querySelector('kirby-modal-footer'); expect(embeddedFooter).toBeNull(); const footerAsWrapperChild = spectator.element.querySelector(':scope > kirby-modal-footer'); expect(footerAsWrapperChild).not.toBeNull(); }); it('should remove embedded footer from wrapper component when not rendered', async () => { let footer = spectator.element.querySelector('kirby-modal-footer'); expect(footer).toBeNull(); const embeddedComponent = spectator.query(DynamicFooterEmbeddedComponent); embeddedComponent.showFooter = true; spectator.detectChanges(); await TestHelper.waitForResizeObserver(); const footerAsWrapperChild = spectator.element.querySelector(':scope > kirby-modal-footer'); expect(footerAsWrapperChild).not.toBeNull(); embeddedComponent.showFooter = false; spectator.detectChanges(); footer = spectator.element.querySelector('kirby-modal-footer'); expect(footer).toBeNull(); }); it('should render changes to embedded footer inside wrapper component', async () => { const footer = spectator.element.querySelector('kirby-modal-footer'); expect(footer).not.toHaveClass('enabled'); const embeddedComponent = spectator.query(DynamicFooterEmbeddedComponent); embeddedComponent.showFooter = true; spectator.detectChanges(); await TestHelper.waitForResizeObserver(); const ionContentElement = spectator.query('ion-content'); const embeddedComponentElement = ionContentElement.firstElementChild; const embeddedFooter = embeddedComponentElement.querySelector('kirby-modal-footer'); expect(embeddedFooter).toBeNull(); const footerAsWrapperChild = spectator.element.querySelector(':scope > kirby-modal-footer'); expect(footerAsWrapperChild).not.toBeNull(); embeddedComponent.isEnabled = true; spectator.detectChanges(); expect(footerAsWrapperChild).toHaveClass('enabled'); }); describe(`should set custom CSS property '--keyboard-offset' on embedded footer`, () => { const keyboardHeight = 400; beforeEach(async () => { const embeddedComponent = spectator.query(DynamicFooterEmbeddedComponent); embeddedComponent.showFooter = true; spectator.detectChanges(); await TestHelper.waitForResizeObserver(); TestHelper.scrollMainWindowToTop(); }); it('to a value', () => { const kirbyModalFooter = spectator.element.querySelector<HTMLElement>( ':scope > kirby-modal-footer' ); spectator.component._onKeyboardShow(keyboardHeight); expect(kirbyModalFooter.style.getPropertyValue('--keyboard-offset')).toBeDefined(); }); it('to 0 when no keyboard overlap', () => { const kirbyModalFooter = spectator.element.querySelector(':scope > kirby-modal-footer'); spectator.element.style.position = 'fixed'; spectator.element.style.bottom = `${keyboardHeight + 200}px`; spectator.component._onKeyboardShow(keyboardHeight); const keyboardOverlap = 0; expect(kirbyModalFooter).toHaveStyle({ '--keyboard-offset': `${keyboardOverlap}px`, }); }); it('to value of overlap when keyboard overlaps partially', () => { const kirbyModalFooter = spectator.element.querySelector(':scope > kirby-modal-footer'); spectator.element.style.position = 'fixed'; spectator.element.style.bottom = `${keyboardHeight - 200}px`; spectator.component._onKeyboardShow(keyboardHeight); const keyboardOverlap = 200; expect(kirbyModalFooter).toHaveStyle({ '--keyboard-offset': `${keyboardOverlap}px`, }); }); it('to keyboard height when keyboard overlaps completely', () => { const kirbyModalFooter = spectator.element.querySelector(':scope > kirby-modal-footer'); spectator.element.style.position = 'fixed'; spectator.element.style.bottom = '0px'; spectator.component._onKeyboardShow(keyboardHeight); const keyboardOverlap = keyboardHeight; expect(kirbyModalFooter).toHaveStyle({ '--keyboard-offset': `${keyboardOverlap}px`, }); }); }); }); describe(`on keyboard show/hide events`, () => { beforeEach(() => { spectator = modalWrapperTestBuilder.build(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it('should set keyboardVisible to true on window:keyboardWillShow', () => { const keyboardWillShowEvent = new CustomEvent('keyboardWillShow'); keyboardWillShowEvent['keyboardHeight'] = 200; window.dispatchEvent(keyboardWillShowEvent); expect(spectator.component['keyboardVisible']).toBeTrue(); }); it('should set keyboardVisible to true on window:ionKeyboardDidShow', () => { const ionKeyboardDidShowEvent = new CustomEvent('ionKeyboardDidShow', { detail: { keyboardHeight: 200 }, }); window.dispatchEvent(ionKeyboardDidShowEvent); expect(spectator.component['keyboardVisible']).toBeTrue(); }); it('should set keyboardVisible to false on window:keyboardWillHide', () => { spectator.component['keyboardVisible'] = true; spectator.dispatchFakeEvent(window, 'keyboardWillHide'); expect(spectator.component['keyboardVisible']).toBeFalse(); }); it('should set keyboardVisible to false on window:ionKeyboardDidHide', () => { spectator.component['keyboardVisible'] = true; spectator.dispatchFakeEvent(window, 'ionKeyboardDidHide'); expect(spectator.component['keyboardVisible']).toBeFalse(); }); it('should keep same height, when keyboard is opened', async () => { const heightWhenKeyboardClosed = spectator.element.getBoundingClientRect().height; const ionKeyboardDidShowEvent = new CustomEvent('ionKeyboardDidShow', { detail: { keyboardHeight: 200 }, }); window.dispatchEvent(ionKeyboardDidShowEvent); expect(spectator.component['keyboardVisible']).toBeTrue(); const heightWhenKeyboardOpened = spectator.element.getBoundingClientRect().height; expect(heightWhenKeyboardClosed).toEqual(heightWhenKeyboardOpened); }); }); describe(`onHeaderTouchStart`, () => { let ionContent: HTMLIonContentElement; let input: HTMLInputElement; beforeEach(async () => { spectator = modalWrapperTestBuilder .flavor('drawer') .withEmbeddedInputComponent() .build(); // Ensure ion-content gets height // or embedded component won't be visible: spectator.element.classList.add('ion-page'); ionContent = spectator.query('ion-content'); // If other test specs have imported IonicModule before this test is run, // then Ionic components won't be mocked - so ensure ionContent.componentOnReady is run if exists: await TestHelper.ionComponentOnReady(ionContent); input = ionContent.querySelector('input'); spyOn(input, 'blur'); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); describe(`when keyboard is NOT visible`, () => { beforeEach(() => { expect(document.activeElement).not.toEqual(input); spectator.dispatchFakeEvent(window, 'keyboardWillHide'); }); it('should not call blurActiveElement', () => { const blurActiveElementSpy = spyOn(spectator.component, 'blurActiveElement'); spectator.dispatchTouchEvent('ion-header', 'touchstart'); expect(blurActiveElementSpy).not.toHaveBeenCalled(); }); }); describe(`when keyboard is visible`, () => { beforeEach(() => { input.focus(); expect(document.activeElement).toEqual(input); spectator.component['_onKeyboardShow'](200); }); it('should blur document.activeElement when it is an input', () => { spectator.dispatchTouchEvent('ion-header', 'touchstart'); expect(input.blur).toHaveBeenCalled(); }); it('should blur document.activeElement when it is a textarea', () => { const textarea = ionContent.querySelector('textarea'); spyOn(textarea, 'blur'); textarea.focus(); expect(document.activeElement).toEqual(textarea); spectator.dispatchTouchEvent('ion-header', 'touchstart'); expect(textarea.blur).toHaveBeenCalled(); }); it('should not blur document.activeElement if not input or textarea', () => { const button = ionContent.querySelector('button'); button.focus(); expect(document.activeElement).toEqual(button); spectator.dispatchTouchEvent('ion-header', 'touchstart'); expect(input.blur).not.toHaveBeenCalled(); }); it('should not blur document.activeElement if event is from toolbar button', () => { spectator.dispatchTouchEvent( 'ion-header > ion-toolbar > ion-buttons > button', 'touchstart' ); expect(input.blur).not.toHaveBeenCalled(); }); it('should not blur document.activeElement if event is from toolbar button child node', () => { spectator.dispatchTouchEvent( 'ion-header > ion-toolbar > ion-buttons > button > kirby-icon', 'touchstart' ); expect(input.blur).not.toHaveBeenCalled(); }); }); }); describe(`close()`, () => { beforeEach(() => { spectator = modalWrapperTestBuilder.withEmbeddedInputComponent().build(); }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); }); it(`should call wrapping ion-modal's dismiss() method immediately`, () => { spectator.component.close('test data'); expect(spectator.component['ionModalElement'].dismiss).toHaveBeenCalledWith('test data'); }); describe(`when keyboard is visible`, () => { beforeEach(() => { spectator.component['keyboardVisible'] = true; }); describe(`and viewport is not resized`, () => { it(`should call wrapping ion-modal's dismiss() method immediately`, () => { spectator.component.close('test data'); expect(spectator.component['ionModalElement'].dismiss).toHaveBeenCalledWith('test data'); }); }); describe(`and viewport is resized`, () => { beforeEach(async () => { // Ensure resizeObserver triggers and initialViewportHeight is set: await TestHelper.waitForResizeObserver(); await TestHelper.whenTrue(() => !!spectator.component['initialViewportHeight']); expect(spectator.component['initialViewportHeight']).toBeGreaterThan(0); const keyboardHeight = 300; //Mimic native keyboard taking height of window: const heightWidthKeyboard = window.innerHeight - keyboardHeight; console.log( `Mimic native keyboard: (window.innerHeight - keyboardHeight) = (${window.innerHeight} - ${keyboardHeight}) = ${heightWidthKeyboard}px` ); await TestHelper.resizeTestWindow({ height: `${window.innerHeight - keyboardHeight}px` }); // Ensure resizeObserver triggers and onViewportResize fires: await TestHelper.waitForResizeObserver(); await TestHelper.whenTrue(() => spectator.component['viewportResized']); // Ensure keyboardVisible is true, as Ionic dispatches 'ionKeyboardDidShow' event on viewport resize: spectator.component['keyboardVisible'] = true; }); afterEach(() => { // Ensure any observers are destroyed: spectator.fixture.destroy(); TestHelper.resetTestWindow(); }); it(`should blur document.activeElement before calling wrapping ion-modal's dismiss() method`, fakeAsync(() => { const ionContent = spectator.query('ion-content'); // If other test specs have imported IonicModule before this test is run, // then Ionic components won't be mocked - so ensure ionContent.componentOnReady is run if exists: TestHelper.ionComponentOnReady(ionContent); const input = ionContent.querySelector('input'); spyOn(input, 'blur'); input.focus(); expect(document.activeElement).toEqual(input); spectator.component.close('test data'); expect(spectator.component['ionModalElement'].dismiss).not.toHaveBeenCalled(); expect(input.blur).toHaveBeenCalled(); tick(ModalWrapperComponent.KEYBOARD_HIDE_DELAY_IN_MS); expect(spectator.component['ionModalElement'].dismiss).toHaveBeenCalledWith('test data'); })); it(`should delay before calling wrapping ion-modal's dismiss() method`, fakeAsync(() => { spectator.component.close('test data'); expect(spectator.component['ionModalElement'].dismiss).not.toHaveBeenCalled(); tick(ModalWrapperComponent.KEYBOARD_HIDE_DELAY_IN_MS); expect(spectator.component['ionModalElement'].dismiss).toHaveBeenCalledWith('test data'); })); }); }); }); });
the_stack