text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
describe('Tabs', () => {
beforeEach(() => {
cy.visit('/tabs');
})
describe('entry url - /tabs', () => {
it('should redirect and load tab-account', () => {
testTabTitle('Tab 1 - Page 1');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1']);
testState(1, 'account');
});
it('should navigate between tabs and ionChange events should be dispatched', () => {
let tab = testTabTitle('Tab 1 - Page 1');
tab.find('.segment-changed').should('have.text', 'false');
cy.get('#tab-button-contact').click();
tab = testTabTitle('Tab 2 - Page 1');
tab.find('.segment-changed').should('have.text', 'false');
});
describe('when navigating between tabs', () => {
it('should emit ionTabsWillChange before setting the selected tab', () => {
cy.get('#ionTabsWillChangeCounter').should('have.text', '1');
cy.get('#ionTabsWillChangeEvent').should('have.text', 'account');
cy.get('#ionTabsWillChangeSelectedTab').should('have.text', '');
cy.get('#ionTabsDidChangeCounter').should('have.text', '1');
cy.get('#ionTabsDidChangeEvent').should('have.text', 'account');
cy.get('#ionTabsDidChangeSelectedTab').should('have.text', 'account');
cy.get('#tab-button-contact').click();
cy.get('#ionTabsWillChangeCounter').should('have.text', '2');
cy.get('#ionTabsWillChangeEvent').should('have.text', 'contact');
cy.get('#ionTabsWillChangeSelectedTab').should('have.text', 'account');
cy.get('#ionTabsDidChangeCounter').should('have.text', '2');
cy.get('#ionTabsDidChangeEvent').should('have.text', 'contact');
cy.get('#ionTabsDidChangeSelectedTab').should('have.text', 'contact');
})
});
it('should simulate stack + double tab click', () => {
let tab = getSelectedTab();
tab.find('#goto-tab1-page2').click();
testTabTitle('Tab 1 - Page 2 (1)');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1', 'app-tabs-tab1-nested']);
testState(1, 'account');
// When you call find on tab above it changes the value of tab
// so we need to redefine it
tab = getSelectedTab();
tab.find('ion-back-button').should('be.visible');
cy.get('#tab-button-contact').click();
testTabTitle('Tab 2 - Page 1');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1', 'app-tabs-tab1-nested', 'app-tabs-tab2']);
testState(2, 'contact');
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 2 (1)');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1', 'app-tabs-tab1-nested', 'app-tabs-tab2']);
testState(3, 'account');
tab = getSelectedTab();
tab.find('ion-back-button').should('be.visible');
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 1');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1', 'app-tabs-tab2']);
testState(3, 'account');
});
it('should simulate stack + back button click', () => {
const tab = getSelectedTab();
tab.find('#goto-tab1-page2').click();
testTabTitle('Tab 1 - Page 2 (1)');
testState(1, 'account');
cy.get('#tab-button-contact').click();
testTabTitle('Tab 2 - Page 1');
testState(2, 'contact');
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 2 (1)');
testState(3, 'account');
cy.get('ion-back-button').click();
testTabTitle('Tab 1 - Page 1');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1', 'app-tabs-tab2']);
testState(3, 'account');
});
it('should navigate deep then go home', () => {
const tab = getSelectedTab();
tab.find('#goto-tab1-page2').click();
testTabTitle('Tab 1 - Page 2 (1)');
cy.get('#goto-next').click();
testTabTitle('Tab 1 - Page 2 (2)');
cy.get('#tab-button-contact').click();
testTabTitle('Tab 2 - Page 1');
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 2 (2)');
cy.testStack('ion-tabs ion-router-outlet', [
'app-tabs-tab1',
'app-tabs-tab1-nested',
'app-tabs-tab1-nested',
'app-tabs-tab2'
]);
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 1');
cy.testStack('ion-tabs ion-router-outlet', [
'app-tabs-tab1',
'app-tabs-tab2'
]);
});
it('should switch tabs and go back', () => {
cy.get('#tab-button-contact').click();
const tab = testTabTitle('Tab 2 - Page 1');
tab.find('#goto-tab1-page1').click();
testTabTitle('Tab 1 - Page 1');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1', 'app-tabs-tab2']);
});
it('should switch tabs and go to nested', () => {
cy.get('#tab-button-contact').click();
const tab = testTabTitle('Tab 2 - Page 1');
tab.find('#goto-tab1-page2').click();
testTabTitle('Tab 1 - Page 2 (1)');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab2', 'app-tabs-tab1-nested']);
});
it('should load lazy loaded tab', () => {
cy.get('#tab-button-lazy').click();
cy.ionPageVisible('app-tabs-tab3');
testTabTitle('Tab 3 - Page 1');
});
it('should use ion-back-button defaultHref', () => {
let tab = getSelectedTab();
tab.find('#goto-tab3-page2').click();
testTabTitle('Tab 3 - Page 2');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1', 'app-tabs-tab3-nested']);
tab = getSelectedTab();
tab.find('ion-back-button').click();
testTabTitle('Tab 3 - Page 1');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1', 'app-tabs-tab3']);
});
it('should preserve navigation extras when switching tabs', () => {
const expectUrlToContain = 'search=hello#fragment';
let tab = getSelectedTab();
tab.find('#goto-nested-page1-with-query-params').click();
testTabTitle('Tab 1 - Page 2 (1)');
testUrlContains(expectUrlToContain);
cy.get('#tab-button-contact').click();
testTabTitle('Tab 2 - Page 1');
cy.get('#tab-button-account').click();
tab = testTabTitle('Tab 1 - Page 2 (1)');
testUrlContains(expectUrlToContain);
});
it('should set root when clicking on an active tab to navigate to the root', () => {
const expectNestedTabUrlToContain = 'search=hello#fragment';
cy.url().then(url => {
const tab = getSelectedTab();
tab.find('#goto-nested-page1-with-query-params').click();
testTabTitle('Tab 1 - Page 2 (1)');
testUrlContains(expectNestedTabUrlToContain);
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 1');
testUrlEquals(url);
})
});
})
describe('entry tab contains navigation extras', () => {
const expectNestedTabUrlToContain = 'search=hello#fragment';
const rootUrlParams = 'test=123#rootFragment';
const rootUrl = `/tabs/account?${rootUrlParams}`;
beforeEach(() => {
cy.visit(rootUrl);
})
it('should preserve root url navigation extras when clicking on an active tab to navigate to the root', () => {
const tab = getSelectedTab();
tab.find('#goto-nested-page1-with-query-params').click();
testTabTitle('Tab 1 - Page 2 (1)');
testUrlContains(expectNestedTabUrlToContain);
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 1');
testUrlContains(rootUrl);
});
it('should preserve root url navigation extras when changing tabs', () => {
getSelectedTab();
cy.get('#tab-button-contact').click();
testTabTitle('Tab 2 - Page 1');
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 1');
testUrlContains(rootUrl);
});
it('should navigate deep then go home and preserve navigation extras', () => {
let tab = getSelectedTab();
tab.find('#goto-tab1-page2').click();
tab = testTabTitle('Tab 1 - Page 2 (1)');
tab.find('#goto-next').click();
testTabTitle('Tab 1 - Page 2 (2)');
cy.get('#tab-button-contact').click();
testTabTitle('Tab 2 - Page 1');
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 2 (2)');
cy.get('#tab-button-account').click();
testTabTitle('Tab 1 - Page 1');
testUrlContains(rootUrl);
});
})
describe('entry url - /tabs/account/nested/1', () => {
beforeEach(() => {
cy.visit('/tabs/account/nested/1');
})
it('should only display the back-button when there is a page in the stack', () => {
let tab = getSelectedTab();
tab.find('ion-back-button').should('not.be.visible');
testTabTitle('Tab 1 - Page 2 (1)');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1-nested']);
cy.get('#tab-button-account').click();
tab = testTabTitle('Tab 1 - Page 1');
tab.find('#goto-tab1-page2').click();
tab = testTabTitle('Tab 1 - Page 2 (1)');
tab.find('ion-back-button').should('be.visible');
});
it('should not reuse the same page', () => {
let tab = testTabTitle('Tab 1 - Page 2 (1)');
tab.find('#goto-next').click();
tab = testTabTitle('Tab 1 - Page 2 (2)');
tab.find('#goto-next').click();
tab = testTabTitle('Tab 1 - Page 2 (3)');
cy.testStack('ion-tabs ion-router-outlet', [
'app-tabs-tab1-nested',
'app-tabs-tab1-nested',
'app-tabs-tab1-nested'
]);
tab = getSelectedTab();
tab.find('ion-back-button').click();
tab = testTabTitle('Tab 1 - Page 2 (2)');
tab.find('ion-back-button').click();
tab = testTabTitle('Tab 1 - Page 2 (1)');
tab.find('ion-back-button').should('not.be.visible');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab1-nested']);
});
})
describe('entry url - /tabs/lazy', () => {
beforeEach(() => {
cy.visit('/tabs/lazy');
});
it('should not display the back-button if coming from a different stack', () => {
let tab = testTabTitle('Tab 3 - Page 1');
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab3']);
tab = getSelectedTab();
tab.find('#goto-tab1-page2').click();
cy.testStack('ion-tabs ion-router-outlet', ['app-tabs-tab3', 'app-tabs-tab1-nested']);
tab = testTabTitle('Tab 1 - Page 2 (1)');
tab.find('ion-back-button').should('not.be.visible');
});
})
describe('enter url - /tabs/contact/one', () => {
beforeEach(() => {
cy.visit('/tabs/contact/one');
});
it('should return to correct tab after going to page in different outlet', () => {
const tab = getSelectedTab();
tab.find('#goto-nested-page1').click();
cy.testStack('app-nested-outlet ion-router-outlet', ['app-nested-outlet-page']);
const nestedOutlet = cy.get('app-nested-outlet');
nestedOutlet.find('ion-back-button').click();
testTabTitle('Tab 2 - Page 1');
});
})
})
function testTabTitle(title) {
const tab = getSelectedTab();
// Find is used to get a direct descendant instead of get
tab.find('ion-title').should('have.text', title);
return getSelectedTab();
}
function getSelectedTab() {
cy.get('ion-tabs ion-router-outlet > *:not(.ion-page-hidden)').should('have.length', 1);
return cy.get('ion-tabs ion-router-outlet > *:not(.ion-page-hidden)').first();
}
function testState(count, tab) {
cy.get('#tabs-state').should('have.text', `${count}.${tab}`);
}
function testUrlContains(urlFragment) {
cy.location().should((location) => {
expect(location.href).to.contain(urlFragment);
});
}
function testUrlEquals(url) {
cy.url().should('eq', url);
} | the_stack |
export { /*class*/ b2BlockAllocator as BlockAllocator } from "./common/b2_block_allocator.js";
export { /*abstract class*/ b2Draw as Draw } from "./common/b2_draw.js";
export { /*class*/ b2Color as Color } from "./common/b2_draw.js";
export { /*enum*/ b2DrawFlags as DrawFlags } from "./common/b2_draw.js";
export { /*interface*/ RGB as RGB } from "./common/b2_draw.js";
export { /*interface*/ RGBA as RGBA } from "./common/b2_draw.js";
export { /*class*/ b2GrowableStack as GrowableStack } from "./common/b2_growable_stack.js";
export { /*class*/ b2Mat22 as Mat22 } from "./common/b2_math.js";
export { /*class*/ b2Mat33 as Mat33 } from "./common/b2_math.js";
export { /*class*/ b2Rot as Rot } from "./common/b2_math.js";
export { /*class*/ b2Sweep as Sweep } from "./common/b2_math.js";
export { /*class*/ b2Transform as Transform } from "./common/b2_math.js";
export { /*class*/ b2Vec2 as Vec2 } from "./common/b2_math.js";
export { /*class*/ b2Vec3 as Vec3 } from "./common/b2_math.js";
export { /*const*/ b2_pi_over_180 as _pi_over_180 } from "./common/b2_math.js";
export { /*const*/ b2_180_over_pi as _180_over_pi } from "./common/b2_math.js";
export { /*const*/ b2_two_pi as two_pi } from "./common/b2_math.js";
export { /*const*/ b2Abs as Abs } from "./common/b2_math.js";
export { /*const*/ b2Acos as Acos } from "./common/b2_math.js";
export { /*const*/ b2Asin as Asin } from "./common/b2_math.js";
export { /*const*/ b2Atan2 as Atan2 } from "./common/b2_math.js";
export { /*const*/ b2Cos as Cos } from "./common/b2_math.js";
export { /*const*/ b2IsValid as IsValid } from "./common/b2_math.js";
export { /*const*/ b2Pow as Pow } from "./common/b2_math.js";
export { /*const*/ b2Sin as Sin } from "./common/b2_math.js";
export { /*const*/ b2Sqrt as Sqrt } from "./common/b2_math.js";
export { /*const*/ b2Vec2_zero as Vec2_zero } from "./common/b2_math.js";
export { /*function*/ b2Clamp as Clamp } from "./common/b2_math.js";
export { /*function*/ b2DegToRad as DegToRad } from "./common/b2_math.js";
export { /*function*/ b2InvSqrt as InvSqrt } from "./common/b2_math.js";
export { /*function*/ b2IsPowerOfTwo as IsPowerOfTwo } from "./common/b2_math.js";
export { /*function*/ b2Max as Max } from "./common/b2_math.js";
export { /*function*/ b2Min as Min } from "./common/b2_math.js";
export { /*function*/ b2NextPowerOfTwo as NextPowerOfTwo } from "./common/b2_math.js";
export { /*function*/ b2RadToDeg as RadToDeg } from "./common/b2_math.js";
export { /*function*/ b2Random as Random } from "./common/b2_math.js";
export { /*function*/ b2RandomRange as RandomRange } from "./common/b2_math.js";
export { /*function*/ b2Sq as Sq } from "./common/b2_math.js";
export { /*function*/ b2Swap as Swap } from "./common/b2_math.js";
export { /*interface*/ XY as XY } from "./common/b2_math.js";
export { /*interface*/ XYZ as XYZ } from "./common/b2_math.js";
export { /*class*/ b2Version as Version } from "./common/b2_settings.js";
export { /*const*/ b2_aabbExtension as aabbExtension } from "./common/b2_settings.js";
export { /*const*/ b2_aabbMultiplier as aabbMultiplier } from "./common/b2_settings.js";
export { /*const*/ b2_angularSleepTolerance as angularSleepTolerance } from "./common/b2_settings.js";
export { /*const*/ b2_angularSlop as angularSlop } from "./common/b2_settings.js";
export { /*const*/ b2_barrierCollisionTime as barrierCollisionTime } from "./common/b2_settings.js";
export { /*const*/ b2_baumgarte as baumgarte } from "./common/b2_settings.js";
export { /*const*/ b2_branch as branch } from "./common/b2_settings.js";
export { /*const*/ b2_commit as commit } from "./common/b2_settings.js";
export { /*const*/ b2_epsilon as epsilon } from "./common/b2_settings.js";
export { /*const*/ b2_epsilon_sq as epsilon_sq } from "./common/b2_settings.js";
export { /*const*/ b2_invalidParticleIndex as invalidParticleIndex } from "./common/b2_settings.js";
export { /*const*/ b2_lengthUnitsPerMeter as lengthUnitsPerMeter } from "./common/b2_settings.js";
export { /*const*/ b2_linearSleepTolerance as linearSleepTolerance } from "./common/b2_settings.js";
export { /*const*/ b2_linearSlop as linearSlop } from "./common/b2_settings.js";
export { /*const*/ b2_maxAngularCorrection as maxAngularCorrection } from "./common/b2_settings.js";
export { /*const*/ b2_maxFloat as maxFloat } from "./common/b2_settings.js";
export { /*const*/ b2_maxLinearCorrection as maxLinearCorrection } from "./common/b2_settings.js";
export { /*const*/ b2_maxManifoldPoints as maxManifoldPoints } from "./common/b2_settings.js";
export { /*const*/ b2_maxParticleForce as maxParticleForce } from "./common/b2_settings.js";
export { /*const*/ b2_maxParticleIndex as maxParticleIndex } from "./common/b2_settings.js";
export { /*const*/ b2_maxParticlePressure as maxParticlePressure } from "./common/b2_settings.js";
export { /*const*/ b2_maxPolygonVertices as maxPolygonVertices } from "./common/b2_settings.js";
export { /*const*/ b2_maxRotation as maxRotation } from "./common/b2_settings.js";
export { /*const*/ b2_maxRotationSquared as maxRotationSquared } from "./common/b2_settings.js";
export { /*const*/ b2_maxSubSteps as maxSubSteps } from "./common/b2_settings.js";
export { /*const*/ b2_maxTOIContacts as maxTOIContacts } from "./common/b2_settings.js";
export { /*const*/ b2_maxTranslation as maxTranslation } from "./common/b2_settings.js";
export { /*const*/ b2_maxTranslationSquared as maxTranslationSquared } from "./common/b2_settings.js";
export { /*const*/ b2_maxTriadDistance as maxTriadDistance } from "./common/b2_settings.js";
export { /*const*/ b2_maxTriadDistanceSquared as maxTriadDistanceSquared } from "./common/b2_settings.js";
export { /*const*/ b2_minParticleSystemBufferCapacity as minParticleSystemBufferCapacity } from "./common/b2_settings.js";
export { /*const*/ b2_minParticleWeight as minParticleWeight } from "./common/b2_settings.js";
export { /*const*/ b2_particleStride as particleStride } from "./common/b2_settings.js";
export { /*const*/ b2_pi as pi } from "./common/b2_settings.js";
export { /*const*/ b2_polygonRadius as polygonRadius } from "./common/b2_settings.js";
export { /*const*/ b2_timeToSleep as timeToSleep } from "./common/b2_settings.js";
export { /*const*/ b2_toiBaumgarte as toiBaumgarte } from "./common/b2_settings.js";
export { /*const*/ b2_version as version } from "./common/b2_settings.js";
export { /*function*/ b2Alloc as Alloc } from "./common/b2_settings.js";
export { /*function*/ b2Assert as Assert } from "./common/b2_settings.js";
export { /*function*/ b2Free as Free } from "./common/b2_settings.js";
export { /*function*/ b2Log as Log } from "./common/b2_settings.js";
export { /*function*/ b2MakeArray as MakeArray } from "./common/b2_settings.js";
export { /*function*/ b2MakeNullArray as MakeNullArray } from "./common/b2_settings.js";
export { /*function*/ b2MakeNumberArray as MakeNumberArray } from "./common/b2_settings.js";
export { /*function*/ b2Maybe as Maybe } from "./common/b2_settings.js";
export { /*function*/ b2ParseInt as ParseInt } from "./common/b2_settings.js";
export { /*function*/ b2ParseUInt as ParseUInt } from "./common/b2_settings.js";
export { /*class*/ b2StackAllocator as StackAllocator } from "./common/b2_stack_allocator.js";
export { /*class*/ b2Counter as Counter } from "./common/b2_timer.js";
export { /*class*/ b2Timer as Timer } from "./common/b2_timer.js";
export { /*class*/ b2BroadPhase as BroadPhase } from "./collision/b2_broad_phase.js";
export { /*class*/ b2Pair as Pair } from "./collision/b2_broad_phase.js";
export { /*class*/ b2ChainShape as ChainShape } from "./collision/b2_chain_shape.js";
export { /*class*/ b2CircleShape as CircleShape } from "./collision/b2_circle_shape.js";
export { /*function*/ b2CollideCircles as CollideCircles } from "./collision/b2_collide_circle.js";
export { /*function*/ b2CollidePolygonAndCircle as CollidePolygonAndCircle } from "./collision/b2_collide_circle.js";
export { /*function*/ b2CollideEdgeAndCircle as CollideEdgeAndCircle } from "./collision/b2_collide_edge.js";
export { /*function*/ b2CollideEdgeAndPolygon as CollideEdgeAndPolygon } from "./collision/b2_collide_edge.js";
export { /*function*/ b2CollidePolygons as CollidePolygons } from "./collision/b2_collide_polygon.js";
export { /*class*/ b2AABB as AABB } from "./collision/b2_collision.js";
export { /*class*/ b2ClipVertex as ClipVertex } from "./collision/b2_collision.js";
export { /*class*/ b2ContactFeature as ContactFeature } from "./collision/b2_collision.js";
export { /*class*/ b2ContactID as ContactID } from "./collision/b2_collision.js";
export { /*class*/ b2Manifold as Manifold } from "./collision/b2_collision.js";
export { /*class*/ b2ManifoldPoint as ManifoldPoint } from "./collision/b2_collision.js";
export { /*class*/ b2RayCastInput as RayCastInput } from "./collision/b2_collision.js";
export { /*class*/ b2RayCastOutput as RayCastOutput } from "./collision/b2_collision.js";
export { /*class*/ b2WorldManifold as WorldManifold } from "./collision/b2_collision.js";
export { /*enum*/ b2ContactFeatureType as ContactFeatureType } from "./collision/b2_collision.js";
export { /*enum*/ b2ManifoldType as ManifoldType } from "./collision/b2_collision.js";
export { /*enum*/ b2PointState as PointState } from "./collision/b2_collision.js";
export { /*function*/ b2ClipSegmentToLine as ClipSegmentToLine } from "./collision/b2_collision.js";
export { /*function*/ b2GetPointStates as GetPointStates } from "./collision/b2_collision.js";
export { /*function*/ b2TestOverlapAABB as TestOverlapAABB } from "./collision/b2_collision.js";
export { /*function*/ b2TestOverlapShape as TestOverlapShape } from "./collision/b2_collision.js";
export { /*class*/ b2DistanceInput as DistanceInput } from "./collision/b2_distance.js";
export { /*class*/ b2DistanceOutput as DistanceOutput } from "./collision/b2_distance.js";
export { /*class*/ b2DistanceProxy as DistanceProxy } from "./collision/b2_distance.js";
export { /*class*/ b2ShapeCastInput as ShapeCastInput } from "./collision/b2_distance.js";
export { /*class*/ b2ShapeCastOutput as ShapeCastOutput } from "./collision/b2_distance.js";
export { /*class*/ b2Simplex as Simplex } from "./collision/b2_distance.js";
export { /*class*/ b2SimplexCache as SimplexCache } from "./collision/b2_distance.js";
export { /*class*/ b2SimplexVertex as SimplexVertex } from "./collision/b2_distance.js";
export { /*function*/ b2Distance as Distance } from "./collision/b2_distance.js";
export { /*function*/ b2_gjk_reset as gjk_reset } from "./collision/b2_distance.js";
export { /*function*/ b2ShapeCast as ShapeCast } from "./collision/b2_distance.js";
export { /*let*/ b2_gjkCalls as gjkCalls } from "./collision/b2_distance.js";
export { /*let*/ b2_gjkIters as gjkIters } from "./collision/b2_distance.js";
export { /*let*/ b2_gjkMaxIters as gjkMaxIters } from "./collision/b2_distance.js";
export { /*class*/ b2DynamicTree as DynamicTree } from "./collision/b2_dynamic_tree.js";
export { /*class*/ b2TreeNode as TreeNode } from "./collision/b2_dynamic_tree.js";
export { /*class*/ b2EdgeShape as EdgeShape } from "./collision/b2_edge_shape.js";
export { /*class*/ b2PolygonShape as PolygonShape } from "./collision/b2_polygon_shape.js";
export { /*abstract class*/ b2Shape as Shape } from "./collision/b2_shape.js";
export { /*class*/ b2MassData as MassData } from "./collision/b2_shape.js";
export { /*enum*/ b2ShapeType as ShapeType } from "./collision/b2_shape.js";
export { /*class*/ b2SeparationFunction as SeparationFunction } from "./collision/b2_time_of_impact.js";
export { /*class*/ b2TOIInput as TOIInput } from "./collision/b2_time_of_impact.js";
export { /*class*/ b2TOIOutput as TOIOutput } from "./collision/b2_time_of_impact.js";
export { /*enum*/ b2SeparationFunctionType as SeparationFunctionType } from "./collision/b2_time_of_impact.js";
export { /*enum*/ b2TOIOutputState as TOIOutputState } from "./collision/b2_time_of_impact.js";
export { /*function*/ b2TimeOfImpact as TimeOfImpact } from "./collision/b2_time_of_impact.js";
export { /*function*/ b2_toi_reset as toi_reset } from "./collision/b2_time_of_impact.js";
export { /*let*/ b2_toiCalls as toiCalls } from "./collision/b2_time_of_impact.js";
export { /*let*/ b2_toiIters as toiIters } from "./collision/b2_time_of_impact.js";
export { /*let*/ b2_toiMaxIters as toiMaxIters } from "./collision/b2_time_of_impact.js";
export { /*let*/ b2_toiMaxRootIters as toiMaxRootIters } from "./collision/b2_time_of_impact.js";
export { /*let*/ b2_toiMaxTime as toiMaxTime } from "./collision/b2_time_of_impact.js";
export { /*let*/ b2_toiRootIters as toiRootIters } from "./collision/b2_time_of_impact.js";
export { /*let*/ b2_toiTime as toiTime } from "./collision/b2_time_of_impact.js";
export { /*interface*/ b2IAreaJointDef as IAreaJointDef } from "./dynamics/b2_area_joint.js";
export { /*class*/ b2AreaJointDef as AreaJointDef } from "./dynamics/b2_area_joint.js";
export { /*class*/ b2AreaJoint as AreaJoint } from "./dynamics/b2_area_joint.js";
export { /*class*/ b2Body as Body } from "./dynamics/b2_body.js";
export { /*interface*/ b2IBodyDef as IBodyDef } from "./dynamics/b2_body.js";
export { /*class*/ b2BodyDef as BodyDef } from "./dynamics/b2_body.js";
export { /*enum*/ b2BodyType as BodyType } from "./dynamics/b2_body.js";
import { b2BodyType } from "./dynamics/b2_body.js";
export const staticBody = b2BodyType.b2_staticBody;
export const kinematicBody = b2BodyType.b2_kinematicBody;
export const dynamicBody = b2BodyType.b2_dynamicBody;
export { /*class*/ b2ChainAndCircleContact as ChainAndCircleContact } from "./dynamics/b2_chain_circle_contact.js";
export { /*class*/ b2ChainAndPolygonContact as ChainAndPolygonContact } from "./dynamics/b2_chain_polygon_contact.js";
export { /*class*/ b2CircleContact as CircleContact } from "./dynamics/b2_circle_contact.js";
export { /*class*/ b2ContactFactory as ContactFactory } from "./dynamics/b2_contact_factory.js";
export { /*class*/ b2ContactRegister as ContactRegister } from "./dynamics/b2_contact_factory.js";
export { /*class*/ b2ContactManager as ContactManager } from "./dynamics/b2_contact_manager.js";
export { /*class*/ b2ContactPositionConstraint as ContactPositionConstraint } from "./dynamics/b2_contact_solver.js";
export { /*class*/ b2ContactSolver as ContactSolver } from "./dynamics/b2_contact_solver.js";
export { /*class*/ b2ContactSolverDef as ContactSolverDef } from "./dynamics/b2_contact_solver.js";
export { /*class*/ b2ContactVelocityConstraint as ContactVelocityConstraint } from "./dynamics/b2_contact_solver.js";
export { /*class*/ b2PositionSolverManifold as PositionSolverManifold } from "./dynamics/b2_contact_solver.js";
export { /*class*/ b2VelocityConstraintPoint as VelocityConstraintPoint } from "./dynamics/b2_contact_solver.js";
export { /*let*/ g_blockSolve as blockSolve } from "./dynamics/b2_contact_solver.js";
export { /*function*/ get_g_blockSolve as get_g_blockSolve } from "./dynamics/b2_contact_solver.js";
export { /*function*/ set_g_blockSolve as set_g_blockSolve } from "./dynamics/b2_contact_solver.js";
export { /*abstract class*/ b2Contact as Contact } from "./dynamics/b2_contact.js";
export { /*class*/ b2ContactEdge as ContactEdge } from "./dynamics/b2_contact.js";
export { /*function*/ b2MixFriction as MixFriction } from "./dynamics/b2_contact.js";
export { /*function*/ b2MixRestitution as MixRestitution } from "./dynamics/b2_contact.js";
export { /*function*/ b2MixRestitutionThreshold as MixRestitutionThreshold } from "./dynamics/b2_contact.js";
export { /*interface*/ b2IDistanceJointDef as IDistanceJointDef } from "./dynamics/b2_distance_joint.js";
export { /*class*/ b2DistanceJointDef as DistanceJointDef } from "./dynamics/b2_distance_joint.js";
export { /*class*/ b2DistanceJoint as DistanceJoint } from "./dynamics/b2_distance_joint.js";
export { /*class*/ b2EdgeAndCircleContact as EdgeAndCircleContact } from "./dynamics/b2_edge_circle_contact.js";
export { /*class*/ b2EdgeAndPolygonContact as EdgeAndPolygonContact } from "./dynamics/b2_edge_polygon_contact.js";
export { /*interface*/ b2IFilter as IFilter } from "./dynamics/b2_fixture.js";
export { /*class*/ b2Filter as Filter } from "./dynamics/b2_fixture.js";
export { /*class*/ b2Fixture as Fixture } from "./dynamics/b2_fixture.js";
export { /*interface*/ b2IFixtureDef as IFixtureDef } from "./dynamics/b2_fixture.js";
export { /*class*/ b2FixtureDef as FixtureDef } from "./dynamics/b2_fixture.js";
export { /*class*/ b2FixtureProxy as FixtureProxy } from "./dynamics/b2_fixture.js";
export { /*interface*/ b2IFrictionJointDef as IFrictionJointDef } from "./dynamics/b2_friction_joint.js";
export { /*class*/ b2FrictionJointDef as FrictionJointDef } from "./dynamics/b2_friction_joint.js";
export { /*class*/ b2FrictionJoint as FrictionJoint } from "./dynamics/b2_friction_joint.js";
export { /*interface*/ b2IGearJointDef as IGearJointDef } from "./dynamics/b2_gear_joint.js";
export { /*class*/ b2GearJointDef as GearJointDef } from "./dynamics/b2_gear_joint.js";
export { /*class*/ b2GearJoint as GearJoint } from "./dynamics/b2_gear_joint.js";
export { /*class*/ b2Island as Island } from "./dynamics/b2_island.js";
export { /*interface*/ b2IJointDef as IJointDef } from "./dynamics/b2_joint.js";
export { /*abstract class*/ b2JointDef as JointDef } from "./dynamics/b2_joint.js";
export { /*abstract class*/ b2Joint as Joint } from "./dynamics/b2_joint.js";
export { /*class*/ b2Jacobian as Jacobian } from "./dynamics/b2_joint.js";
export { /*class*/ b2JointEdge as JointEdge } from "./dynamics/b2_joint.js";
export { /*enum*/ b2JointType as JointType } from "./dynamics/b2_joint.js";
export { /*function*/ b2AngularStiffness as AngularStiffness } from "./dynamics/b2_joint.js";
export { /*function*/ b2LinearStiffness as LinearStiffness } from "./dynamics/b2_joint.js";
export { /*interface*/ b2IMotorJointDef as IMotorJointDef } from "./dynamics/b2_motor_joint.js";
export { /*class*/ b2MotorJointDef as MotorJointDef } from "./dynamics/b2_motor_joint.js";
export { /*class*/ b2MotorJoint as MotorJoint } from "./dynamics/b2_motor_joint.js";
export { /*interface*/ b2IMouseJointDef as IMouseJointDef } from "./dynamics/b2_mouse_joint.js";
export { /*class*/ b2MouseJointDef as MouseJointDef } from "./dynamics/b2_mouse_joint.js";
export { /*class*/ b2MouseJoint as MouseJoint } from "./dynamics/b2_mouse_joint.js";
export { /*class*/ b2PolygonAndCircleContact as PolygonAndCircleContact } from "./dynamics/b2_polygon_circle_contact.js";
export { /*class*/ b2PolygonContact as PolygonContact } from "./dynamics/b2_polygon_contact.js";
export { /*interface*/ b2IPrismaticJointDef as IPrismaticJointDef } from "./dynamics/b2_prismatic_joint.js";
export { /*class*/ b2PrismaticJointDef as PrismaticJointDef } from "./dynamics/b2_prismatic_joint.js";
export { /*class*/ b2PrismaticJoint as PrismaticJoint } from "./dynamics/b2_prismatic_joint.js";
export { /*interface*/ b2IPulleyJointDef as IPulleyJointDef } from "./dynamics/b2_pulley_joint.js";
export { /*class*/ b2PulleyJointDef as PulleyJointDef } from "./dynamics/b2_pulley_joint.js";
export { /*class*/ b2PulleyJoint as PulleyJoint } from "./dynamics/b2_pulley_joint.js";
export { /*const*/ b2_minPulleyLength as minPulleyLength } from "./dynamics/b2_pulley_joint.js";
export { /*interface*/ b2IRevoluteJointDef as IRevoluteJointDef } from "./dynamics/b2_revolute_joint.js";
export { /*class*/ b2RevoluteJointDef as RevoluteJointDef } from "./dynamics/b2_revolute_joint.js";
export { /*class*/ b2RevoluteJoint as RevoluteJoint } from "./dynamics/b2_revolute_joint.js";
export { /*class*/ b2Position as Position } from "./dynamics/b2_time_step.js";
export { /*class*/ b2Profile as Profile } from "./dynamics/b2_time_step.js";
export { /*class*/ b2SolverData as SolverData } from "./dynamics/b2_time_step.js";
export { /*class*/ b2TimeStep as TimeStep } from "./dynamics/b2_time_step.js";
export { /*class*/ b2Velocity as Velocity } from "./dynamics/b2_time_step.js";
export { /*interface*/ b2IWeldJointDef as IWeldJointDef } from "./dynamics/b2_weld_joint.js";
export { /*class*/ b2WeldJointDef as WeldJointDef } from "./dynamics/b2_weld_joint.js";
export { /*class*/ b2WeldJoint as WeldJoint } from "./dynamics/b2_weld_joint.js";
export { /*interface*/ b2IWheelJointDef as IWheelJointDef } from "./dynamics/b2_wheel_joint.js";
export { /*class*/ b2WheelJointDef as WheelJointDef } from "./dynamics/b2_wheel_joint.js";
export { /*class*/ b2WheelJoint as WheelJoint } from "./dynamics/b2_wheel_joint.js";
export { /*class*/ b2ContactFilter as ContactFilter } from "./dynamics/b2_world_callbacks.js";
export { /*class*/ b2ContactImpulse as ContactImpulse } from "./dynamics/b2_world_callbacks.js";
export { /*class*/ b2ContactListener as ContactListener } from "./dynamics/b2_world_callbacks.js";
export { /*class*/ b2DestructionListener as DestructionListener } from "./dynamics/b2_world_callbacks.js";
export { /*class*/ b2QueryCallback as QueryCallback } from "./dynamics/b2_world_callbacks.js";
export { /*class*/ b2RayCastCallback as RayCastCallback } from "./dynamics/b2_world_callbacks.js";
export { /*type*/ b2QueryCallbackFunction as QueryCallbackFunction } from "./dynamics/b2_world_callbacks.js";
export { /*type*/ b2RayCastCallbackFunction as RayCastCallbackFunction } from "./dynamics/b2_world_callbacks.js";
export { /*class*/ b2World as World } from "./dynamics/b2_world.js";
export { /*class*/ b2RopeDef as RopeDef } from "./rope/b2_rope.js";
export { /*class*/ b2Rope as Rope } from "./rope/b2_rope.js";
export { /*class*/ b2RopeTuning as RopeTuning } from "./rope/b2_rope.js";
export { /*enum*/ b2BendingModel as BendingModel } from "./rope/b2_rope.js";
import { b2BendingModel } from "./rope/b2_rope.js";
export const springAngleBendingModel = b2BendingModel.b2_springAngleBendingModel;
export const pbdAngleBendingModel = b2BendingModel.b2_pbdAngleBendingModel;
export const xpbdAngleBendingModel = b2BendingModel.b2_xpbdAngleBendingModel;
export const pbdDistanceBendingModel = b2BendingModel.b2_pbdDistanceBendingModel;
export const pbdHeightBendingModel = b2BendingModel.b2_pbdHeightBendingModel;
export const pbdTriangleBendingModel = b2BendingModel.b2_pbdTriangleBendingModel;
export { /*enum*/ b2StretchingModel as StretchingModel } from "./rope/b2_rope.js";
import { b2StretchingModel } from "./rope/b2_rope.js";
export const pbdStretchingModel = b2StretchingModel.b2_pbdStretchingModel;
export const xpbdStretchingModel = b2StretchingModel.b2_xpbdStretchingModel;
export { /*class*/ b2BuoyancyController as BuoyancyController } from "./controllers/b2_buoyancy_controller.js";
export { /*class*/ b2ConstantAccelController as ConstantAccelController } from "./controllers/b2_constant_accel_controller.js";
export { /*class*/ b2ConstantForceController as ConstantForceController } from "./controllers/b2_constant_force_controller.js";
export { /*abstract class*/ b2Controller as Controller } from "./controllers/b2_controller.js";
export { /*class*/ b2ControllerEdge as ControllerEdge } from "./controllers/b2_controller.js";
export { /*class*/ b2GravityController as GravityController } from "./controllers/b2_gravity_controller.js";
export { /*class*/ b2TensorDampingController as TensorDampingController } from "./controllers/b2_tensor_damping_controller.js";
export { /*class*/ b2ParticleGroup as ParticleGroup } from "./particle/b2_particle_group.js";
export { /*interface*/ b2IParticleGroupDef as IParticleGroupDef } from "./particle/b2_particle_group.js";
export { /*class*/ b2ParticleGroupDef as ParticleGroupDef } from "./particle/b2_particle_group.js";
export { /*enum*/ b2ParticleGroupFlag as ParticleGroupFlag } from "./particle/b2_particle_group.js";
export { /*class*/ b2FixtureParticleQueryCallback as FixtureParticleQueryCallback } from "./particle/b2_particle_system.js";
export { /*class*/ b2GrowableBuffer as GrowableBuffer } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleBodyContact as ParticleBodyContact } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleContact as ParticleContact } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticlePair as ParticlePair } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticlePairSet as ParticlePairSet } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem as ParticleSystem } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_CompositeShape as ParticleSystem_CompositeShape } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_ConnectionFilter as ParticleSystem_ConnectionFilter } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystemDef as ParticleSystemDef } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_DestroyParticlesInShapeCallback as ParticleSystem_DestroyParticlesInShapeCallback } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_FixedSetAllocator as ParticleSystem_FixedSetAllocator } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_FixtureParticle as ParticleSystem_FixtureParticle } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_FixtureParticleSet as ParticleSystem_FixtureParticleSet } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_InsideBoundsEnumerator as ParticleSystem_InsideBoundsEnumerator } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_JoinParticleGroupsFilter as ParticleSystem_JoinParticleGroupsFilter } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_ParticleListNode as ParticleSystem_ParticleListNode } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_ParticlePair as ParticleSystem_ParticlePair } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_Proxy as ParticleSystem_Proxy } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_ReactiveFilter as ParticleSystem_ReactiveFilter } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_SolveCollisionCallback as ParticleSystem_SolveCollisionCallback } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_UpdateBodyContactsCallback as ParticleSystem_UpdateBodyContactsCallback } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleSystem_UserOverridableBuffer as ParticleSystem_UserOverridableBuffer } from "./particle/b2_particle_system.js";
export { /*class*/ b2ParticleTriad as ParticleTriad } from "./particle/b2_particle_system.js";
export { /*type*/ b2ParticleIndex as ParticleIndex } from "./particle/b2_particle_system.js";
export { /*interface*/ b2IParticleDef as IParticleDef } from "./particle/b2_particle.js";
export { /*class*/ b2ParticleDef as ParticleDef } from "./particle/b2_particle.js";
export { /*class*/ b2ParticleHandle as ParticleHandle } from "./particle/b2_particle.js";
export { /*enum*/ b2ParticleFlag as ParticleFlag } from "./particle/b2_particle.js";
export { /*function*/ b2CalculateParticleIterations as CalculateParticleIterations } from "./particle/b2_particle.js";
export { /*class*/ b2StackQueue as StackQueue } from "./particle/b2_stack_queue.js";
export { /*class*/ b2VoronoiDiagram as VoronoiDiagram } from "./particle/b2_voronoi_diagram.js";
export { /*class*/ b2VoronoiDiagram_Generator as VoronoiDiagram_Generator } from "./particle/b2_voronoi_diagram.js";
export { /*class*/ b2VoronoiDiagram_Task as VoronoiDiagram_Task } from "./particle/b2_voronoi_diagram.js";
export { /*type*/ b2VoronoiDiagram_NodeCallback as VoronoiDiagram_NodeCallback } from "./particle/b2_voronoi_diagram.js"; | the_stack |
import { guessType } from './typeGuess';
import { Hashable } from './hasher';
import TypedArray = NodeJS.TypedArray;
/**
* List of functions responsible for converting certain types to string
*/
export type Stringifiers = { [key: string]: (obj: any) => string };
/**
* Prefixes that used when type coercion is disabled
*/
export const PREFIX = {
string: '<:s>',
number: '<:n>',
bigint: '<:bi>',
boolean: '<:b>',
symbol: '<:smbl>',
undefined: '<:undf>',
null: '<:null>',
function: '<:func>',
array: '',
date: '<:date>',
set: '<:set>',
map: '<:map>',
};
/**
* Converts Hashable to string
* @private
* @param obj object to convert
* @returns object string representation
*/
export function _hashable(obj: Hashable): string {
return obj.toHashableString();
}
/**
* Converts string to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _stringCoerce(obj: string): string {
return obj;
}
/**
* Converts string to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _string(obj: string): string {
return PREFIX.string + ':' + obj;
}
/**
* Converts string to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _stringTrimCoerce(obj: string): string {
return obj.replace(/(\s+|\t|\r\n|\n|\r)/gm, ' ').trim();
}
/**
* Converts string to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _stringTrim(obj: string): string {
return PREFIX.string + ':' + obj.replace(/(\s+|\t|\r\n|\n|\r)/gm, ' ').trim();
}
/**
* Converts number to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _numberCoerce(obj: number): string {
return obj.toString();
}
/**
* Converts number to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _number(obj: number): string {
return `${PREFIX.number}:${obj}`;
}
/**
* Converts BigInt to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _bigIntCoerce(obj: BigInt): string {
return obj.toString();
}
/**
* Converts BigInt to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _bigInt(obj: BigInt): string {
return `${PREFIX.bigint}:${obj.toString()}`;
}
/**
* Converts boolean to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _booleanCoerce(obj: boolean): string {
return obj ? '1' : '0';
}
/**
* Converts boolean to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _boolean(obj: boolean): string {
return PREFIX.boolean + ':' + obj.toString();
}
/**
* Converts symbol to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _symbolCoerce(): string {
return PREFIX.symbol;
}
/**
* Converts symbol to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _symbol(obj: symbol): string {
return PREFIX.symbol + ':' + obj.toString();
}
/**
* Converts undefined to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _undefinedCoerce(): string {
return '';
}
/**
* Converts undefined to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _undefined(): string {
return PREFIX.undefined;
}
/**
* Converts null to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _nullCoerce(): string {
return '';
}
/**
* Converts null to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _null(): string {
return PREFIX.null;
}
/**
* Converts function to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _functionCoerce(obj: Function): string {
return obj.name + '=>' + obj.toString();
}
/**
* Converts function to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _function(obj: Function): string {
return PREFIX.function + ':' + obj.name + '=>' + obj.toString();
}
/**
* Converts function to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _functionTrimCoerce(obj: Function): string {
return (
obj.name +
'=>' +
obj
.toString()
.replace(/(\s+|\t|\r\n|\n|\r)/gm, ' ')
.trim()
);
}
/**
* Converts function to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _functionTrim(obj: Function): string {
return (
PREFIX.function +
':' +
obj.name +
'=>' +
obj
.toString()
.replace(/(\s+|\t|\r\n|\n|\r)/gm, ' ')
.trim()
);
}
/**
* Converts date to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _dateCoerce(obj: Date): string {
return obj.toISOString();
}
/**
* Converts date to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _date(obj: Date): string {
return PREFIX.date + ':' + obj.toISOString();
}
/**
* Converts array to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _arraySort(obj: Array<any>): string {
const stringifiers: Stringifiers = this as Stringifiers;
return (
'[' +
obj
.map((item) => {
return stringifiers[guessType(item)](item);
})
.sort()
.toString() +
']'
);
}
/**
* Converts array to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _array(obj: Array<any>): string {
const stringifiers: Stringifiers = this as Stringifiers;
return (
'[' +
obj
.map((item) => {
return stringifiers[guessType(item)](item);
})
.toString() +
']'
);
}
/**
* Converts TypedArray to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _typedArraySort(obj: TypedArray): string {
const stringifiers: Stringifiers = this as Stringifiers;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const values: Array<any> = Array.prototype.slice.call(obj);
return (
'[' +
values
.map((num) => {
return stringifiers[guessType(num)](num);
})
.sort()
.toString() +
']'
);
}
/**
* Converts TypedArray to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _typedArray(obj: TypedArray): string {
const stringifiers: Stringifiers = this as Stringifiers;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const values: Array<any> = Array.prototype.slice.call(obj);
return (
'[' +
values
.map((num) => {
return stringifiers[guessType(num)](num);
})
.toString() +
']'
);
}
/**
* Converts set to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _setSortCoerce(obj: Set<any>): string {
return _arraySort.call(this as Stringifiers, Array.from(obj)) as string;
}
/**
* Converts set to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _setSort(obj: Set<any>): string {
return `${PREFIX.set}:${_arraySort.call(this, Array.from(obj)) as string}`;
}
/**
* Converts set to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _set(obj: Set<any>): string {
return `${PREFIX.set}:${_array.call(this, Array.from(obj)) as string}`;
}
/**
* Converts set to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _setCoerce(obj: Set<any>): string {
return _array.call(this, Array.from(obj)) as string;
}
/**
* Converts object to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _object(obj: { [key: string]: any }): string {
const stringifiers: Stringifiers = this as Stringifiers;
const keys = Object.keys(obj);
const objArray = [];
for (const key of keys) {
const val = obj[key] as unknown;
const valT = guessType(val);
objArray.push(key + ':' + stringifiers[valT](val));
}
return '{' + objArray.toString() + '}';
}
/**
* Converts object to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _objectSort(obj: { [key: string]: any }): string {
const stringifiers: Stringifiers = this as Stringifiers;
const keys = Object.keys(obj).sort();
const objArray = [];
for (const key of keys) {
const val = obj[key] as unknown;
const valT = guessType(val);
objArray.push(key + ':' + stringifiers[valT](val));
}
return '{' + objArray.toString() + '}';
}
/**
* Converts map to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _map(obj: Map<any, any>): string {
const stringifiers: Stringifiers = this as Stringifiers;
const arr = Array.from(obj);
const mapped = [];
for (const item of arr) {
const [key, value] = item as unknown[];
mapped.push([
stringifiers[guessType(key)](key),
stringifiers[guessType(value)](value),
]);
}
return '[' + mapped.join(';') + ']';
}
/**
* Converts map to string
* @private
* @param obj object to convert
* @return object string representation
*/
export function _mapSort(obj: Map<any, any>): string {
const stringifiers: Stringifiers = this as Stringifiers;
const arr = Array.from(obj);
const mapped = [];
for (const item of arr) {
const [key, value] = item as unknown[];
mapped.push([
stringifiers[guessType(key)](key),
stringifiers[guessType(value)](value),
]);
}
return '[' + mapped.sort().join(';') + ']';
} | the_stack |
/* eslint-enable prettier/prettier*/
import { RSocketServer } from "rsocket-core";
import RSocketTCPServer from "rsocket-tcp-server";
import { AdbHelper } from "../android/adb";
import { Single } from "rsocket-flowable";
import { appNameWithUpdateHint, buildClientId } from "./clientUtils";
import { SecureClientQuery, ClientCsrQuery, ClientDevice, ClientQuery } from "./clientDevice";
import { OutputChannelLogger } from "../log/OutputChannelLogger";
import { Responder, Payload, ReactiveSocket } from "rsocket-types";
import {
CertificateProvider,
SecureServerConfig,
CertificateExchangeMedium,
} from "./certificateProvider";
import { ClientOS } from "./clientUtils";
import * as net from "net";
import * as tls from "tls";
import * as nls from "vscode-nls";
import { InspectorViewType } from "./views/inspectorView";
import { TipNotificationService } from "../services/tipsNotificationsService/tipsNotificationService";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize = nls.loadMessageBundle();
/**
* @preserve
* Start region: the code is borrowed from https://github.com/facebook/flipper/blob/master/desktop/app/src/server.tsx
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
function transformCertificateExchangeMediumToType(
medium: number | undefined,
): CertificateExchangeMedium {
if (medium == 1) {
return "FS_ACCESS";
} else if (medium == 2) {
return "WWW";
} else {
return "FS_ACCESS";
}
}
export const NETWORK_INSPECTOR_LOG_CHANNEL_NAME = "Network Inspector";
export class NetworkInspectorServer {
public static readonly SecureServerPort = 8088;
public static readonly InsecureServerPort = 8089;
private connections: Map<string, ClientDevice>;
private secureServer: RSocketServer<any, any> | null;
private insecureServer: RSocketServer<any, any> | null;
private certificateProvider: CertificateProvider;
private initialisePromise: Promise<void> | null;
private logger: OutputChannelLogger;
constructor() {
this.connections = new Map<string, ClientDevice>();
this.logger = OutputChannelLogger.getChannel(NETWORK_INSPECTOR_LOG_CHANNEL_NAME);
}
public async start(adbHelper: AdbHelper): Promise<void> {
this.logger.info(localize("StartNetworkinspector", "Starting Network inspector"));
TipNotificationService.getInstance().setKnownDateForFeatureById("networkInspector");
TipNotificationService.getInstance().showTipNotification(
false,
"networkInspectorLogsColorTheme",
);
this.initialisePromise = new Promise(async (resolve, reject) => {
this.certificateProvider = new CertificateProvider(adbHelper);
try {
let options = await this.certificateProvider.loadSecureServerConfig();
this.secureServer = await this.startServer(
NetworkInspectorServer.SecureServerPort,
options,
);
this.insecureServer = await this.startServer(
NetworkInspectorServer.InsecureServerPort,
);
} catch (err) {
return reject(err);
}
this.logger.info(localize("NetworkInspectorWorking", "Network inspector is working"));
resolve();
});
return this.initialisePromise;
}
public async stop(): Promise<void> {
if (this.initialisePromise) {
try {
await this.initialisePromise;
} catch (err) {
this.logger.error(err.toString());
}
if (this.secureServer) {
this.secureServer.stop();
}
if (this.insecureServer) {
this.insecureServer.stop();
}
}
this.logger.info(localize("NetworkInspectorStopped", "Network inspector has been stopped"));
}
private async startServer(
port: number,
sslConfig?: SecureServerConfig,
): Promise<RSocketServer<any, any>> {
return new Promise((resolve, reject) => {
let rsServer: RSocketServer<any, any> | undefined; // eslint-disable-line prefer-const
const serverFactory = (onConnect: (socket: net.Socket) => void) => {
const transportServer = sslConfig
? tls.createServer(sslConfig, socket => {
onConnect(socket);
})
: net.createServer(onConnect);
transportServer
.on("error", err => {
this.logger.error(
localize(
"ErrorOpeningNetworkInspectorServerOnPort",
"Error while opening Network inspector server on port {0}",
port,
),
);
reject(err);
})
.on("listening", () => {
this.logger.debug(
`${
sslConfig ? "Secure" : "Certificate"
} server started on port ${port}`,
);
resolve(rsServer!);
});
return transportServer;
};
rsServer = new RSocketServer({
getRequestHandler: sslConfig
? this.trustedRequestHandler
: this.untrustedRequestHandler,
transport: new RSocketTCPServer({
port: port,
serverFactory: serverFactory,
}),
});
rsServer && rsServer.start();
});
}
private trustedRequestHandler = (
socket: ReactiveSocket<string, any>,
payload: Payload<string, any>,
): Partial<Responder<string, any>> => {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const server = this;
if (!payload.data) {
return {};
}
const clientData: SecureClientQuery = JSON.parse(payload.data);
const { app, os, device, device_id, sdk_version, csr, csr_path, medium } = clientData;
const transformedMedium = transformCertificateExchangeMediumToType(medium);
const client: Promise<ClientDevice> = this.addConnection(
socket,
{
app,
os,
device,
device_id,
sdk_version,
medium: transformedMedium,
},
{ csr, csr_path },
).then(client => {
return (resolvedClient = client);
});
let resolvedClient: ClientDevice | undefined;
socket.connectionStatus().subscribe({
onNext(payload) {
if (payload.kind == "ERROR" || payload.kind == "CLOSED") {
client.then(client => {
server.logger.info(
localize(
"NIDeviceDisconnected",
"Device disconnected {0} from the Network inspector",
client.id,
),
);
server.removeConnection(client.id);
});
}
},
onSubscribe(subscription) {
subscription.request(Number.MAX_SAFE_INTEGER);
},
onError(error) {
server.logger.error("Network inspector server connection status error ", error);
},
});
return {
fireAndForget: (payload: { data: string }) => {
if (resolvedClient) {
resolvedClient.onMessage(payload.data);
} else {
client.then(client => {
client.onMessage(payload.data);
});
}
},
};
};
private untrustedRequestHandler = (
_socket: ReactiveSocket<string, any>,
payload: Payload<string, any>,
): Partial<Responder<string, any>> => {
if (!payload.data) {
return {};
}
const clientData: ClientQuery = JSON.parse(payload.data);
return {
requestResponse: (payload: Payload<string, any>): Single<Payload<string, any>> => {
if (typeof payload.data !== "string") {
return new Single(() => {});
}
let rawData;
try {
rawData = JSON.parse(payload.data);
} catch (err) {
this.logger.error(`Network inspector: invalid JSON: ${payload.data}`);
return new Single(() => {});
}
const json: {
method: "signCertificate";
csr: string;
destination: string;
medium: number | undefined; // OSS's older Client SDK might not send medium information. This is not an issue for internal FB users, as Flipper release is insync with client SDK through launcher.
} = rawData;
if (json.method === "signCertificate") {
this.logger.debug("CSR received from device");
const { csr, destination, medium } = json;
return new Single(subscriber => {
subscriber.onSubscribe(undefined);
this.certificateProvider
.processCertificateSigningRequest(
csr,
clientData.os,
destination,
transformCertificateExchangeMediumToType(medium),
)
.then(result => {
subscriber.onComplete({
data: JSON.stringify({
deviceId: result.deviceId,
}),
metadata: "",
});
})
.catch(e => {
this.logger.error(e.toString());
subscriber.onError(e);
});
});
}
return new Single(() => {});
},
// Leaving this here for a while for backwards compatibility,
// but for up to date SDKs it will no longer used.
// We can delete it after the SDK change has been using requestResponse for a few weeks.
fireAndForget: (payload: Payload<string, any>) => {
if (typeof payload.data !== "string") {
return;
}
let json:
| {
method: "signCertificate";
csr: string;
destination: string;
medium: number | undefined;
}
| undefined;
try {
json = JSON.parse(payload.data);
} catch (err) {
this.logger.error(`Network inspector: invalid JSON: ${payload.data}`);
return;
}
if (json && json.method === "signCertificate") {
this.logger.debug("CSR received from device");
const { csr, destination, medium } = json;
this.certificateProvider
.processCertificateSigningRequest(
csr,
clientData.os,
destination,
transformCertificateExchangeMediumToType(medium),
)
.catch(e => {
this.logger.error(e.toString());
});
}
},
};
};
private async addConnection(
conn: ReactiveSocket<any, any>,
query: ClientQuery & { medium: CertificateExchangeMedium },
csrQuery: ClientCsrQuery,
): Promise<ClientDevice> {
// try to get id by comparing giving `csr` to file from `csr_path`
// otherwise, use given device_id
const { csr_path, csr } = csrQuery;
// For iOS we do not need to confirm the device id, as it never changes unlike android.
return (
csr_path && csr && query.os !== ClientOS.iOS
? this.certificateProvider.extractAppNameFromCSR(csr).then(appName => {
return this.certificateProvider.getTargetDeviceId(
query.os,
appName,
csr_path,
csr,
);
})
: Promise.resolve(query.device_id)
).then(async csrId => {
query.device_id = csrId;
query.app = appNameWithUpdateHint(query);
const id = buildClientId(
{
app: query.app,
os: query.os,
device: query.device,
device_id: csrId,
},
this.logger,
);
this.logger.info(localize("NIDeviceConnected", "Device connected: {0}", id));
const client = new ClientDevice(
id,
query,
conn,
InspectorViewType.console,
this.logger,
);
client.init().then(() => {
this.logger.debug(`Device client initialised: ${id}`);
/* If a device gets disconnected without being cleaned up properly,
* Flipper won't be aware until it attempts to reconnect.
* When it does we need to terminate the zombie connection.
*/
this.removeConnection(id);
this.connections.set(id, client);
});
return client;
});
}
/**
* @preserve
* End region: https://github.com/facebook/flipper/blob/master/desktop/app/src/server.tsx
*/
private removeConnection(id: string) {
const clientDevice = this.connections.get(id);
if (clientDevice) {
clientDevice.connection && clientDevice.connection.close();
this.connections.delete(id);
}
}
} | the_stack |
export interface DeleteCfsFileSystemResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 版本控制-可用区数组
*/
export interface AvailableZone {
/**
* 可用区名称
*/
Zone: string;
/**
* 可用区ID
*/
ZoneId: number;
/**
* 可用区中文名称
*/
ZoneCnName: string;
/**
* Type数组
*/
Types: Array<AvailableType>;
/**
* 可用区中英文名称
*/
ZoneName: string;
}
/**
* UpdateCfsRule请求参数结构体
*/
export interface UpdateCfsRuleRequest {
/**
* 权限组 ID
*/
PGroupId: string;
/**
* 规则 ID
*/
RuleId: string;
/**
* 可以填写单个 IP 或者单个网段,例如 10.1.10.11 或者 10.10.1.0/24。默认来访地址为*表示允许所有。同时需要注意,此处需填写 CVM 的内网 IP。
*/
AuthClientIp?: string;
/**
* 读写权限, 值为RO、RW;其中 RO 为只读,RW 为读写,不填默认为只读
*/
RWPermission?: string;
/**
* 用户权限,值为all_squash、no_all_squash、root_squash、no_root_squash。其中all_squash为所有访问用户都会被映射为匿名用户或用户组;no_all_squash为访问用户会先与本机用户匹配,匹配失败后再映射为匿名用户或用户组;root_squash为将来访的root用户映射为匿名用户或用户组;no_root_squash为来访的root用户保持root帐号权限。不填默认为root_squash。
*/
UserPermission?: string;
/**
* 规则优先级,参数范围1-100。 其中 1 为最高,100为最低
*/
Priority?: number;
}
/**
* DescribeCfsFileSystems请求参数结构体
*/
export interface DescribeCfsFileSystemsRequest {
/**
* 文件系统 ID
*/
FileSystemId?: string;
/**
* 私有网络(VPC) ID
*/
VpcId?: string;
/**
* 子网 ID
*/
SubnetId?: string;
}
/**
* DeleteMountTarget请求参数结构体
*/
export interface DeleteMountTargetRequest {
/**
* 文件系统 ID
*/
FileSystemId: string;
/**
* 挂载点 ID
*/
MountTargetId: string;
}
/**
* CreateCfsRule请求参数结构体
*/
export interface CreateCfsRuleRequest {
/**
* 权限组 ID
*/
PGroupId: string;
/**
* 可以填写单个 IP 或者单个网段,例如 10.1.10.11 或者 10.10.1.0/24。默认来访地址为*表示允许所有。同时需要注意,此处需填写 CVM 的内网 IP。
*/
AuthClientIp: string;
/**
* 规则优先级,参数范围1-100。 其中 1 为最高,100为最低
*/
Priority: number;
/**
* 读写权限, 值为 RO、RW;其中 RO 为只读,RW 为读写,不填默认为只读
*/
RWPermission?: string;
/**
* 用户权限,值为 all_squash、no_all_squash、root_squash、no_root_squash。其中all_squash为所有访问用户都会被映射为匿名用户或用户组;no_all_squash为访问用户会先与本机用户匹配,匹配失败后再映射为匿名用户或用户组;root_squash为将来访的root用户映射为匿名用户或用户组;no_root_squash为来访的root用户保持root帐号权限。不填默认为root_squash。
*/
UserPermission?: string;
}
/**
* 文件系统绑定权限组信息
*/
export interface PGroup {
/**
* 权限组ID
*/
PGroupId: string;
/**
* 权限组名称
*/
Name: string;
}
/**
* DescribeAvailableZoneInfo返回参数结构体
*/
export interface DescribeAvailableZoneInfoResponse {
/**
* 各可用区的资源售卖情况以及支持的存储类型、存储协议等信息
*/
RegionZones?: Array<AvailableRegion>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UpdateCfsFileSystemName返回参数结构体
*/
export interface UpdateCfsFileSystemNameResponse {
/**
* 用户自定义文件系统名称
*/
CreationToken?: string;
/**
* 文件系统ID
*/
FileSystemId?: string;
/**
* 用户自定义文件系统名称
*/
FsName?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UpdateCfsFileSystemName请求参数结构体
*/
export interface UpdateCfsFileSystemNameRequest {
/**
* 文件系统 ID
*/
FileSystemId: string;
/**
* 用户自定义文件系统名称
*/
FsName?: string;
}
/**
* DescribeCfsPGroups返回参数结构体
*/
export interface DescribeCfsPGroupsResponse {
/**
* 权限组信息列表
*/
PGroupList?: Array<PGroupInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCfsFileSystemClients返回参数结构体
*/
export interface DescribeCfsFileSystemClientsResponse {
/**
* 客户端列表
*/
ClientList?: Array<FileSystemClient>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteMountTarget返回参数结构体
*/
export interface DeleteMountTargetResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeMountTargets返回参数结构体
*/
export interface DescribeMountTargetsResponse {
/**
* 挂载点详情
*/
MountTargets?: Array<MountInfo>;
/**
* 挂载点数量
*/
NumberOfMountTargets?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteCfsRule返回参数结构体
*/
export interface DeleteCfsRuleResponse {
/**
* 规则 ID
*/
RuleId?: string;
/**
* 权限组 ID
*/
PGroupId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteCfsRule请求参数结构体
*/
export interface DeleteCfsRuleRequest {
/**
* 权限组 ID
*/
PGroupId: string;
/**
* 规则 ID
*/
RuleId: string;
}
/**
* UpdateCfsPGroup请求参数结构体
*/
export interface UpdateCfsPGroupRequest {
/**
* 权限组 ID
*/
PGroupId: string;
/**
* 权限组名称,1-64个字符且只能为中文,字母,数字,下划线或横线
*/
Name?: string;
/**
* 权限组描述信息,1-255个字符
*/
DescInfo?: string;
}
/**
* 挂载点信息
*/
export interface MountInfo {
/**
* 文件系统 ID
*/
FileSystemId: string;
/**
* 挂载点 ID
*/
MountTargetId: string;
/**
* 挂载点 IP
*/
IpAddress: string;
/**
* 挂载根目录
*/
FSID: string;
/**
* 挂载点状态
*/
LifeCycleState: string;
/**
* 网络类型
*/
NetworkInterface: string;
/**
* 私有网络 ID
*/
VpcId: string;
/**
* 私有网络名称
*/
VpcName: string;
/**
* 子网 Id
*/
SubnetId: string;
/**
* 子网名称
*/
SubnetName: string;
/**
* CFS Turbo使用的云联网ID
*/
CcnID: string;
/**
* 云联网中CFS Turbo使用的网段
*/
CidrBlock: string;
}
/**
* UpdateCfsRule返回参数结构体
*/
export interface UpdateCfsRuleResponse {
/**
* 权限组 ID
*/
PGroupId?: string;
/**
* 规则 ID
*/
RuleId?: string;
/**
* 允许访问的客户端 IP 或者 IP 段
*/
AuthClientIp?: string;
/**
* 读写权限
*/
RWPermission?: string;
/**
* 用户权限
*/
UserPermission?: string;
/**
* 优先级
*/
Priority?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 文件系统客户端信息
*/
export interface FileSystemClient {
/**
* 文件系统IP地址
*/
CfsVip: string;
/**
* 客户端IP地址
*/
ClientIp: string;
/**
* 文件系统所属VPCID
*/
VpcId: string;
/**
* 可用区名称,例如ap-beijing-1,请参考 概览文档中的地域与可用区列表
*/
Zone: string;
/**
* 可用区中文名称
*/
ZoneName: string;
/**
* 该文件系统被挂载到客户端上的路径信息
*/
MountDirectory: string;
}
/**
* DescribeCfsFileSystems返回参数结构体
*/
export interface DescribeCfsFileSystemsResponse {
/**
* 文件系统信息
*/
FileSystems?: Array<FileSystemInfo>;
/**
* 文件系统总数
*/
TotalCount?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateCfsFileSystem返回参数结构体
*/
export interface CreateCfsFileSystemResponse {
/**
* 文件系统创建时间
*/
CreationTime: string;
/**
* 用户自定义文件系统名称
*/
CreationToken: string;
/**
* 文件系统 ID
*/
FileSystemId: string;
/**
* 文件系统状态,可能出现状态包括:“creating” 创建中, “create_failed” 创建失败, “available” 可用, “unserviced” 不可用, “upgrading” 升级中, “deleting” 删除中。
*/
LifeCycleState: string;
/**
* 文件系统已使用容量大小,单位为 Byte
*/
SizeByte: number;
/**
* 可用区 ID
*/
ZoneId: number;
/**
* 用户自定义文件系统名称
*/
FsName: string;
/**
* 文件系统是否加密
*/
Encrypted: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 文件系统基本信息
*/
export interface FileSystemInfo {
/**
* 创建时间
*/
CreationTime: string;
/**
* 用户自定义名称
*/
CreationToken: string;
/**
* 文件系统 ID
*/
FileSystemId: string;
/**
* 文件系统状态
*/
LifeCycleState: string;
/**
* 文件系统已使用容量
*/
SizeByte: number;
/**
* 文件系统最大空间限制
*/
SizeLimit: number;
/**
* 区域 ID
*/
ZoneId: number;
/**
* 区域名称
*/
Zone: string;
/**
* 文件系统协议类型
*/
Protocol: string;
/**
* 文件系统存储类型
*/
StorageType: string;
/**
* 文件系统绑定的预付费存储包
*/
StorageResourcePkg: string;
/**
* 文件系统绑定的预付费带宽包(暂未支持)
*/
BandwidthResourcePkg: string;
/**
* 文件系统绑定权限组信息
*/
PGroup: PGroup;
/**
* 用户自定义名称
*/
FsName: string;
/**
* 文件系统是否加密
*/
Encrypted: boolean;
/**
* 加密所使用的密钥,可以为密钥的 ID 或者 ARN
*/
KmsKeyId: string;
/**
* 应用ID
*/
AppId: number;
/**
* 文件系统吞吐上限,吞吐上限是根据文件系统当前已使用存储量、绑定的存储资源包以及吞吐资源包一同确定
*/
BandwidthLimit: number;
/**
* 文件系统总容量
*/
Capacity: number;
}
/**
* Tag信息单元
*/
export interface TagInfo {
/**
* 标签键
*/
TagKey: string;
/**
* 标签值
*/
TagValue: string;
}
/**
* DescribeCfsPGroups请求参数结构体
*/
export declare type DescribeCfsPGroupsRequest = null;
/**
* DescribeCfsFileSystemClients请求参数结构体
*/
export interface DescribeCfsFileSystemClientsRequest {
/**
* 文件系统 ID。
*/
FileSystemId: string;
}
/**
* CreateCfsPGroup请求参数结构体
*/
export interface CreateCfsPGroupRequest {
/**
* 权限组名称,1-64个字符且只能为中文,字母,数字,下划线或横线
*/
Name: string;
/**
* 权限组描述信息,1-255个字符
*/
DescInfo?: string;
}
/**
* DeleteCfsPGroup返回参数结构体
*/
export interface DeleteCfsPGroupResponse {
/**
* 权限组 ID
*/
PGroupId?: string;
/**
* 用户 ID
*/
AppId?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UpdateCfsFileSystemSizeLimit返回参数结构体
*/
export interface UpdateCfsFileSystemSizeLimitResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeAvailableZoneInfo请求参数结构体
*/
export declare type DescribeAvailableZoneInfoRequest = null;
/**
* 版本控制-区域数组
*/
export interface AvailableRegion {
/**
* 区域名称,如“ap-beijing”
*/
Region: string;
/**
* 区域名称,如“bj”
*/
RegionName: string;
/**
* 区域可用情况,当区域内至少有一个可用区处于可售状态时,取值为AVAILABLE,否则为UNAVAILABLE
*/
RegionStatus: string;
/**
* 可用区数组
*/
Zones: Array<AvailableZone>;
/**
* 区域中文名称,如“广州”
*/
RegionCnName: string;
}
/**
* CreateCfsFileSystem请求参数结构体
*/
export interface CreateCfsFileSystemRequest {
/**
* 可用区名称,例如ap-beijing-1,请参考 [概览](https://cloud.tencent.com/document/product/582/13225) 文档中的地域与可用区列表
*/
Zone: string;
/**
* 网络类型,可选值为 VPC,BASIC,CCN;其中 VPC 为私有网络,BASIC 为基础网络, CCN 为云联网,Turbo系列当前必须选择云联网。目前基础网络已逐渐淘汰,不推荐使用。
*/
NetInterface: string;
/**
* 权限组 ID,通用标准型和性能型必填,turbo系列请填写pgroupbasic
*/
PGroupId: string;
/**
* 文件系统协议类型, 值为 NFS、CIFS、TURBO ; 若留空则默认为 NFS协议,turbo系列必须选择turbo,不支持NFS、CIFS
*/
Protocol?: string;
/**
* 文件系统存储类型,默认值为 SD ;其中 SD 为通用标准型标准型存储, HP为通用性能型存储, TB为turbo标准型, TP 为turbo性能型。
*/
StorageType?: string;
/**
* 私有网络(VPC) ID,若网络类型选择的是VPC,该字段为必填。
*/
VpcId?: string;
/**
* 子网 ID,若网络类型选择的是VPC,该字段为必填。
*/
SubnetId?: string;
/**
* 指定IP地址,仅VPC网络支持;若不填写、将在该子网下随机分配 IP,Turbo系列当前不支持指定
*/
MountIP?: string;
/**
* 用户自定义文件系统名称
*/
FsName?: string;
/**
* 文件系统标签
*/
ResourceTags?: Array<TagInfo>;
/**
* 用于保证请求幂等性的字符串。该字符串由客户生成,需保证不同请求之间唯一,最大值不超过64个ASCII字符。若不指定该参数,则无法保证请求的幂等性。用于保证请求幂等性的字符串失效时间为2小时。
*/
ClientToken?: string;
/**
* 云联网ID, 若网络类型选择的是CCN,该字段为必填
*/
CcnId?: string;
/**
* 云联网中CFS使用的网段, 若网络类型选择的是Ccn,该字段为必填,且不能和Ccn中已经绑定的网段冲突
*/
CidrBlock?: string;
/**
* 文件系统容量,turbo系列必填,单位为GiB。 turbo标准型单位GB,起售40TiB,即40960 GiB;扩容步长20TiB,即20480 GiB。turbo性能型起售20TiB,即20480 GiB;扩容步长10TiB,10240 GiB。
*/
Capacity?: number;
}
/**
* DescribeMountTargets请求参数结构体
*/
export interface DescribeMountTargetsRequest {
/**
* 文件系统 ID
*/
FileSystemId: string;
}
/**
* CreateCfsPGroup返回参数结构体
*/
export interface CreateCfsPGroupResponse {
/**
* 权限组 ID
*/
PGroupId?: string;
/**
* 权限组名字
*/
Name?: string;
/**
* 权限组描述信息
*/
DescInfo?: string;
/**
* 已经与该权限组绑定的文件系统个数
*/
BindCfsNum?: number;
/**
* 权限组创建时间
*/
CDate?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* SignUpCfsService请求参数结构体
*/
export declare type SignUpCfsServiceRequest = null;
/**
* DescribeCfsServiceStatus请求参数结构体
*/
export declare type DescribeCfsServiceStatusRequest = null;
/**
* 权限组数组
*/
export interface PGroupInfo {
/**
* 权限组ID
*/
PGroupId: string;
/**
* 权限组名称
*/
Name: string;
/**
* 描述信息
*/
DescInfo: string;
/**
* 创建时间
*/
CDate: string;
/**
* 关联文件系统个数
*/
BindCfsNum: number;
}
/**
* SignUpCfsService返回参数结构体
*/
export interface SignUpCfsServiceResponse {
/**
* 该用户当前 CFS 服务的状态,none 是未开通,creating 是开通中,created 是已开通
*/
CfsServiceStatus?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UpdateCfsFileSystemPGroup请求参数结构体
*/
export interface UpdateCfsFileSystemPGroupRequest {
/**
* 权限组 ID
*/
PGroupId: string;
/**
* 文件系统 ID
*/
FileSystemId: string;
}
/**
* DescribeCfsServiceStatus返回参数结构体
*/
export interface DescribeCfsServiceStatusResponse {
/**
* 该用户当前 CFS 服务的状态,none 为未开通,creating 为开通中,created 为已开通
*/
CfsServiceStatus?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateCfsRule返回参数结构体
*/
export interface CreateCfsRuleResponse {
/**
* 规则 ID
*/
RuleId?: string;
/**
* 权限组 ID
*/
PGroupId?: string;
/**
* 客户端 IP
*/
AuthClientIp?: string;
/**
* 读写权限
*/
RWPermission?: string;
/**
* 用户权限
*/
UserPermission?: string;
/**
* 优先级
*/
Priority?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 版本控制-协议详情
*/
export interface AvailableProtoStatus {
/**
* 售卖状态。可选值有 sale_out 售罄、saling可售、no_saling不可销售
*/
SaleStatus: string;
/**
* 协议类型。可选值有 NFS、CIFS
*/
Protocol: string;
}
/**
* DescribeCfsRules请求参数结构体
*/
export interface DescribeCfsRulesRequest {
/**
* 权限组 ID
*/
PGroupId: string;
}
/**
* 权限组规则列表
*/
export interface PGroupRuleInfo {
/**
* 规则ID
*/
RuleId: string;
/**
* 允许访问的客户端IP
*/
AuthClientIp: string;
/**
* 读写权限, ro为只读,rw为读写
*/
RWPermission: string;
/**
* 用户权限。其中all_squash为所有访问用户都会被映射为匿名用户或用户组;no_all_squash为访问用户会先与本机用户匹配,匹配失败后再映射为匿名用户或用户组;root_squash为将来访的root用户映射为匿名用户或用户组;no_root_squash为来访的root用户保持root帐号权限。
*/
UserPermission: string;
/**
* 规则优先级,1-100。 其中 1 为最高,100为最低
*/
Priority: number;
}
/**
* DeleteCfsPGroup请求参数结构体
*/
export interface DeleteCfsPGroupRequest {
/**
* 权限组 ID
*/
PGroupId: string;
}
/**
* 版本控制-类型数组
*/
export interface AvailableType {
/**
* 协议与售卖详情
*/
Protocols: Array<AvailableProtoStatus>;
/**
* 存储类型。返回值中 SD 为标准型存储、HP 为性能型存储
*/
Type: string;
/**
* 是否支持预付费。返回值中 true 为支持、false 为不支持
*/
Prepayment: boolean;
}
/**
* UpdateCfsFileSystemSizeLimit请求参数结构体
*/
export interface UpdateCfsFileSystemSizeLimitRequest {
/**
* 文件系统容量限制大小,输入范围0-1073741824, 单位为GB;其中输入值为0时,表示不限制文件系统容量。
*/
FsLimit: number;
/**
* 文件系统ID,目前仅支持标准型文件系统。
*/
FileSystemId: string;
}
/**
* DeleteCfsFileSystem请求参数结构体
*/
export interface DeleteCfsFileSystemRequest {
/**
* 文件系统 ID。说明,进行删除文件系统操作前需要先调用 DeleteMountTarget 接口删除该文件系统的挂载点,否则会删除失败。
*/
FileSystemId: string;
}
/**
* UpdateCfsPGroup返回参数结构体
*/
export interface UpdateCfsPGroupResponse {
/**
* 权限组ID
*/
PGroupId?: string;
/**
* 权限组名称
*/
Name?: string;
/**
* 描述信息
*/
DescInfo?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCfsRules返回参数结构体
*/
export interface DescribeCfsRulesResponse {
/**
* 权限组规则列表
*/
RuleList?: Array<PGroupRuleInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UpdateCfsFileSystemPGroup返回参数结构体
*/
export interface UpdateCfsFileSystemPGroupResponse {
/**
* 权限组 ID
*/
PGroupId?: string;
/**
* 文件系统 ID
*/
FileSystemId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
} | the_stack |
import {
CompatibleTypes,
FieldKind,
FieldNullability,
FieldOptionsFromKind,
NormalizeArgs,
RootName,
SchemaTypes,
TypeParam,
} from '../types';
import RootFieldBuilder from './root';
export default class FieldBuilder<
Types extends SchemaTypes,
ParentShape,
Kind extends Exclude<FieldKind, RootName> = Exclude<FieldKind, RootName>,
> extends RootFieldBuilder<Types, ParentShape, Kind> {
/**
* Create a Boolean field from a boolean property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeBoolean<
Name extends CompatibleTypes<Types, ParentShape, 'Boolean', Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<'Boolean'> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
'Boolean',
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<'Boolean', Nullable, Name>(name, { ...options, type: 'Boolean' });
}
/**
* Create a Float field from a numeric property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeFloat<
Name extends CompatibleTypes<Types, ParentShape, 'Float', Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<'Float'> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
'Float',
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<'Float', Nullable, Name>(name, { ...options, type: 'Float' });
}
/**
* Create an ID field from a property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeID<
Name extends CompatibleTypes<Types, ParentShape, 'ID', Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<'ID'> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
'ID',
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<'ID', Nullable, Name>(name, { ...options, type: 'ID' });
}
/**
* Create an Int field from a numeric property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeInt<
Name extends CompatibleTypes<Types, ParentShape, 'Int', Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<'Int'> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
'Int',
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'args' | 'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<'Int', Nullable, Name>(name, { ...options, type: 'Int' });
}
/**
* Create a String field from a string property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeString<
Name extends CompatibleTypes<Types, ParentShape, 'String', Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<'String'> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
'String',
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<'String', Nullable, Name>(name, { ...options, type: 'String' });
}
/**
* Create a Boolean list field from a boolean[] property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeBooleanList<
Name extends CompatibleTypes<Types, ParentShape, ['Boolean'], Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<['Boolean']> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
['Boolean'],
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<['Boolean'], Nullable, Name>(name, { ...options, type: ['Boolean'] });
}
/**
* Create a Float list field from a number[] property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeFloatList<
Name extends CompatibleTypes<Types, ParentShape, ['Float'], Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<['Float']> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
['Float'],
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<['Float'], Nullable, Name>(name, { ...options, type: ['Float'] });
}
/**
* Create an ID list field from an id[] property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeIDList<
Name extends CompatibleTypes<Types, ParentShape, ['ID'], Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<['ID']> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
['ID'],
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<['ID'], Nullable, Name>(name, { ...options, type: ['ID'] });
}
/**
* Create a Int list field from a number[] property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeIntList<
Name extends CompatibleTypes<Types, ParentShape, ['Int'], Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<['Int']> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
['Int'],
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<['Int'], Nullable, Name>(name, { ...options, type: ['Int'] });
}
/**
* Create a String list field from a string[] property on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
exposeStringList<
Name extends CompatibleTypes<Types, ParentShape, ['String'], Nullable>,
ResolveReturnShape,
Nullable extends FieldNullability<['String']> = Types['DefaultFieldNullability'],
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
['String'],
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField<['String'], Nullable, Name>(name, { ...options, type: ['String'] });
}
/**
* Create a field that resolves to a property of the corresponding type on the parent object
* @param {string} name - the name of the property on the source object (does not need to match the field name).
* @param {object} [options={}] - Options for this field
*/
expose<
Type extends TypeParam<Types>,
Nullable extends boolean,
ResolveReturnShape,
Name extends CompatibleTypes<Types, ParentShape, Type, Nullable>,
>(
...args: NormalizeArgs<
[
name: Name,
options?: Omit<
FieldOptionsFromKind<
Types,
ParentShape,
Type,
Nullable,
{},
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve'
>,
]
>
) {
const [name, options = {} as never] = args;
return this.exposeField(name, options);
}
} | the_stack |
import React, { useRef, useState } from 'react'
import { render } from '@testing-library/react'
import { useInertOthers } from './use-inert-others'
import { getByText } from '../test-utils/accessibility-assertions'
import { click } from '../test-utils/interactions'
beforeEach(() => {
jest.restoreAllMocks()
jest.spyOn(global.console, 'error').mockImplementation(jest.fn())
})
it('should be possible to inert other elements', async () => {
function Example() {
let ref = useRef(null)
let [enabled, setEnabled] = useState(true)
useInertOthers(ref, enabled)
return (
<div ref={ref} id="main">
<button onClick={() => setEnabled(v => !v)}>toggle</button>
</div>
)
}
function Before() {
return <div>before</div>
}
function After() {
return <div>after</div>
}
render(
<>
<Before />
<Example />
<After />
</>,
{ container: document.body }
)
// Verify the others are hidden
expect(document.getElementById('main')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Restore
await click(getByText('toggle'))
// Verify we are un-hidden
expect(document.getElementById('main')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).not.toHaveAttribute('aria-hidden')
expect(getByText('after')).not.toHaveAttribute('aria-hidden')
})
it('should restore inert elements, when all useInertOthers calls are disabled', async () => {
function Example({ toggle, id }: { toggle: string; id: string }) {
let ref = useRef(null)
let [enabled, setEnabled] = useState(false)
useInertOthers(ref, enabled)
return (
<div ref={ref} id={id}>
<button onClick={() => setEnabled(v => !v)}>{toggle}</button>
</div>
)
}
function Before() {
return <div>before</div>
}
function After() {
return <div>after</div>
}
render(
<>
<Before />
<Example id="main1" toggle="toggle 1" />
<Example id="main2" toggle="toggle 2" />
<After />
</>,
{ container: document.body }
)
// Verify nothing is hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).not.toHaveAttribute('aria-hidden')
expect(getByText('after')).not.toHaveAttribute('aria-hidden')
// Enable inert on others (via toggle 1)
await click(getByText('toggle 1'))
// Verify the others are hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Enable inert on others (via toggle 2)
await click(getByText('toggle 2'))
// Verify the others are hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Remove first level of inert (via toggle 1)
await click(getByText('toggle 1'))
// Verify the others are hidden
expect(document.getElementById('main1')).toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Remove second level of inert (via toggle 2)
await click(getByText('toggle 2'))
// Verify the others are not hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).not.toHaveAttribute('aria-hidden')
expect(getByText('after')).not.toHaveAttribute('aria-hidden')
})
it('should restore inert elements, when all useInertOthers calls are disabled (including parents)', async () => {
function Example({ toggle, id }: { toggle: string; id: string }) {
let ref = useRef(null)
let [enabled, setEnabled] = useState(false)
useInertOthers(ref, enabled)
return (
<div id={`parent-${id}`}>
<div ref={ref} id={id}>
<button onClick={() => setEnabled(v => !v)}>{toggle}</button>
</div>
</div>
)
}
function Before() {
return <div>before</div>
}
function After() {
return <div>after</div>
}
render(
<>
<Before />
<Example id="main1" toggle="toggle 1" />
<Example id="main2" toggle="toggle 2" />
<After />
</>,
{ container: document.body }
)
// Verify nothing is hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main2')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).not.toHaveAttribute('aria-hidden')
expect(getByText('after')).not.toHaveAttribute('aria-hidden')
// Enable inert on others (via toggle 1)
await click(getByText('toggle 1'))
// Verify the others are hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden', 'true')
expect(document.getElementById('parent-main2')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Enable inert on others (via toggle 2)
await click(getByText('toggle 2'))
// Verify the others are hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main2')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Remove first level of inert (via toggle 1)
await click(getByText('toggle 1'))
// Verify the others are hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main1')).toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main2')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Remove second level of inert (via toggle 2)
await click(getByText('toggle 2'))
// Verify the others are not hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent-main2')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).not.toHaveAttribute('aria-hidden')
expect(getByText('after')).not.toHaveAttribute('aria-hidden')
})
it('should handle inert others correctly when 2 useInertOthers are used in a shared parent', async () => {
function Example({ toggle, id }: { toggle: string; id: string }) {
let ref = useRef(null)
let [enabled, setEnabled] = useState(false)
useInertOthers(ref, enabled)
return (
<div ref={ref} id={id}>
<button onClick={() => setEnabled(v => !v)}>{toggle}</button>
</div>
)
}
function Before() {
return <div>before</div>
}
function After() {
return <div>after</div>
}
render(
<>
<Before />
<div id="parent">
<Example id="main1" toggle="toggle 1" />
<Example id="main2" toggle="toggle 2" />
</div>
<After />
</>,
{ container: document.body }
)
// Verify nothing is hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).not.toHaveAttribute('aria-hidden')
expect(getByText('after')).not.toHaveAttribute('aria-hidden')
// Enable inert on others (via toggle 1)
await click(getByText('toggle 1'))
// Verify the others are hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden', 'true')
expect(document.getElementById('parent')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Enable inert on others (via toggle 2)
await click(getByText('toggle 2'))
// Verify the others are hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Remove first level of inert (via toggle 1)
await click(getByText('toggle 1'))
// Verify the others are hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).toHaveAttribute('aria-hidden', 'true')
expect(getByText('after')).toHaveAttribute('aria-hidden', 'true')
// Remove second level of inert (via toggle 2)
await click(getByText('toggle 2'))
// Verify the others are not hidden
expect(document.getElementById('main1')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('main2')).not.toHaveAttribute('aria-hidden')
expect(document.getElementById('parent')).not.toHaveAttribute('aria-hidden')
expect(getByText('before')).not.toHaveAttribute('aria-hidden')
expect(getByText('after')).not.toHaveAttribute('aria-hidden')
}) | the_stack |
import { ThemeTypes } from '@getstation/theme';
import * as classNames from 'classnames';
// @ts-ignore: no declaration file
import * as scrollIntoView from 'dom-scroll-into-view';
// @ts-ignore: no declaration file
import * as isBlank from 'is-blank';
import * as React from 'react';
import { findDOMNode } from 'react-dom';
// @ts-ignore: no declaration file
import injectSheet from 'react-jss';
import { EMPTY_SECTION, flattenResults, sectionsAlwaysExpanded } from '../api';
import { SearchResultSerialized, SearchSectionSerialized } from '../duck';
import { findItemById, getId } from '../helpers/utils';
import BangItem from './BangItem';
const throttle = require('lodash.throttle');
interface Classes {
list: string;
lastOpened: string;
section: string;
withResults: string;
category: string;
results: string;
loading: string;
expandSection: string;
expandSectionIcon: string;
resultsCount: string;
}
interface CollapseSections {
[sectionName: string]: { collapsed: boolean };
}
interface State {
collapseSections: CollapseSections;
}
export interface Props {
classes?: Classes;
forEmptyQuery: boolean;
items: SearchSectionSerialized[];
historyItems: SearchResultSerialized[];
highlightedItemId?: string;
onItemClick: (id: string, position: number) => void;
onResetHighlightedItem: () => void;
onCollapseSection: () => void;
}
const shouldShowSection = (item: SearchSectionSerialized) =>
(item.results && item.results.length > 0) || item.loading;
const sectionAlwaysExpanded = (item: SearchSectionSerialized) =>
sectionsAlwaysExpanded.includes(item.sectionName);
const getHighlightedItem = (props: Props) =>
findItemById(props.highlightedItemId!, flattenResults(props.items)) ||
findItemById(props.highlightedItemId!, props.historyItems);
const itemIsInTopHits = (item: SearchResultSerialized) =>
item.sectionKind === 'top-hits';
const itemIsCollapsed = (
item: SearchResultSerialized,
collapseSections: CollapseSections
) =>
item.category &&
collapseSections[item.category] &&
collapseSections[item.category].collapsed &&
!itemIsInTopHits(item);
@injectSheet((theme: ThemeTypes) => ({
list: {
flex: 1,
overflowY: 'auto',
},
lastOpened: {
margin: [15, 20, 10],
color: 'rgba(255, 255, 255, .4)',
...theme.fontMixin(11, 600),
},
section: {
marginBottom: 12,
'&.withResults': {
backgroundColor: 'rgba(0,0,0,0.15)',
},
},
category: {
padding: [6, 20],
color: 'rgba(255,255,255,0.5)',
textTransform: 'uppercase',
fontSize: '.8em',
display: 'flex',
flexFlow: 'row',
justifyContent: 'space-between',
alignItems: 'center',
'&.clickable': {
cursor: 'pointer',
},
},
results: {
marginTop: 15,
'&.collapsed': {
height: 0,
overflow: 'hidden',
},
},
loading: {
animationDuration: '2s',
animationFillMode: 'forwards',
animationIterationCount: 'infinite',
animationName: 'bangLoading',
animationTimingFunction: 'ease-in-out',
opacity: 0.3,
marginRight: 5,
},
expandSection: {
display: 'flex',
alignItems: 'center',
},
expandSectionIcon: {
fill: '#fff',
fillOpacity: '0.5',
transform: 'rotate(90deg)',
transitionProperty: 'transform',
transitionDuration: '25ms',
'&.collapsed': {
transform: 'rotate(0deg)',
},
},
resultsCount: {
backgroundColor: 'rgba(255,255,255,0.2)',
borderRadius: '50%',
textAlign: 'center',
color: 'rgba(255,255,255,0.8)',
width: 20,
height: 20,
paddingTop: 2,
},
'@keyframes bangLoading': {
'0%': {
backgroundPosition: '10% 0%',
opacity: 0.3,
},
'50%': {
backgroundPosition: '91% 100%',
opacity: 0.5,
},
'100%': {
backgroundPosition: '10% 0%',
opacity: 0.3,
},
},
}))
export default class BangList extends React.PureComponent<Props, State> {
private highlightedItemComponent: Element | null;
constructor(props: Props) {
super(props);
this.componentDidUpdate = throttle(this.componentDidUpdate, 100, {
leading: false,
});
this.toggleCollapse = this.toggleCollapse.bind(this);
this.isCollapsedResults = this.isCollapsedResults.bind(this);
this.renderSectionTitle = this.renderSectionTitle.bind(this);
this.renderArrow = this.renderArrow.bind(this);
}
componentDidMount() {
this.setState({
collapseSections: this.props.items.reduce((state, item) => {
state[item.sectionName] = { collapsed: true };
return state;
}, {}),
});
}
// tslint:disable-next-line:function-name
UNSAFE_componentWillReceiveProps(nextProps: Props) {
const { forEmptyQuery } = nextProps;
if (forEmptyQuery) return;
if (!this.state) return;
const { collapseSections } = this.state;
const nextCollapseSectionsState = nextProps.items.reduce(
(collapseSectionsNewState, item) => {
if (
collapseSections[item.sectionName] &&
!collapseSections[item.sectionName].collapsed
) {
return collapseSectionsNewState;
}
collapseSectionsNewState[item.sectionName] = { collapsed: true };
return collapseSectionsNewState;
},
{},
);
this.updateCollapsedSections(nextCollapseSectionsState);
}
componentDidUpdate(_: Props, prevState: State) {
const highlightedItem = getHighlightedItem(this.props);
if (!highlightedItem) return;
if (
prevState &&
!itemIsCollapsed(highlightedItem, prevState.collapseSections) &&
itemIsCollapsed(highlightedItem, this.state.collapseSections)
) {
this.props.onResetHighlightedItem();
return;
}
const { forEmptyQuery } = this.props;
const highlightedItemIsCollapsed = itemIsCollapsed(
highlightedItem,
this.state.collapseSections
);
if (!forEmptyQuery && highlightedItemIsCollapsed) {
this.expandSectionForSearchResult(highlightedItem);
}
if (forEmptyQuery && !isBlank(this.state.collapseSections)) {
this.setState({ collapseSections: {} });
}
if (this.highlightedItemComponent) {
scrollIntoView(
findDOMNode(this.highlightedItemComponent),
findDOMNode(this),
{ onlyScrollIfNeeded: true }
);
}
}
expandSectionForSearchResult(item: SearchResultSerialized) {
this.updateCollapsedSections({ [item!.category]: { collapsed: false } });
}
toggleCollapse(item: SearchSectionSerialized) {
const nextCollapseState =
this.state.collapseSections[item.sectionName] &&
!this.state.collapseSections[item.sectionName].collapsed;
this.props.onCollapseSection();
this.updateCollapsedSections({
[item.sectionName]: { collapsed: nextCollapseState },
});
}
isCollapsedResults(item: SearchSectionSerialized) {
if (!Boolean(this.state)) return false;
const shouldNotCollapseFromState =
this.state.collapseSections[item.sectionName] &&
!this.state.collapseSections[item.sectionName].collapsed;
if (shouldNotCollapseFromState) return false;
return !sectionAlwaysExpanded(item);
}
renderSectionTitle(item: SearchSectionSerialized) {
const { classes } = this.props;
const clickable =
!sectionAlwaysExpanded(item) && item.results && item.results.length > 0;
const collapsed = this.isCollapsedResults(item);
const showResultPart =
!item.loading && item.results && !sectionAlwaysExpanded(item);
return (
<h4
className={classNames(classes!.category, { clickable, collapsed })}
onClick={() => this.toggleCollapse(item)}
>
{item.sectionName} {showResultPart && ` (${item.results!.length})`}
<div className={classes!.expandSection}>
{item.loading && <span className={classes!.loading}>loading</span>}
{showResultPart && <span>{this.renderArrow(item)}</span>}
</div>
</h4>
);
}
renderArrow(item: SearchSectionSerialized) {
const { classes } = this.props;
return (
<svg
className={classNames(classes!.expandSectionIcon, {
collapsed: this.isCollapsedResults(item),
})}
xmlns="http://www.w3.org/2000/svg"
width="15"
height="15"
viewBox="0 0 24 24"
>
<path d="M8.122 24l-4.122-4 8-8-8-8 4.122-4 11.878 12z" />
</svg>
);
}
renderItem(item: SearchResultSerialized, position: number) {
const { highlightedItemId, forEmptyQuery } = this.props;
const id = getId(item);
const highlighted = highlightedItemId === id;
return (
<BangItem
current={forEmptyQuery && position === 0}
key={id}
label={item.label}
context={item.context}
imgUrl={item.imgUrl}
type={item.type}
themeColor={item.themeColor!}
// todo change all `highlighted` by `selected`
selected={highlighted}
ref={(itemComp: Element) => {
if (highlighted) this.highlightedItemComponent = itemComp;
}}
onClick={() => this.props.onItemClick(id, position)}
/>
);
}
render() {
const { classes, items, historyItems, forEmptyQuery } = this.props;
return (
<div className={classes!.list}>
{forEmptyQuery ? (
<>
<>
<div className={classes!.lastOpened}>CURRENT</div>
{historyItems.length > 0
? this.renderItem(historyItems[0], 0)
: null}
</>
<div className={classes!.lastOpened}>RECENTS</div>
<div className={classNames(classes!.section)}>
<div className={classNames(classes!.results)}>
{historyItems.map((result, position) => {
if (forEmptyQuery && position === 0) return null;
return this.renderItem(result, position);
})}
</div>
</div>
</>
) : (
items.some(i => i.sectionKind === 'top-hits') &&
items.filter(shouldShowSection).map(item => (
<div
className={classNames(classes!.section, {
withResults: item.sectionName !== EMPTY_SECTION,
})}
key={item.sectionName}
>
{item.sectionName === EMPTY_SECTION
? null
: this.renderSectionTitle(item)}
{!this.isCollapsedResults(item) && (
<div
className={classNames(classes!.results, {
collapsed: this.isCollapsedResults(item),
})}
>
{item.results
? item.results.map((result, position) => {
if (forEmptyQuery && position === 0) {
return null;
}
return this.renderItem(result, position);
})
: null}
</div>
)}
</div>
))
)}
</div>
);
}
private updateCollapsedSections(state: CollapseSections) {
this.setState({
collapseSections: { ...this.state.collapseSections, ...state },
});
}
} | the_stack |
import { SetStateAction, useCallback, useMemo, useState } from "react";
import {
useControlledState,
useInitialValue,
useLazyValue,
useLiveRef,
useSafeLayoutEffect,
} from "ariakit-utils/hooks";
import { applyState } from "ariakit-utils/misc";
import { useStorePublisher } from "ariakit-utils/store";
import { AnyObject, SetState } from "ariakit-utils/types";
import {
CollectionState,
CollectionStateProps,
useCollectionState,
} from "../collection/collection-state";
import {
DeepMap,
DeepPartial,
Names,
StringLike,
createNames,
get,
hasMessages,
set,
setAll,
} from "./__utils";
type ErrorMessage = string | undefined | null;
type Callback = () => void | Promise<void>;
type Item = CollectionState["items"][number] & {
type: "field" | "label" | "description" | "error" | "button";
name: string;
id?: string;
};
/**
* Provides state for the `Form` component.
* @example
* ```jsx
* const form = useFormState({ defaultValues: { email: "" } });
* <Form state={form}>
* <FormLabel name={form.names.email}>Email</FormLabel>
* <FormInput name={form.names.email} />
* <FormError name={form.names.email} />
* <FormSubmit>Submit</FormSubmit>
* </Form>
* ```
*/
export function useFormState<V = AnyObject>(
props: FormStateProps<V> = {}
): FormState<V> {
const collection = useCollectionState(props);
const defaultValues = useInitialValue(
props.defaultValues || ({} as FormState<V>["values"])
);
const [values, setValues] = useControlledState(
defaultValues,
props.values,
props.setValues
);
const defaultErrors = useInitialValue(
props.defaultErrors || ({} as FormState<V>["errors"])
);
const [errors, setErrors] = useControlledState(
defaultErrors,
props.errors,
props.setErrors
);
const defaultTouched = useInitialValue(
props.defaultTouched || ({} as FormState<V>["touched"])
);
const [touched, setTouched] = useControlledState(
defaultTouched,
props.touched,
props.setTouched
);
const [validating, setValidating] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [submitSucceed, setSubmitSucceed] = useState(0);
const [submitFailed, setSubmitFailed] = useState(0);
const valid = useMemo(() => !hasMessages(errors), [errors]);
const names = useLazyValue(createNames);
const submitCallbacks = useLazyValue(() => new Set<Callback>());
const validateCallbacks = useLazyValue(() => new Set<Callback>());
const getValue: FormState["getValue"] = useCallback(
(name) => get(values, name),
[values]
);
const setValue: FormState["setValue"] = useCallback(
(name, value) =>
setValues((prevValues) => {
const prevValue = get(prevValues, name);
const nextValue = applyState(value, prevValue);
if (nextValue === prevValue) return prevValues;
return set(prevValues, name, nextValue);
}),
[]
);
const pushValue: FormState["pushValue"] = useCallback((name, value) => {
setValues((prevValues) => {
const array = get(prevValues, name, [] as unknown[]);
return set(prevValues, name, [...array, value]);
});
}, []);
const removeValue: FormState["removeValue"] = useCallback((name, index) => {
setValues((prevValues) => {
const array = get(prevValues, name, [] as unknown[]);
return set(prevValues, name, [
...array.slice(0, index),
null,
...array.slice(index + 1),
]);
});
}, []);
const getError: FormState["getError"] = useCallback(
(name) => get(errors, name),
[errors]
);
const setError: FormState["setError"] = useCallback(
(name, error) =>
setErrors((prevErrors) => {
const prevError = get(prevErrors, name);
const nextError = applyState(error, prevError);
if (nextError === prevError) return prevErrors;
return set(prevErrors, name, nextError);
}),
[]
);
const getFieldTouched: FormState["getFieldTouched"] = useCallback(
(name) => !!get(touched, name),
[touched]
);
const setFieldTouched: FormState["setFieldTouched"] = useCallback(
(name, value) =>
setTouched((prevTouched) => {
const prevValue = get(prevTouched, name);
const nextValue = applyState(value, prevValue);
if (nextValue === prevValue) return prevTouched;
return set(prevTouched, name, nextValue);
}),
[]
);
const useValidate: FormState["useValidate"] = useCallback((callback) => {
useSafeLayoutEffect(() => {
validateCallbacks.add(callback);
return () => {
validateCallbacks.delete(callback);
};
}, [callback]);
}, []);
const useSubmit: FormState["useSubmit"] = useCallback((callback) => {
useSafeLayoutEffect(() => {
submitCallbacks.add(callback);
return () => {
submitCallbacks.delete(callback);
};
}, [callback]);
}, []);
const errorsRef = useLiveRef(errors);
const validate: FormState["validate"] = useCallback(async () => {
setValidating(true);
setErrors(defaultErrors);
try {
const callbacks = [...validateCallbacks];
const results = callbacks.map((callback) => callback());
await Promise.all(results);
return !hasMessages(errorsRef.current);
} finally {
setValidating(false);
}
}, [defaultErrors]);
const valuesRef = useLiveRef(values);
const submit: FormState["submit"] = useCallback(async () => {
setSubmitting(true);
setTouched(setAll(valuesRef.current, true));
try {
if (await validate()) {
const callbacks = [...submitCallbacks];
const results = callbacks.map((callback) => callback());
await Promise.all(results);
if (!hasMessages(errorsRef.current)) {
setSubmitSucceed((value) => value + 1);
return true;
}
}
setSubmitFailed((value) => value + 1);
return false;
} catch (error) {
setSubmitFailed((value) => value + 1);
throw error;
} finally {
setSubmitting(false);
}
}, [validate]);
const reset = useCallback(() => {
setValues(defaultValues);
setErrors(defaultErrors);
setTouched(defaultTouched);
setValidating(false);
setSubmitting(false);
setSubmitSucceed(0);
setSubmitFailed(0);
}, [defaultValues, defaultErrors, defaultTouched]);
const state = useMemo(
() => ({
...collection,
values,
setValues,
errors,
setErrors,
touched,
setTouched,
validating,
submitting,
submitSucceed,
submitFailed,
valid,
names,
getValue,
setValue,
pushValue,
removeValue,
getError,
setError,
getFieldTouched,
setFieldTouched,
useValidate,
useSubmit,
validate,
submit,
reset,
}),
[
collection,
values,
setValues,
errors,
setErrors,
touched,
setTouched,
validating,
submitting,
submitSucceed,
submitFailed,
valid,
names,
getValue,
setValue,
pushValue,
removeValue,
getError,
setError,
getFieldTouched,
setFieldTouched,
useValidate,
useSubmit,
validate,
submit,
reset,
]
);
return useStorePublisher(state);
}
export type FormState<V = AnyObject> = CollectionState<Item> & {
/**
* Form values.
*/
values: V;
/**
* Sets the `values` state.
* @example
* const form = useFormState({ defaultValues: { name: "John" } });
* // Inside an effect or event callback.
* form.setValues({ name: "Jane" });
* form.setValues((prevValues) => ({ ...prevValues, name: "John" }));
*/
setValues: SetState<FormState<V>["values"]>;
/**
* Retrieves a field value.
* @example
* const form = useFormState({ defaultValues: { firstName: "John" } });
* form.getValue(form.names.firstName); // "John"
*/
getValue: <T = any>(name: StringLike) => T;
/**
* Sets a field value.
* @example
* const form = useFormState({ defaultValues: { firstName: "John" } });
* // Inside an effect or event callback.
* form.setValue(form.names.firstName, "Jane");
* form.setValue(form.names.firstName, (prevValue) => `${prevValue} Doe`);
*/
setValue: <T>(name: StringLike, value: SetStateAction<T>) => void;
/**
* Pushes a value to an array field.
* @example
* const form = useFormState({ defaultValues: { tags: [] } });
* // Inside an effect or event callback.
* form.pushValue(form.names.tags, "tag");
*/
pushValue: <T>(name: StringLike, value: T) => void;
/**
* Removes a value from an array field.
* @example
* const form = useFormState({ defaultValues: { tags: ["tag"] } });
* // Inside an effect or event callback.
* form.removeValue(form.names.tags, 0);
*/
removeValue: (name: StringLike, index: number) => void;
/**
* Form errors.
*/
errors: DeepPartial<DeepMap<V, ErrorMessage>>;
/**
* Sets the `errors` state.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* // Inside an effect or event callback.
* form.setErrors({ name: "Name is required" });
*/
setErrors: SetState<FormState<V>["errors"]>;
/**
* Retrieves a field error.
* @example
* const form = useFormState({ defaultValues: { email: "" } });
* form.getError(form.names.email); // undefined
*/
getError: (name: StringLike) => ErrorMessage;
/**
* Sets a field error.
* @example
* const form = useFormState({ defaultValues: { email: "" } });
* form.useValidate(() => {
* if (!form.getValue(form.names.email)) {
* form.setError(form.names.email, "Email is required");
* }
* });
*/
setError: (name: StringLike, error: SetStateAction<ErrorMessage>) => void;
/**
* The touched state of the form.
*/
touched: DeepPartial<DeepMap<V, boolean>>;
/**
* Sets the `touched` state.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* // Inside an effect or event callback.
* form.setTouched({ name: true });
*/
setTouched: SetState<FormState<V>["touched"]>;
/**
* Retrieves a field touched state.
* @example
* const form = useFormState({ defaultValues: { email: "" } });
* form.getFieldTouched(form.names.email); // false
*/
getFieldTouched: (name: StringLike) => boolean;
/**
* Sets a field touched state.
* @example
* const form = useFormState({ defaultValues: { email: "" } });
* // Inside an effect or event callback.
* form.setFieldTouched(form.names.email, true);
* form.setFieldTouched(form.names.email, (prevTouched) => !prevTouched);
*/
setFieldTouched: (name: StringLike, value: SetStateAction<boolean>) => void;
/**
* An object containing the names of the form fields.
* @example
* const form = useFormState({
* defaultValues: { name: { first: "", last: "" } },
* });
* form.names.name; // "name"
* form.names.name.first; // "name.first"
* form.names.name.last; // "name.last"
*/
names: Names<V>;
/**
* Whether the form is valid.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* form.valid; // true
* // Inside an effect or event callback.
* form.setError(form.names.name, "Name is required");
* // On the next render.
* form.valid; // false
*/
valid: boolean;
/**
* Whether the form is validating.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* form.validating; // false
* // Inside an effect or event callback.
* form.validate();
* // On the next render.
* form.validating; // true
* // On the next render.
* form.validating; // false
*/
validating: boolean;
/**
* Validates the form by running all validation callbacks passed to
* `form.useValidate`.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* // Inside an effect or event callback.
* if (await form.validate()) {
* // Form is valid.
* }
*/
validate: () => Promise<boolean>;
/**
* Custom hook that accepts a callback that will be used to validate the form
* when `form.validate` is called.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* form.useValidate(async () => {
* const errors = await api.validate(form.values);
* if (errors) {
* form.setErrors(errors);
* }
* });
*/
useValidate: (callback: Callback) => void;
/**
* Whether the form is submitting.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* form.submitting; // false
* // Inside an effect or event callback.
* form.submit();
* // On the next render.
* form.submitting; // true
* // On the next render.
* form.submitting; // false
*/
submitting: boolean;
/**
* The number of times `form.submit` has been called with a successful
* response.
*/
submitSucceed: number;
/**
* The number of times `form.submit` has been called with an error response.
*/
submitFailed: number;
/**
* Submits the form by running all submit callbacks passed to
* `form.useSubmit`. This also triggers validation.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* // Inside an effect or event callback.
* if (await form.submit()) {
* // Form is submitted.
* }
*/
submit: () => Promise<boolean>;
/**
* Custom hook that accepts a callback that will be used to submit the form
* when `form.submit` is called.
* @example
* const form = useFormState({ defaultValues: { name: "" } });
* form.useSubmit(async () => {
* try {
* await api.submit(form.values);
* } catch (errors) {
* form.setErrors(errors);
* }
* });
*/
useSubmit: (callback: Callback) => void;
/**
* Resets the form to its default values.
*/
reset: () => void;
};
export type FormStateProps<V = AnyObject> = CollectionStateProps<Item> &
Partial<Pick<FormState<V>, "values" | "errors" | "touched">> & {
/**
* The default values of the form.
*/
defaultValues?: V;
/**
* The default errors of the form.
*/
defaultErrors?: FormState<V>["errors"];
/**
* The default touched state of the form.
*/
defaultTouched?: FormState<V>["touched"];
/**
* Function that will be called when setting the form `values` state.
* @example
* // Uncontrolled example
* useFormState({ setValues: (values) => console.log(values) });
* @example
* // Controlled example
* const [values, setValues] = useState({});
* useFormState({ values, setValues });
* @example
* // Externally controlled example
* function MyForm({ values, onChange }) {
* const form = useFormState({ values, setValues: onChange });
* }
*/
setValues?: (values: FormState<V>["values"]) => void;
/**
* Function that will be called when setting the form `errors` state.
* @example
* useFormState({ setErrors: (errors) => console.log(errors) });
*/
setErrors?: (errors: FormState<V>["errors"]) => void;
/**
* Function that will be called when setting the form `touched` state.
* @example
* useFormState({ setTouched: (touched) => console.log(touched) });
*/
setTouched?: (touched: FormState<V>["touched"]) => void;
}; | the_stack |
import * as React from 'react';
import { ownerDocument } from '@mui/material/utils';
import { GridApiRef } from '../../../models/api/gridApiRef';
import { GridPrintExportApi } from '../../../models/api/gridPrintExportApi';
import { useGridLogger } from '../../utils/useGridLogger';
import { visibleGridRowCountSelector } from '../filter/gridFilterSelector';
import { GridComponentProps } from '../../../GridComponentProps';
import { GridPrintExportOptions } from '../../../models/gridExport';
import { allGridColumnsSelector } from '../columns/gridColumnsSelector';
import {
gridDensityRowHeightSelector,
gridDensityHeaderHeightSelector,
} from '../density/densitySelector';
import { gridClasses } from '../../../gridClasses';
import { useGridState } from '../../utils/useGridState';
import { useGridSelector } from '../../utils/useGridSelector';
import { useGridApiMethod } from '../../utils/useGridApiMethod';
type PrintWindowOnLoad = (
printWindow: HTMLIFrameElement,
options?: Pick<
GridPrintExportOptions,
'copyStyles' | 'bodyClassName' | 'pageStyle' | 'hideToolbar' | 'hideFooter'
>,
) => void;
/**
* @requires useGridColumns (state)
* @requires useGridFilter (state)
* @requires useGridSorting (state)
* @requires useGridNoVirtualization (method)
* @requires useGridParamsApi (method)
*/
export const useGridPrintExport = (
apiRef: GridApiRef,
props: Pick<GridComponentProps, 'pagination'>,
): void => {
const logger = useGridLogger(apiRef, 'useGridPrintExport');
const [gridState, setGridState] = useGridState(apiRef);
const rowHeight = useGridSelector(apiRef, gridDensityRowHeightSelector);
const headerHeight = useGridSelector(apiRef, gridDensityHeaderHeightSelector);
const visibleRowCount = useGridSelector(apiRef, visibleGridRowCountSelector);
const columns = useGridSelector(apiRef, allGridColumnsSelector);
const doc = React.useRef<Document | null>(null);
const previousGridState = React.useRef<any>();
const previousHiddenColumns = React.useRef<string[]>([]);
React.useEffect(() => {
doc.current = ownerDocument(apiRef.current.rootElementRef!.current!);
}, [apiRef]);
// Returns a promise because updateColumns triggers state update and
// the new state needs to be in place before the grid can be sized correctly
const updateGridColumnsForPrint = React.useCallback(
(fields?: string[], allColumns?: boolean) =>
new Promise<void>((resolve) => {
if (!fields && !allColumns) {
resolve();
return;
}
// Show only wanted columns.
apiRef.current.updateColumns(
columns.map((column) => {
if (column.hide) {
previousHiddenColumns.current.push(column.field);
}
// Show all columns
if (allColumns) {
column.hide = false;
return column;
}
column.hide = !fields?.includes(column.field) || column.disableExport;
return column;
}),
);
resolve();
}),
[columns, apiRef],
);
const buildPrintWindow = React.useCallback((title?: string): HTMLIFrameElement => {
const iframeEl = document.createElement('iframe');
iframeEl.id = 'grid-print-window';
// Without this 'onload' event won't fire in some browsers
iframeEl.src = window.location.href;
iframeEl.style.position = 'absolute';
iframeEl.style.width = '0px';
iframeEl.style.height = '0px';
iframeEl.title = title || document.title;
return iframeEl;
}, []);
const handlePrintWindowLoad: PrintWindowOnLoad = React.useCallback(
(printWindow, options): void => {
const normalizeOptions = {
copyStyles: true,
hideToolbar: false,
hideFooter: false,
...options,
};
// Some agents, such as IE11 and Enzyme (as of 2 Jun 2020) continuously call the
// `onload` callback. This ensures that it is only called once.
printWindow.onload = null;
const printDoc = printWindow.contentDocument || printWindow.contentWindow?.document;
if (!printDoc) {
return;
}
const gridRootElement = apiRef.current.rootElementRef!.current;
const gridClone = gridRootElement!.cloneNode(true) as HTMLElement;
const gridCloneViewport: HTMLElement | null = gridClone.querySelector(
`.${gridClasses.virtualScroller}`,
);
// Expand the viewport window to prevent clipping
gridCloneViewport!.style.height = 'auto';
gridCloneViewport!.style.width = 'auto';
gridCloneViewport!.parentElement!.style.width = 'auto';
gridCloneViewport!.parentElement!.style.height = 'auto';
const columnsContainer = gridClone.querySelector(`.${gridClasses.columnsContainer}`);
const columnHeaders = columnsContainer!.firstChild! as HTMLElement;
columnHeaders.style.width = '100%';
let gridToolbarElementHeight =
gridRootElement!.querySelector(`.${gridClasses.toolbarContainer}`)?.clientHeight || 0;
let gridFooterElementHeight =
gridRootElement!.querySelector(`.${gridClasses.footerContainer}`)?.clientHeight || 0;
if (normalizeOptions.hideToolbar) {
gridClone.querySelector(`.${gridClasses.toolbarContainer}`)?.remove();
gridToolbarElementHeight = 0;
}
if (normalizeOptions.hideFooter) {
gridClone.querySelector(`.${gridClasses.footerContainer}`)?.remove();
gridFooterElementHeight = 0;
}
// Expand container height to accommodate all rows
gridClone.style.height = `${
visibleRowCount * rowHeight +
headerHeight +
gridToolbarElementHeight +
gridFooterElementHeight
}px`;
// Remove all loaded elements from the current host
printDoc.body.innerHTML = '';
printDoc.body.appendChild(gridClone);
const defaultPageStyle =
typeof normalizeOptions.pageStyle === 'function'
? normalizeOptions.pageStyle()
: normalizeOptions.pageStyle;
if (typeof defaultPageStyle === 'string') {
// TODO custom styles should always win
const styleElement = printDoc.createElement('style');
styleElement.appendChild(printDoc.createTextNode(defaultPageStyle));
printDoc.head.appendChild(styleElement);
}
if (normalizeOptions.bodyClassName) {
printDoc.body.classList.add(...normalizeOptions.bodyClassName.split(' '));
}
if (normalizeOptions.copyStyles) {
const headStyleElements = doc.current!.querySelectorAll("style, link[rel='stylesheet']");
for (let i = 0; i < headStyleElements.length; i += 1) {
const node = headStyleElements[i];
if (node.tagName === 'STYLE') {
const newHeadStyleElements = printDoc.createElement(node.tagName);
const sheet = (node as HTMLStyleElement).sheet;
if (sheet) {
let styleCSS = '';
// NOTE: for-of is not supported by IE
for (let j = 0; j < sheet.cssRules.length; j += 1) {
if (typeof sheet.cssRules[j].cssText === 'string') {
styleCSS += `${sheet.cssRules[j].cssText}\r\n`;
}
}
newHeadStyleElements.appendChild(printDoc.createTextNode(styleCSS));
printDoc.head.appendChild(newHeadStyleElements);
}
} else if (node.getAttribute('href')) {
// If `href` tag is empty, avoid loading these links
const newHeadStyleElements = printDoc.createElement(node.tagName);
for (let j = 0; j < node.attributes.length; j += 1) {
const attr = node.attributes[j];
if (attr) {
newHeadStyleElements.setAttribute(attr.nodeName, attr.nodeValue || '');
}
}
printDoc.head.appendChild(newHeadStyleElements);
}
}
}
// Trigger print
printWindow.contentWindow!.print();
},
[apiRef, doc, visibleRowCount, rowHeight, headerHeight],
);
const handlePrintWindowAfterPrint = React.useCallback(
(printWindow: HTMLIFrameElement): void => {
// Remove the print iframe
doc.current!.body.removeChild(printWindow);
// Revert grid to previous state
setGridState((state) => ({
...state,
...previousGridState.current,
}));
apiRef.current.UNSTABLE_enableVirtualization();
// Revert columns to their original state
if (previousHiddenColumns.current.length) {
apiRef.current.updateColumns(
columns.map((column) => {
column.hide = previousHiddenColumns.current.includes(column.field);
return column;
}),
);
}
// Clear local state
previousGridState.current = null;
previousHiddenColumns.current = [];
},
[columns, apiRef, setGridState],
);
const exportDataAsPrint = React.useCallback(
async (options?: GridPrintExportOptions) => {
logger.debug(`Export data as Print`);
if (!apiRef.current.rootElementRef!.current) {
throw new Error('MUI: No grid root element available.');
}
previousGridState.current = gridState;
if (props.pagination) {
apiRef.current.setPageSize(visibleRowCount);
}
await updateGridColumnsForPrint(options?.fields, options?.allColumns);
apiRef.current.UNSTABLE_disableVirtualization();
const printWindow = buildPrintWindow(options?.fileName);
doc.current!.body.appendChild(printWindow);
printWindow.onload = () => handlePrintWindowLoad(printWindow, options);
printWindow.contentWindow!.onafterprint = () => handlePrintWindowAfterPrint(printWindow);
},
[
visibleRowCount,
props,
logger,
apiRef,
gridState,
buildPrintWindow,
handlePrintWindowLoad,
handlePrintWindowAfterPrint,
updateGridColumnsForPrint,
],
);
const printExportApi: GridPrintExportApi = {
exportDataAsPrint,
};
useGridApiMethod(apiRef, printExportApi, 'GridPrintExportApi');
}; | the_stack |
import * as chai from 'chai';
import { ChaincodeStub } from 'fabric-shim';
import * as mockery from 'mockery';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';
import { Roles } from '../../constants';
import { EventType, Order, OrderStatus, Policy, PolicyType, UsageEvent, Vehicle, VehicleStatus } from '../assets';
import { AssetList, ParticipantList } from '../lists';
import { Insurer, Manufacturer, Organization } from '../organizations';
import { Participant } from '../participants';
import { VehicleManufactureNetClientIdentity } from '../utils/client-identity';
import { VehicleManufactureNetContext } from '../utils/context';
import { VehicleContract as VehicleContractImport } from './vehicle';
chai.should();
chai.use(sinonChai);
describe ('#VehicleContract', () => {
let VehicleContract;
let sandbox: sinon.SinonSandbox;
let contract: VehicleContractImport;
let ctx: sinon.SinonStubbedInstance<VehicleManufactureNetContext>;
let stub: sinon.SinonStubbedInstance<ChaincodeStub>;
let clientIdentity: sinon.SinonStubbedInstance<VehicleManufactureNetClientIdentity>;
let participantList: sinon.SinonStubbedInstance<ParticipantList>;
let orderList: sinon.SinonStubbedInstance<AssetList<Order>>;
let vehicleList: sinon.SinonStubbedInstance<AssetList<Vehicle>>;
let policyList: sinon.SinonStubbedInstance<AssetList<Policy>>;
let usageList: sinon.SinonStubbedInstance<AssetList<UsageEvent>>;
let participant: sinon.SinonStubbedInstance<Participant>;
let organization: sinon.SinonStubbedInstance<Organization>;
let generateIdStub: sinon.SinonStub;
before(() => {
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false,
});
});
beforeEach(() => {
generateIdStub = sinon.stub();
mockery.registerMock('../utils/functions', {
generateId: generateIdStub,
});
cleanCache();
VehicleContract = requireVehicleContract();
sandbox = sinon.createSandbox();
contract = new VehicleContract();
ctx = sinon.createStubInstance(VehicleManufactureNetContext);
stub = sinon.createStubInstance(ChaincodeStub);
clientIdentity = sinon.createStubInstance(VehicleManufactureNetClientIdentity);
participantList = sinon.createStubInstance(ParticipantList);
orderList = sinon.createStubInstance(AssetList);
vehicleList = sinon.createStubInstance(AssetList);
policyList = sinon.createStubInstance(AssetList);
usageList = sinon.createStubInstance(AssetList);
organization = sinon.createStubInstance(Organization);
participant = sinon.createStubInstance(Participant);
(clientIdentity as any)._participant = participant;
(clientIdentity as any)._organization = organization;
(ctx as any)._clientIdentity = clientIdentity;
(ctx as any).participantList = participantList;
(ctx as any).vehicleList = vehicleList;
(ctx as any).policyList = policyList;
(ctx as any).orderList = orderList;
(ctx as any).usageList = usageList;
(ctx as any).stub = stub;
});
afterEach(() => {
sandbox.restore();
});
after(() => {
mockery.deregisterAll();
mockery.disable();
});
describe ('placeOrder', () => {
const fakeVehicleDetails = {
colour: 'some colour',
makeId: 'some make',
modelType: 'some model',
};
const fakeOrder = {
extras: ['some', 'extra'],
interior: 'some interior',
trim: 'some trim',
};
it ('should error if the participant lacks the role to create orders', async () => {
participant.hasRole.returns(true).withArgs(Roles.ORDER_CREATE).returns(false);
await contract.placeOrder(
ctx as any, 'some orderer', fakeVehicleDetails, fakeOrder,
).should.be.rejectedWith(`Only callers with role ${Roles.ORDER_CREATE} can place orders`);
});
it ('should error if the participant is not from the same org as the requested vehicles make', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_CREATE).returns(true);
(participant as any).orgId = 'not' + fakeVehicleDetails.makeId;
await contract.placeOrder(
ctx as any, 'some orderer', fakeVehicleDetails, fakeOrder,
).should.be.rejectedWith('Callers may only create orders in their organisation');
});
it ('should place an order', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_CREATE).returns(true);
(participant as any).orgId = fakeVehicleDetails.makeId;
participantList.get.withArgs('some orderer').returns('something');
orderList.count.returns(100);
stub.getTxID.returns('some tx id');
stub.getTxTimestamp.returns({
getSeconds: () => {
return {
toInt: () => {
return 1;
},
};
},
});
generateIdStub.withArgs('some tx id', 'ORDER_100').returns('some id');
const expectedOrder = new Order(
'some id', fakeVehicleDetails, OrderStatus.PLACED, fakeOrder, 'some orderer', 1000,
);
(await contract.placeOrder(
ctx as any, 'some orderer', fakeVehicleDetails, fakeOrder,
)).should.deep.equal(expectedOrder);
orderList.add.should.have.been.calledOnceWithExactly(expectedOrder);
ctx.setEvent.should.have.been.calledOnceWithExactly('PLACE_ORDER', expectedOrder);
});
});
describe ('getOrders', () => {
it ('should error when the caller is not allowed to read orders', async () => {
participant.hasRole.returns(true).withArgs(Roles.ORDER_READ).returns(false);
await contract.getOrders(ctx as any).should.be.rejectedWith(
`Only callers with role ${Roles.ORDER_READ} can read orders`,
);
});
it ('should query with filters for manufacturer', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_READ).returns(true);
organization = sinon.createStubInstance(Manufacturer);
(organization as any).id = 'some org id';
(clientIdentity as any)._organization = organization;
const fakeOrder = sinon.createStubInstance(Order);
orderList.query.withArgs(
{ selector: { vehicleDetails: { makeId: organization.id } } },
).returns([fakeOrder]);
(await contract.getOrders(ctx as any)).should.deep.equal(
[fakeOrder],
);
});
it ('should query with filters for not manufacturer', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_READ).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
orderList.query.withArgs(
{},
).returns([fakeOrder]);
(await contract.getOrders(ctx as any)).should.deep.equal(
[fakeOrder],
);
});
});
describe ('getOrder', () => {
it ('should error when the caller is not allowed to read orders', async () => {
participant.hasRole.returns(true).withArgs(Roles.ORDER_READ).returns(false);
await contract.getOrder(ctx as any, 'some order id').should.be.rejectedWith(
`Only callers with role ${Roles.ORDER_READ} can read orders`,
);
});
it ('should error when manufacturer and not made by org', async () => {
participant.hasRole.returns(true).withArgs(Roles.ORDER_READ).returns(true);
(participant as any).orgId = 'some org';
organization = sinon.createStubInstance(Manufacturer);
(clientIdentity as any)._organization = organization;
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(true).withArgs('some org').returns(false);
orderList.get.withArgs('some order id').returns(fakeOrder);
await contract.getOrder(ctx as any, 'some order id').should.be.rejectedWith(
`Manufacturers may only read an order made by their organisation`,
);
});
it ('should return when the order is made by their org', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_READ).returns(true);
(participant as any).orgId = 'some org';
organization = sinon.createStubInstance(Manufacturer);
(clientIdentity as any)._organization = organization;
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(false).withArgs('some org').returns(true);
orderList.get.withArgs('some order id').resolves(fakeOrder);
(await contract.getOrder(ctx as any, 'some order id')).should.deep.equal(
fakeOrder,
);
});
it ('should return when the caller is not manufacturer', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_READ).returns(true);
(participant as any).orgId = 'some org';
const fakeOrder = sinon.createStubInstance(Order);
orderList.get.withArgs('some order id').resolves(fakeOrder);
(await contract.getOrder(ctx as any, 'some order id')).should.deep.equal(
fakeOrder,
);
fakeOrder.madeByOrg.should.have.not.been.called; // tslint:disable-line
});
});
describe ('getOrderHistory', () => {
it ('should return the history of an order', async () => {
sandbox.stub(contract, 'getOrder').rejects().withArgs(ctx as any, 'some order id').resolves();
orderList.getHistory.withArgs('some order id').resolves('some history');
(await contract.getOrderHistory(ctx as any, 'some order id')).should.deep.equal('some history');
});
});
describe ('scheduleOrderForManufacture', () => {
it ('should error when the caller is not allowed to update orders', async () => {
participant.hasRole.returns(true).withArgs(Roles.ORDER_UPDATE).returns(false);
await contract.scheduleOrderForManufacture(ctx as any, 'some order id').should.be.rejectedWith(
`Only callers with role ${Roles.ORDER_UPDATE} can schedule orders for manufacture`,
);
});
it ('should error when order was not made by org', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(false);
orderList.get.returns(fakeOrder);
await contract.scheduleOrderForManufacture(ctx as any, 'some order id').should.be.rejectedWith(
'Callers may only schedule an order in their organisation for manufacture',
);
});
it ('should update the order', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(true);
const fakeSetter = sinon.stub();
sandbox.stub(fakeOrder, 'orderStatus').set(fakeSetter);
orderList.get.returns(fakeOrder);
(await contract.scheduleOrderForManufacture(ctx as any, 'some order id')).should.deep.equal(
fakeOrder,
);
fakeSetter.should.have.been.calledOnceWithExactly(OrderStatus.SCHEDULED_FOR_MANUFACTURE);
orderList.update.should.have.been.calledOnceWithExactly(fakeOrder);
ctx.setEvent.should.have.been.calledOnceWithExactly('UPDATE_ORDER', fakeOrder);
});
});
describe ('registerVehicleForOrder', () => {
beforeEach(() => {
(organization as sinon.SinonStubbedInstance<Manufacturer>).originCode = 'some origin code';
(organization as sinon.SinonStubbedInstance<Manufacturer>).manufacturerCode = 'some manufacturer code';
});
it ('should error when the caller is not allowed to update orders', async () => {
participant.hasRole.returns(true).withArgs(Roles.ORDER_UPDATE).returns(false);
await contract.registerVehicleForOrder(ctx as any, 'some order id', 'some vin').should.be.rejectedWith(
`Only callers with roles ${Roles.ORDER_UPDATE} and ${Roles.VEHICLE_CREATE} can register vehicles for orders`, // tslint:disable-line
);
});
it ('should error when the caller is not allowed to create vehicles', async () => {
participant.hasRole.returns(true).withArgs(Roles.VEHICLE_CREATE).returns(false);
await contract.registerVehicleForOrder(ctx as any, 'some order id', 'some vin').should.be.rejectedWith(
`Only callers with roles ${Roles.ORDER_UPDATE} and ${Roles.VEHICLE_CREATE} can register vehicles for orders`, // tslint:disable-line
);
});
it ('should error when manufacturer manufacturer code not set', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true)
.withArgs(Roles.VEHICLE_CREATE).returns(true);
delete (organization as sinon.SinonStubbedInstance<Manufacturer>).originCode;
delete (organization as sinon.SinonStubbedInstance<Manufacturer>).manufacturerCode;
await contract.registerVehicleForOrder(ctx as any, 'some order id', 'some vin').should.be.rejectedWith(
'Manufacturer\'s origin and manufacturer code must be set before vehicles can be registered',
);
});
it ('should error when manufacturer origin code not set', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true)
.withArgs(Roles.VEHICLE_CREATE).returns(true);
delete (organization as sinon.SinonStubbedInstance<Manufacturer>).originCode;
await contract.registerVehicleForOrder(ctx as any, 'some order id', 'some vin').should.be.rejectedWith(
'Manufacturer\'s origin and manufacturer code must be set before vehicles can be registered',
);
});
it ('should error when order was not made by org', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true)
.withArgs(Roles.VEHICLE_CREATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(false);
orderList.get.returns(fakeOrder);
await contract.registerVehicleForOrder(ctx as any, 'some order id', 'some vin').should.be.rejectedWith(
'Callers may only register a vehicle for an order in their organisation',
);
});
it ('should error when vin was not valid', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true)
.withArgs(Roles.VEHICLE_CREATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(true);
orderList.get.returns(fakeOrder);
stub.getTxTimestamp.returns({
getSeconds: () => {
return {
toInt: () => {
return 1;
},
};
},
});
sandbox.stub(Vehicle, 'validateVin').returns(true)
.withArgs('some vin', organization as any, 1970).returns(false);
await contract.registerVehicleForOrder(ctx as any, 'some order id', 'some vin').should.be.rejectedWith(
'Invalid VIN supplied',
);
});
it ('should update the order', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true)
.withArgs(Roles.VEHICLE_CREATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(true);
stub.getTxTimestamp.returns({
getSeconds: () => {
return {
toInt: () => {
return 1;
},
};
},
});
sandbox.stub(Vehicle, 'validateVin').returns(false)
.withArgs('some vin', organization as any, 1970).returns(true);
const fakeStatusSetter = sinon.stub();
const fakeVinSetter = sinon.stub();
sandbox.stub(fakeOrder, 'orderStatus').set(fakeStatusSetter);
sandbox.stub(fakeOrder, 'vin').set(fakeVinSetter);
orderList.get.withArgs('some order id').returns(fakeOrder);
(await contract.registerVehicleForOrder(ctx as any, 'some order id', 'some vin')).should.deep.equal(
fakeOrder,
);
const fakeVehicle = new Vehicle('some vin', fakeOrder.vehicleDetails, VehicleStatus.OFF_THE_ROAD, 1000);
fakeStatusSetter.should.have.been.calledOnceWithExactly(OrderStatus.VIN_ASSIGNED);
fakeVinSetter.should.have.been.calledOnceWithExactly('some vin');
orderList.update.should.have.been.calledOnceWithExactly(fakeOrder);
vehicleList.add.should.have.been.calledOnceWithExactly(fakeVehicle);
ctx.setEvent.should.have.been.calledOnceWithExactly('UPDATE_ORDER', fakeOrder);
});
});
describe ('assignOwnershipForOrder', () => {
it ('should error when the caller is not allowed to update orders', async () => {
participant.hasRole.returns(true).withArgs(Roles.ORDER_UPDATE).returns(false);
await contract.assignOwnershipForOrder(ctx as any, 'some order id').should.be.rejectedWith(
`Only callers with roles ${Roles.ORDER_UPDATE} and ${Roles.VEHICLE_UPDATE} can assign ownership of vehicles of orders`, // tslint:disable-line
);
});
it ('should error when the caller is not allowed to create vehicles', async () => {
participant.hasRole.returns(true).withArgs(Roles.VEHICLE_UPDATE).returns(false);
await contract.assignOwnershipForOrder(ctx as any, 'some order id').should.be.rejectedWith(
`Only callers with roles ${Roles.ORDER_UPDATE} and ${Roles.VEHICLE_UPDATE} can assign ownership of vehicles of orders`, // tslint:disable-line
);
});
it ('should error when order was not made by org', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true)
.withArgs(Roles.VEHICLE_UPDATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(false);
orderList.get.returns(fakeOrder);
await contract.assignOwnershipForOrder(ctx as any, 'some order id').should.be.rejectedWith(
'Callers may only assign an owner for a vehicle of an order in their organisation',
);
});
it ('should update the order', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true)
.withArgs(Roles.VEHICLE_UPDATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(true);
fakeOrder.vin = 'some vin';
(fakeOrder as any)._ordererId = 'some orderer id';
const fakeVehicle = sinon.createStubInstance(Vehicle);
const fakeStatusSetter = sinon.stub();
const fakeOwnerIdSetter = sinon.stub();
sandbox.stub(fakeOrder, 'orderStatus').set(fakeStatusSetter);
sandbox.stub(fakeVehicle, 'ownerId').set(fakeOwnerIdSetter);
orderList.get.withArgs('some order id').returns(fakeOrder);
vehicleList.get.withArgs(fakeOrder.vin).returns(fakeVehicle);
(await contract.assignOwnershipForOrder(ctx as any, 'some order id')).should.deep.equal(
fakeOrder,
);
fakeStatusSetter.should.have.been.calledOnceWithExactly(OrderStatus.OWNER_ASSIGNED);
fakeOwnerIdSetter.should.have.been.calledOnceWithExactly(fakeOrder.ordererId);
orderList.update.should.have.been.calledOnceWithExactly(fakeOrder);
vehicleList.update.should.have.been.calledOnceWithExactly(fakeVehicle);
ctx.setEvent.should.have.been.calledOnceWithExactly('UPDATE_ORDER', fakeOrder);
});
});
describe ('deliverOrder', () => {
it ('should error when the caller is not allowed to update orders', async () => {
participant.hasRole.returns(true).withArgs(Roles.ORDER_UPDATE).returns(false);
await contract.deliverOrder(ctx as any, 'some order id').should.be.rejectedWith(
`Only callers with role ${Roles.ORDER_UPDATE} can deliver orders`,
);
});
it ('should error when order was not made by org', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(false);
orderList.get.returns(fakeOrder);
await contract.deliverOrder(ctx as any, 'some order id').should.be.rejectedWith(
'Callers may only deliver an order in their organisation',
);
});
it ('should update the order', async () => {
participant.hasRole.returns(false).withArgs(Roles.ORDER_UPDATE).returns(true);
const fakeOrder = sinon.createStubInstance(Order);
fakeOrder.madeByOrg.returns(true);
const fakeVehicle = sinon.createStubInstance(Vehicle);
const fakeOrderStatusSetter = sinon.stub();
const fakeVehicleStatusSetter = sinon.stub();
sandbox.stub(fakeOrder, 'orderStatus').set(fakeOrderStatusSetter);
sandbox.stub(fakeVehicle, 'vehicleStatus').set(fakeVehicleStatusSetter);
orderList.get.returns(fakeOrder);
vehicleList.get.withArgs(fakeOrder.vin).returns(fakeVehicle);
(await contract.deliverOrder(ctx as any, 'some order id')).should.deep.equal(
fakeOrder,
);
fakeOrderStatusSetter.should.have.been.calledOnceWithExactly(OrderStatus.DELIVERED);
fakeVehicleStatusSetter.should.have.been.calledOnceWithExactly(VehicleStatus.ACTIVE);
orderList.update.should.have.been.calledOnceWithExactly(fakeOrder);
vehicleList.update.should.have.been.calledOnceWithExactly(fakeVehicle);
ctx.setEvent.should.have.been.calledOnceWithExactly('UPDATE_ORDER', fakeOrder);
});
});
describe ('getVehicles', () => {
it ('should error when the caller is not allowed to read vehicles', async () => {
participant.hasRole.returns(true).withArgs(Roles.VEHICLE_READ).returns(false);
await contract.getVehicles(ctx as any).should.be.rejectedWith(
`Only callers with role ${Roles.VEHICLE_READ} can get vehicles`,
);
});
it ('should query with filters for manufacturer', async () => {
participant.hasRole.returns(false).withArgs(Roles.VEHICLE_READ).returns(true);
organization = sinon.createStubInstance(Manufacturer);
(clientIdentity as any)._organization = organization;
const fakeVehicle = sinon.createStubInstance(Vehicle);
vehicleList.query.withArgs(
{ selector: { vehicleDetails: { makeId: organization.id } } },
).returns([fakeVehicle]);
(await contract.getVehicles(ctx as any)).should.deep.equal(
[fakeVehicle],
);
});
it ('should query with filters for insurer', async () => {
participant.hasRole.returns(false).withArgs(Roles.VEHICLE_READ).returns(true);
organization = sinon.createStubInstance(Insurer);
(clientIdentity as any)._organization = organization;
const fakeVehicle = sinon.createStubInstance(Vehicle);
sandbox.stub(contract, 'getPolicies').withArgs(ctx as any).resolves([{vin: 'vin1'}, {vin: 'vin2'}]);
vehicleList.query.withArgs(
{ selector: { id: { $in: ['vin1', 'vin2'] } } },
).returns([fakeVehicle]);
(await contract.getVehicles(ctx as any)).should.deep.equal(
[fakeVehicle],
);
});
it ('should query with filters for not manufacturer or insurer', async () => {
participant.hasRole.returns(false).withArgs(Roles.VEHICLE_READ).returns(true);
const fakeVehicle = sinon.createStubInstance(Vehicle);
vehicleList.query.withArgs(
{},
).returns([fakeVehicle]);
(await contract.getVehicles(ctx as any)).should.deep.equal(
[fakeVehicle],
);
});
});
describe ('getVehicle', () => {
it ('should error when the caller is not allowed to read vehicles', async () => {
participant.hasRole.returns(true).withArgs(Roles.VEHICLE_READ).returns(false);
await contract.getVehicle(ctx as any, 'some vin').should.be.rejectedWith(
`Only callers with role ${Roles.VEHICLE_READ} can get vehicles`,
);
});
it ('should error when manufacturer and not made by org', async () => {
participant.hasRole.returns(true).withArgs(Roles.VEHICLE_READ).returns(true);
(participant as any).orgId = 'some org';
organization = sinon.createStubInstance(Manufacturer);
(clientIdentity as any)._organization = organization;
const fakeVehicle = sinon.createStubInstance(Vehicle);
fakeVehicle.madeByOrg.returns(true).withArgs('some org').returns(false);
vehicleList.get.withArgs('some vin').returns(fakeVehicle);
await contract.getVehicle(ctx as any, 'some vin').should.be.rejectedWith(
'Manufacturers may only get a vehicle produced by their organisation',
);
});
it ('should return when the order is made by their org', async () => {
participant.hasRole.returns(false).withArgs(Roles.VEHICLE_READ).returns(true);
(participant as any).orgId = 'some org';
organization = sinon.createStubInstance(Manufacturer);
(clientIdentity as any)._organization = organization;
const fakeVehicle = sinon.createStubInstance(Vehicle);
fakeVehicle.madeByOrg.returns(false).withArgs('some org').returns(true);
vehicleList.get.withArgs('some vin').resolves(fakeVehicle);
(await contract.getVehicle(ctx as any, 'some vin')).should.deep.equal(
fakeVehicle,
);
});
it ('should return when the caller is not manufacturer', async () => {
participant.hasRole.returns(false).withArgs(Roles.VEHICLE_READ).returns(true);
(participant as any).orgId = 'some org';
const fakeVehicle = sinon.createStubInstance(Vehicle);
vehicleList.get.withArgs('some vin').resolves(fakeVehicle);
(await contract.getVehicle(ctx as any, 'some vin')).should.deep.equal(
fakeVehicle,
);
fakeVehicle.madeByOrg.should.have.not.been.called; // tslint:disable-line
});
});
describe ('createPolicy', () => {
it ('should error when the caller is not allowed to create policies', async () => {
participant.hasRole.returns(true).withArgs(Roles.POLICY_CREATE).returns(false);
await contract.createPolicy(
ctx as any, 'some vin', 'some holder id', PolicyType.FULLY_COMPREHENSIVE, 1,
).should.be.rejectedWith(
`Only callers with role ${Roles.POLICY_CREATE} can create policies`,
);
});
it ('should error when vehicle is not in state to be insured', async () => {
participant.hasRole.returns(false).withArgs(Roles.POLICY_CREATE).returns(true);
const fakeVehicle = sinon.createStubInstance(Vehicle);
fakeVehicle.vehicleStatus = VehicleStatus.OFF_THE_ROAD;
vehicleList.get.withArgs('some vin').returns(fakeVehicle);
await contract.createPolicy(
ctx as any, 'some vin', 'some holder id', PolicyType.FULLY_COMPREHENSIVE, 1,
).should.be.rejectedWith(
'Cannot insure vehicle which is not active',
);
});
it ('should create insurance policy', async () => {
participant.hasRole.returns(false).withArgs(Roles.POLICY_CREATE).returns(true);
(participant as any).orgId = 'some org';
const fakeVehicle = sinon.createStubInstance(Vehicle);
fakeVehicle.vehicleStatus = VehicleStatus.ACTIVE;
vehicleList.get.withArgs('some vin').returns(fakeVehicle);
policyList.count.returns(100);
stub.getTxID.returns('some tx id');
stub.getTxTimestamp.returns({
getSeconds: () => {
return {
toInt: () => {
return 1;
},
};
},
});
generateIdStub.withArgs('some tx id', 'POLICY_100').returns('some id');
const expectedPolicy = new Policy(
'some id', 'some vin', 'some org', 'some holder id', PolicyType.FULLY_COMPREHENSIVE, 1000, 2000,
);
(await contract.createPolicy(
ctx as any, 'some vin', 'some holder id', PolicyType.FULLY_COMPREHENSIVE, 2000,
)).should.deep.equal(expectedPolicy);
policyList.add.should.have.been.calledOnceWithExactly(expectedPolicy);
ctx.setEvent.should.have.been.calledOnceWithExactly('CREATE_POLICY', expectedPolicy);
});
});
describe ('getPolicies', () => {
it ('should error when the caller is not allowed to read policies', async () => {
participant.hasRole.returns(true).withArgs(Roles.POLICY_READ).returns(false);
await contract.getPolicies(ctx as any).should.be.rejectedWith(
`Only callers with role ${Roles.POLICY_READ} can read policies`,
);
});
it ('should query with filters for insurer', async () => {
participant.hasRole.returns(false).withArgs(Roles.POLICY_READ).returns(true);
organization = sinon.createStubInstance(Insurer);
(organization as any).id = 'some org id';
(clientIdentity as any)._organization = organization;
const fakePolicy = sinon.createStubInstance(Policy);
policyList.query.withArgs(
{ selector: { insurerId: organization.id } },
).returns([fakePolicy]);
(await contract.getPolicies(ctx as any)).should.deep.equal(
[fakePolicy],
);
});
it ('should query with filters for not insurer', async () => {
participant.hasRole.returns(false).withArgs(Roles.POLICY_READ).returns(true);
const fakePolicy = sinon.createStubInstance(Policy);
policyList.query.withArgs(
{},
).returns([fakePolicy]);
(await contract.getPolicies(ctx as any)).should.deep.equal(
[fakePolicy],
);
});
});
describe ('getPolicy', () => {
it ('should error when the caller is not allowed to read policies', async () => {
participant.hasRole.returns(true).withArgs(Roles.POLICY_READ).returns(false);
await contract.getPolicy(ctx as any, 'some policy id').should.be.rejectedWith(
`Only callers with role ${Roles.POLICY_READ} can read policies`,
);
});
it ('should error when insurer and not their policy', async () => {
participant.hasRole.returns(false).withArgs(Roles.POLICY_READ).returns(true);
organization = sinon.createStubInstance(Insurer);
(organization as any).id = 'some org';
(clientIdentity as any)._organization = organization;
const fakePolicy = sinon.createStubInstance(Policy);
(fakePolicy as any).insurerId = 'some other org';
policyList.get.withArgs('some policy id').returns(fakePolicy);
await contract.getPolicy(ctx as any, 'some policy id').should.be.rejectedWith(
'Only insurers who insure the policy can view it',
);
});
it ('should return when the policy is owned by their org', async () => {
participant.hasRole.returns(false).withArgs(Roles.POLICY_READ).returns(true);
organization = sinon.createStubInstance(Insurer);
(organization as any).id = 'some org';
(clientIdentity as any)._organization = organization;
const fakePolicy = sinon.createStubInstance(Policy);
(fakePolicy as any).insurerId = 'some org';
policyList.get.withArgs('some policy id').resolves(fakePolicy);
(await contract.getPolicy(ctx as any, 'some policy id')).should.deep.equal(
fakePolicy,
);
});
it ('should return when the caller is not manufacturer', async () => {
participant.hasRole.returns(false).withArgs(Roles.POLICY_READ).returns(true);
const fakePolicy = sinon.createStubInstance(Policy);
policyList.get.withArgs('some policy id').resolves(fakePolicy);
(await contract.getPolicy(ctx as any, 'some policy id')).should.deep.equal(
fakePolicy,
);
});
});
describe ('addUsageEvent', async () => {
it ('should error when the caller is not allowed to create usage event', async () => {
participant.hasRole.returns(true).withArgs(Roles.USAGE_EVENT_CREATE).returns(false);
await contract.addUsageEvent(
ctx as any, 'some vin', EventType.CRASHED, 1, 20, 50, 100, 1, 1,
).should.be.rejectedWith(
`Only callers with role ${Roles.USAGE_EVENT_CREATE} can add usage events`,
);
});
it ('should add a usage event', async () => {
participant.hasRole.returns(false).withArgs(Roles.USAGE_EVENT_CREATE).returns(true);
sinon.stub(contract, 'getVehicle').rejects('stub called with bad args')
.withArgs(ctx as any, 'some vin').resolves();
stub.getTxID.returns('some tx id');
stub.getTxTimestamp.returns({
getSeconds: () => {
return {
toInt: () => {
return 1;
},
};
},
});
generateIdStub.withArgs('some tx id', EventType.CRASHED.toString()).returns('some id');
const expectedUsageEvent = new UsageEvent(
'some id', EventType.CRASHED, 1, 20, 50, 100, 1, 1, 1000, 'some vin',
);
(await contract.addUsageEvent(
ctx as any, 'some vin', EventType.CRASHED, 1, 20, 50, 100, 1, 1,
)).should.deep.equal(expectedUsageEvent);
usageList.add.should.have.been.calledOnceWithExactly(expectedUsageEvent);
ctx.setEvent.should.have.been.calledOnceWithExactly('ADD_USAGE_EVENT', expectedUsageEvent);
});
});
describe ('getUsageEvents', async () => {
it ('should error when the caller is not allowed to read usage events', async () => {
participant.hasRole.returns(true).withArgs(Roles.USAGE_EVENT_READ).returns(false);
await contract.getUsageEvents(
ctx as any,
).should.be.rejectedWith(
`Only callers with role ${Roles.USAGE_EVENT_READ} can get usage events`,
);
});
it ('should return all usage events', async () => {
participant.hasRole.returns(false).withArgs(Roles.USAGE_EVENT_READ).returns(true);
sandbox.stub(contract, 'getVehicles')
.withArgs(ctx as any).resolves([{id: 'vin 1'}, {id: 'vin 2'}]);
sandbox.stub(contract, 'getVehicleEvents')
.withArgs(ctx as any, 'vin 1').resolves(['EVENT VIN 1 1', 'EVENT VIN 1 2'])
.withArgs(ctx as any, 'vin 2').resolves(['EVENT VIN 2 1', 'EVENT VIN 2 2']);
(await contract.getUsageEvents(ctx as any)).should.deep.equal(
['EVENT VIN 1 1', 'EVENT VIN 1 2', 'EVENT VIN 2 1', 'EVENT VIN 2 2'],
);
});
});
describe ('getUsageEvents', async () => {
it ('should error when get vehicle errors', async () => {
sandbox.stub(contract, 'getVehicle').resolves()
.withArgs(ctx as any, 'some vin').rejects(Error('some error'));
await contract.getVehicleEvents(
ctx as any, 'some vin',
).should.be.rejectedWith(
`some error`,
);
});
it ('should error when the caller is not allowed to read usage events', async () => {
sandbox.stub(contract, 'getVehicle').resolves();
participant.hasRole.returns(true).withArgs(Roles.USAGE_EVENT_READ).returns(false);
await contract.getVehicleEvents(
ctx as any, 'some vin',
).should.be.rejectedWith(
`Only callers with role ${Roles.USAGE_EVENT_READ} can get usage events`,
);
});
it ('should return the usage events of a vehicle', async () => {
sandbox.stub(contract, 'getVehicle').resolves();
participant.hasRole.returns(false).withArgs(Roles.USAGE_EVENT_READ).returns(true);
usageList.query.withArgs({selector: {vin: 'some vin'}}).resolves(['some', 'usage', 'events']);
(await contract.getVehicleEvents(ctx as any, 'some vin')).should.deep.equal(['some', 'usage', 'events']);
});
});
describe ('getPolicyEvents', async () => {
const fakePolicy = {
endDate: 2000,
startDate: 1000,
vin: 'some vin',
};
it ('should error when get policy errors', async () => {
sandbox.stub(contract, 'getPolicy').resolves()
.withArgs(ctx as any, 'some policy id').rejects(Error('some error'));
await contract.getPolicyEvents(
ctx as any, 'some policy id',
).should.be.rejectedWith(
`some error`,
);
});
it ('should error when get policy errors', async () => {
sandbox.stub(contract, 'getPolicy').rejects()
.withArgs(ctx as any, 'some policy id').resolves(fakePolicy);
sandbox.stub(contract, 'getVehicle').resolves()
.withArgs(ctx as any, fakePolicy.vin).rejects(Error('some error'));
await contract.getPolicyEvents(
ctx as any, 'some policy id',
).should.be.rejectedWith(
`some error`,
);
});
it ('should error when the caller is not allowed to read usage events', async () => {
sandbox.stub(contract, 'getPolicy').rejects()
.withArgs(ctx as any, 'some policy id').resolves(fakePolicy);
sandbox.stub(contract, 'getVehicle').resolves();
participant.hasRole.returns(true).withArgs(Roles.USAGE_EVENT_READ).returns(false);
await contract.getPolicyEvents(
ctx as any, 'some policy id',
).should.be.rejectedWith(
`Only callers with role ${Roles.USAGE_EVENT_READ} can get usage events`,
);
});
it ('should return the usage events of a vehicle', async () => {
sandbox.stub(contract, 'getPolicy').rejects()
.withArgs(ctx as any, 'some policy id').resolves(fakePolicy);
sandbox.stub(contract, 'getVehicle').resolves();
participant.hasRole.returns(false).withArgs(Roles.USAGE_EVENT_READ).returns(true);
usageList.query.withArgs({
selector: {vin: fakePolicy.vin, timestamp: {$gte: fakePolicy.startDate, $lt: fakePolicy.endDate }},
}).resolves(['some', 'usage', 'events']);
(await contract.getPolicyEvents(ctx as any, 'some policy id'))
.should.deep.equal(['some', 'usage', 'events']);
});
});
});
function requireVehicleContract() {
return require('./vehicle.ts').VehicleContract;
}
function cleanCache() {
delete require.cache[require.resolve('./vehicle.ts')];
} | the_stack |
import fs from 'fs';
import path from 'path';
import {Plugin} from 'rollup';
import execa from 'execa';
import {VM as VM2} from 'vm2';
import {AbstractLogger, InstallTarget} from '../types';
import {getWebDependencyName, isJavaScript, isRemoteUrl, isTruthy} from '../util';
import isValidIdentifier from 'is-valid-identifier';
import resolve from 'resolve';
// Use CJS intentionally here! ESM interface is async but CJS is sync, and this file is sync
const {parse} = require('cjs-module-lexer');
function isValidNamedExport(name: string): boolean {
return name !== 'default' && name !== '__esModule' && isValidIdentifier(name);
}
// Add popular CJS/UMD packages here that use "synthetic" named imports in their documentation.
// Our scanner can statically scan most packages without an opt-in here, but these packages
// are built oddly, in a way that we can't statically analyze.
const TRUSTED_CJS_PACKAGES = ['chai/index.js', 'events/events.js', 'uuid/index.js'];
// These packages are written in such a way that the official CJS scanner succeeds at scanning
// the file but fails to pick up some exports. Add popular packages here to save everyone a bit
// of headache.
// We use the exact file here to match the official package, but not any ESM aliase packages
// that the user may have installed instead (ex: react-esm).
const UNSCANNABLE_CJS_PACKAGES = [
'chai/index.js',
'events/events.js',
'property-expr/index.js',
// Note: resolved in v4.x release
'react-transition-group/index.js',
];
/**
* rollup-plugin-wrap-install-targets
*
* How it works:
* 1. An array of "install targets" are passed in, describing all known imports + metadata.
* 2. If isTreeshake: Known imports are marked for tree-shaking by appending 'snowpack-wrap:' to the input value.
* 3. If autoDetectPackageExports match: Also mark for wrapping, and use automatic export detection.
* 4. On load, we return a false virtual file for all "snowpack-wrap:" inputs.
* a. That virtual file contains only `export ... from 'ACTUAL_FILE_PATH';` exports
* b. Rollup uses those exports to drive its tree-shaking algorithm.
* c. Rollup uses those exports to inform its "namedExports" for Common.js entrypoints.
*/
export function rollupPluginWrapInstallTargets(
isTreeshake: boolean,
installTargets: InstallTarget[],
logger: AbstractLogger,
): Plugin {
const installTargetSummaries: {[loc: string]: InstallTarget} = {};
const cjsScannedNamedExports = new Map<string, string[]>();
/**
* Attempt #1: Static analysis: Lower Fidelity, but faster.
* Do our best job to statically scan a file for named exports. This uses "cjs-module-lexer", the
* same CJS export scanner that Node.js uses internally. Very fast, but only works on some modules,
* depending on how they were build/written/compiled.
*/
function cjsAutoDetectExportsStatic(filename: string, visited = new Set()): string[] | undefined {
const isMainEntrypoint = visited.size === 0;
// Prevent infinite loops via circular dependencies.
if (visited.has(filename)) {
return [];
} else {
visited.add(filename);
}
const fileContents = fs.readFileSync(filename, 'utf8');
try {
// Attempt 1 - CJS: Run cjs-module-lexer to statically analyze exports.
let {exports, reexports} = parse(fileContents);
// If re-exports were detected (`exports.foo = require(...)`) then resolve them here.
let resolvedReexports: string[] = [];
if (reexports.length > 0) {
resolvedReexports = ([] as string[]).concat.apply(
[],
reexports
.map((e) =>
cjsAutoDetectExportsStatic(
resolve.sync(e, {basedir: path.dirname(filename)}),
visited,
),
)
.filter(isTruthy),
);
}
// If nothing was detected, return undefined.
// Otherwise, resolve and flatten all exports into a single array, remove invalid exports.
const resolvedExports = Array.from(new Set([...exports, ...resolvedReexports])).filter(
isValidNamedExport,
);
return isMainEntrypoint && resolvedExports.length === 0 ? undefined : resolvedExports;
} catch (err) {
// Safe to ignore, this is usually due to the file not being CJS.
logger.debug(`cjsAutoDetectExportsStatic ${filename}: ${err.message}`);
}
}
/**
* Attempt #2a - Runtime analysis: More powerful, but slower. (trusted code)
* This function spins off a Node.js process to analyze the most accurate set of named imports that this
* module supports. If this fails, there's not much else possible that we could do.
*
* We consider this "trusted" because it will actually run the package code in Node.js on your machine.
* Since this is code that you are intentionally bundling into your application, we consider this fine
* for most users and equivilent to the current security story of Node.js/npm. But, if you are operating
* a service that runs esinstall on arbitrary code, you should set `process.env.ESINSTALL_UNTRUSTED_ENVIRONMENT`
* so that this is skipped.
*/
function cjsAutoDetectExportsRuntimeTrusted(normalizedFileName: string): string[] | undefined {
// Skip if set to not trust package code (besides a few popular, always-trusted packages).
if (
process.env.ESINSTALL_UNTRUSTED_ENVIRONMENT &&
!TRUSTED_CJS_PACKAGES.includes(normalizedFileName)
) {
return undefined;
}
try {
const {stdout} = execa.sync(
`node`,
['-p', `JSON.stringify(Object.keys(require('${normalizedFileName}')))`],
{
cwd: __dirname,
extendEnv: false,
},
);
const exportsResult = JSON.parse(stdout).filter(isValidNamedExport);
logger.debug(`cjsAutoDetectExportsRuntime success ${normalizedFileName}: ${exportsResult}`);
return exportsResult;
} catch (err) {
logger.debug(`cjsAutoDetectExportsRuntime error ${normalizedFileName}: ${err.message}`);
}
}
/**
* Attempt #2b - Sandboxed runtime analysis: More powerful, but slower.
* This will only work on UMD and very simple CJS files (require not supported).
* Uses VM2 to run safely sandbox untrusted code (no access no Node.js primitives, just JS).
* If nothing was detected, return undefined.
*/
function cjsAutoDetectExportsRuntimeUntrusted(filename: string): string[] | undefined {
try {
const fileContents = fs.readFileSync(filename, 'utf8');
const vm = new VM2({wasm: false, fixAsync: false});
const exportsResult = Object.keys(
vm.run('const exports={}; const module={exports}; ' + fileContents + ';; module.exports;'),
);
logger.debug(`cjsAutoDetectExportsRuntimeUntrusted success ${filename}: ${exportsResult}`);
return exports.filter((identifier) => isValidIdentifier(identifier));
} catch (err) {
logger.debug(`cjsAutoDetectExportsRuntimeUntrusted error ${filename}: ${err.message}`);
}
}
return {
name: 'snowpack:wrap-install-targets',
// Mark some inputs for tree-shaking.
buildStart(inputOptions) {
const input = inputOptions.input as {[entryAlias: string]: string};
for (const [key, val] of Object.entries(input)) {
if (isRemoteUrl(val)) {
continue;
}
if (!isJavaScript(val)) {
continue;
}
const allInstallTargets = installTargets.filter(
(imp) => getWebDependencyName(imp.specifier) === key,
);
const installTargetSummary = allInstallTargets.reduce((summary, imp) => {
summary.all = summary.all || imp.all;
summary.default = summary.default || imp.default || imp.all;
summary.namespace = summary.namespace || imp.namespace || imp.all;
summary.named = [...(summary.named || []), ...imp.named];
return summary;
}, {} as any);
installTargetSummaries[val] = installTargetSummary;
const normalizedFileLoc = val.split(path.win32.sep).join(path.posix.sep);
const knownBadPackage = UNSCANNABLE_CJS_PACKAGES.some((p) =>
normalizedFileLoc.includes(`node_modules/${p}${p.endsWith('.js') ? '' : '/'}`),
);
const cjsExports =
// If we can trust the static analyzer, run that first.
(!knownBadPackage && cjsAutoDetectExportsStatic(val)) ||
// Otherwise, run our more powerful, runtime analysis.
// Attempted trusted first (won't run in untrusted environments).
cjsAutoDetectExportsRuntimeTrusted(normalizedFileLoc) ||
cjsAutoDetectExportsRuntimeUntrusted(normalizedFileLoc);
if (cjsExports && cjsExports.length > 0) {
cjsScannedNamedExports.set(normalizedFileLoc, cjsExports);
input[key] = `snowpack-wrap:${val}`;
}
if (isTreeshake && !installTargetSummary.all) {
input[key] = `snowpack-wrap:${val}`;
}
}
},
resolveId(source) {
if (source.startsWith('snowpack-wrap:')) {
return source;
}
return null;
},
load(id) {
if (!id.startsWith('snowpack-wrap:')) {
return null;
}
const fileLoc = id.substring('snowpack-wrap:'.length);
// Reduce all install targets into a single "summarized" install target.
const installTargetSummary = installTargetSummaries[fileLoc];
let uniqueNamedExports = Array.from(new Set(installTargetSummary.named));
const normalizedFileLoc = fileLoc.split(path.win32.sep).join(path.posix.sep);
const scannedNamedExports = cjsScannedNamedExports.get(normalizedFileLoc);
if (scannedNamedExports && (!isTreeshake || installTargetSummary.namespace)) {
uniqueNamedExports = scannedNamedExports || [];
installTargetSummary.default = true;
}
const result = `
${installTargetSummary.namespace ? `export * from '${normalizedFileLoc}';` : ''}
${
installTargetSummary.default
? `import __pika_web_default_export_for_treeshaking__ from '${normalizedFileLoc}'; export default __pika_web_default_export_for_treeshaking__;`
: ''
}
${`export {${uniqueNamedExports.join(',')}} from '${normalizedFileLoc}';`}
`;
return result;
},
};
} | the_stack |
import 'jasmine';
import {Status} from '@pigweed/pw_status';
import {MessageCreator} from '@pigweed/pw_protobuf_compiler';
import {Message} from 'google-protobuf';
import {
PacketType,
RpcPacket,
} from 'packet_proto_tspb/packet_proto_tspb_pb/pw_rpc/internal/packet_pb';
import {ProtoCollection} from 'rpc_proto_collection/generated/ts_proto_collection';
import {
Request,
Response,
} from 'test_protos_tspb/test_protos_tspb_pb/pw_rpc/ts/test_pb';
import {Client} from './client';
import {Channel, Method} from './descriptors';
import {
BidirectionalStreamingMethodStub,
ClientStreamingMethodStub,
ServerStreamingMethodStub,
UnaryMethodStub,
} from './method';
import * as packets from './packets';
const TEST_PROTO_PATH = 'pw_rpc/ts/test_protos-descriptor-set.proto.bin';
describe('Client', () => {
let protoCollection: ProtoCollection;
let client: Client;
let lastPacketSent: RpcPacket;
beforeEach(() => {
protoCollection = new ProtoCollection();
const channels = [new Channel(1, savePacket), new Channel(5)];
client = Client.fromProtoSet(channels, protoCollection);
});
function savePacket(packetBytes: Uint8Array): void {
lastPacketSent = RpcPacket.deserializeBinary(packetBytes);
}
it('channel returns undefined for empty list', () => {
const channels = Array<Channel>();
const emptyChannelClient = Client.fromProtoSet(channels, protoCollection);
expect(emptyChannelClient.channel()).toBeUndefined();
});
it('fetches channel or returns undefined', () => {
expect(client.channel(1)!.channel.id).toEqual(1);
expect(client.channel(5)!.channel.id).toEqual(5);
expect(client.channel()!.channel.id).toEqual(1);
expect(client.channel(2)).toBeUndefined();
});
it('ChannelClient fetches method by name', () => {
const channel = client.channel()!;
const stub = channel.methodStub('pw.rpc.test1.TheTestService.SomeUnary')!;
expect(stub.method.name).toEqual('SomeUnary');
});
it('ChannelClient for unknown name returns undefined', () => {
const channel = client.channel()!;
expect(channel.methodStub('')).toBeUndefined();
expect(
channel.methodStub('pw.rpc.test1.Garbage.SomeUnary')
).toBeUndefined();
expect(
channel.methodStub('pw.rpc.test1.TheTestService.Garbage')
).toBeUndefined();
});
it('processPacket with invalid proto data', () => {
const textEncoder = new TextEncoder();
const data = textEncoder.encode('NOT a packet!');
expect(client.processPacket(data)).toEqual(Status.DATA_LOSS);
});
it('processPacket not for client', () => {
const packet = new RpcPacket();
packet.setType(PacketType.REQUEST);
const processStatus = client.processPacket(packet.serializeBinary());
expect(processStatus).toEqual(Status.INVALID_ARGUMENT);
});
it('processPacket for unrecognized channel', () => {
const packet = packets.encodeResponse([123, 456, 789], new Request());
expect(client.processPacket(packet)).toEqual(Status.NOT_FOUND);
});
it('processPacket for unrecognized service', () => {
const packet = packets.encodeResponse([1, 456, 789], new Request());
const status = client.processPacket(packet);
expect(client.processPacket(packet)).toEqual(Status.OK);
expect(lastPacketSent.getChannelId()).toEqual(1);
expect(lastPacketSent.getServiceId()).toEqual(456);
expect(lastPacketSent.getMethodId()).toEqual(789);
expect(lastPacketSent.getType()).toEqual(PacketType.CLIENT_ERROR);
expect(lastPacketSent.getStatus()).toEqual(Status.NOT_FOUND);
});
it('processPacket for unrecognized method', () => {
const service = client.services.values().next().value;
const packet = packets.encodeResponse([1, service.id, 789], new Request());
const status = client.processPacket(packet);
expect(client.processPacket(packet)).toEqual(Status.OK);
expect(lastPacketSent.getChannelId()).toEqual(1);
expect(lastPacketSent.getServiceId()).toEqual(service.id);
expect(lastPacketSent.getMethodId()).toEqual(789);
expect(lastPacketSent.getType()).toEqual(PacketType.CLIENT_ERROR);
expect(lastPacketSent.getStatus()).toEqual(Status.NOT_FOUND);
});
it('processPacket for non-pending method', () => {
const service = client.services.values().next().value;
const method = service.methods.values().next().value;
const packet = packets.encodeResponse(
[1, service.id, method.id],
new Request()
);
const status = client.processPacket(packet);
expect(client.processPacket(packet)).toEqual(Status.OK);
expect(lastPacketSent.getChannelId()).toEqual(1);
expect(lastPacketSent.getServiceId()).toEqual(service.id);
expect(lastPacketSent.getMethodId()).toEqual(method.id);
expect(lastPacketSent.getType()).toEqual(PacketType.CLIENT_ERROR);
expect(lastPacketSent.getStatus()).toEqual(Status.FAILED_PRECONDITION);
});
});
describe('RPC', () => {
let protoCollection: ProtoCollection;
let client: Client;
let lastPacketSent: RpcPacket | undefined;
let requests: RpcPacket[] = [];
let nextPackets: [Uint8Array, Status][] = [];
let responseLock = false;
let sendResponsesAfterPackets = 0;
let outputException: Error | undefined;
beforeEach(async () => {
protoCollection = new ProtoCollection();
const channels = [new Channel(1, handlePacket), new Channel(2, () => {})];
client = Client.fromProtoSet(channels, protoCollection);
lastPacketSent = undefined;
requests = [];
nextPackets = [];
responseLock = false;
sendResponsesAfterPackets = 0;
outputException = undefined;
});
function newRequest(magicNumber = 123): Message {
const request = new Request();
request.setMagicNumber(magicNumber);
return request;
}
function newResponse(payload = '._.'): Message {
const response = new Response();
response.setPayload(payload);
return response;
}
function enqueueResponse(
channelId: number,
method: Method,
status: Status,
response?: Message
) {
const packet = new RpcPacket();
packet.setType(PacketType.RESPONSE);
packet.setChannelId(channelId);
packet.setServiceId(method.service.id);
packet.setMethodId(method.id);
packet.setStatus(status);
if (response === undefined) {
packet.setPayload(new Uint8Array());
} else {
packet.setPayload(response.serializeBinary());
}
nextPackets.push([packet.serializeBinary(), Status.OK]);
}
function enqueueServerStream(
channelId: number,
method: Method,
response: Message,
status: Status = Status.OK
) {
const packet = new RpcPacket();
packet.setType(PacketType.SERVER_STREAM);
packet.setChannelId(channelId);
packet.setServiceId(method.service.id);
packet.setMethodId(method.id);
packet.setPayload(response.serializeBinary());
packet.setStatus(status);
nextPackets.push([packet.serializeBinary(), status]);
}
function enqueueError(
channelId: number,
method: Method,
status: Status,
processStatus: Status
) {
const packet = new RpcPacket();
packet.setType(PacketType.SERVER_ERROR);
packet.setChannelId(channelId);
packet.setServiceId(method.service.id);
packet.setMethodId(method.id);
packet.setStatus(status);
nextPackets.push([packet.serializeBinary(), processStatus]);
}
function lastRequest(): RpcPacket {
if (requests.length == 0) {
throw Error('Tried to fetch request from empty list');
}
return requests[requests.length - 1];
}
function sentPayload(messageType: typeof Message): any {
return messageType.deserializeBinary(lastRequest().getPayload_asU8());
}
function handlePacket(data: Uint8Array): void {
if (outputException !== undefined) {
throw outputException;
}
requests.push(packets.decode(data));
if (sendResponsesAfterPackets > 1) {
sendResponsesAfterPackets -= 1;
return;
}
processEnqueuedPackets();
}
function processEnqueuedPackets(): void {
// Avoid infinite recursion when processing a packet causes another packet
// to send.
responseLock = true;
for (const [packet, status] of nextPackets) {
expect(client.processPacket(packet)).toEqual(status);
}
nextPackets = [];
responseLock = false;
}
describe('Unary', () => {
let unaryStub: UnaryMethodStub;
beforeEach(async () => {
unaryStub = client
.channel()
?.methodStub(
'pw.rpc.test1.TheTestService.SomeUnary'
)! as UnaryMethodStub;
});
it('blocking call', async () => {
for (let i = 0; i < 3; i++) {
enqueueResponse(
1,
unaryStub.method,
Status.ABORTED,
newResponse('0_o')
);
const [status, response] = await unaryStub.call(newRequest(6));
expect(sentPayload(Request).getMagicNumber()).toEqual(6);
expect(status).toEqual(Status.ABORTED);
expect(response).toEqual(newResponse('0_o'));
}
});
it('nonblocking call', () => {
for (let i = 0; i < 3; i++) {
const response = newResponse('hello world');
enqueueResponse(1, unaryStub.method, Status.ABORTED, response);
const onNext = jasmine.createSpy();
const onCompleted = jasmine.createSpy();
const onError = jasmine.createSpy();
const call = unaryStub.invoke(
newRequest(5),
onNext,
onCompleted,
onError
);
expect(sentPayload(Request).getMagicNumber()).toEqual(5);
expect(onNext).toHaveBeenCalledOnceWith(response);
expect(onError).not.toHaveBeenCalled();
expect(onCompleted).toHaveBeenCalledOnceWith(Status.ABORTED);
}
});
it('open', () => {
outputException = Error('Error should be ignored');
for (let i = 0; i < 3; i++) {
const response = newResponse('hello world');
enqueueResponse(1, unaryStub.method, Status.ABORTED, response);
const onNext = jasmine.createSpy();
const onCompleted = jasmine.createSpy();
const onError = jasmine.createSpy();
unaryStub.open(newRequest(5), onNext, onCompleted, onError);
expect(requests).toHaveSize(0);
processEnqueuedPackets();
expect(onNext).toHaveBeenCalledOnceWith(response);
expect(onError).not.toHaveBeenCalled();
expect(onCompleted).toHaveBeenCalledOnceWith(Status.ABORTED);
}
});
it('blocking server error', async () => {
for (let i = 0; i < 3; i++) {
enqueueError(1, unaryStub.method, Status.NOT_FOUND, Status.OK);
try {
await unaryStub.call(newRequest());
fail('call expected to fail');
} catch (e: any) {
expect(e.status).toBe(Status.NOT_FOUND);
}
}
});
it('nonblocking call cancel', () => {
for (let i = 0; i < 3; i++) {
const onNext = jasmine.createSpy();
const call = unaryStub.invoke(newRequest(), onNext);
expect(requests.length).toBeGreaterThan(0);
requests = [];
expect(call.cancel()).toBeTrue();
expect(call.cancel()).toBeFalse();
expect(onNext).not.toHaveBeenCalled();
}
});
it('blocking call with timeout', async () => {
try {
await unaryStub.call(newRequest(), 10);
fail('Promise should not be resolve');
} catch (err: any) {
expect(err.timeoutMs).toEqual(10);
}
});
it('nonblocking duplicate calls first is cancelled', () => {
const firstCall = unaryStub.invoke(newRequest());
expect(firstCall.completed).toBeFalse();
const secondCall = unaryStub.invoke(newRequest());
expect(firstCall.error).toEqual(Status.CANCELLED);
expect(secondCall.completed).toBeFalse();
});
it('nonblocking exception in callback', () => {
const errorCallback = () => {
throw Error('Something went wrong!');
};
enqueueResponse(1, unaryStub.method, Status.OK);
const call = unaryStub.invoke(newRequest(), errorCallback);
expect(call.callbackException!.name).toEqual('Error');
expect(call.callbackException!.message).toEqual('Something went wrong!');
});
});
describe('ServerStreaming', () => {
let serverStreaming: ServerStreamingMethodStub;
beforeEach(async () => {
serverStreaming = client
.channel()
?.methodStub(
'pw.rpc.test1.TheTestService.SomeServerStreaming'
)! as ServerStreamingMethodStub;
});
it('non-blocking call', () => {
const response1 = newResponse('!!!');
const response2 = newResponse('?');
for (let i = 0; i < 3; i++) {
enqueueServerStream(1, serverStreaming.method, response1);
enqueueServerStream(1, serverStreaming.method, response2);
enqueueResponse(1, serverStreaming.method, Status.ABORTED);
const onNext = jasmine.createSpy();
const onCompleted = jasmine.createSpy();
const onError = jasmine.createSpy();
serverStreaming.invoke(newRequest(4), onNext, onCompleted, onError);
expect(onNext).toHaveBeenCalledWith(response1);
expect(onNext).toHaveBeenCalledWith(response2);
expect(onError).not.toHaveBeenCalled();
expect(onCompleted).toHaveBeenCalledOnceWith(Status.ABORTED);
expect(
sentPayload(serverStreaming.method.requestType).getMagicNumber()
).toEqual(4);
}
});
it('open', () => {
outputException = Error('Error should be ignored');
const response1 = newResponse('!!!');
const response2 = newResponse('?');
for (let i = 0; i < 3; i++) {
enqueueServerStream(1, serverStreaming.method, response1);
enqueueServerStream(1, serverStreaming.method, response2);
enqueueResponse(1, serverStreaming.method, Status.ABORTED);
const onNext = jasmine.createSpy();
const onCompleted = jasmine.createSpy();
const onError = jasmine.createSpy();
const call = serverStreaming.open(
newRequest(3),
onNext,
onCompleted,
onError
);
expect(requests).toHaveSize(0);
processEnqueuedPackets();
expect(onNext).toHaveBeenCalledWith(response1);
expect(onNext).toHaveBeenCalledWith(response2);
expect(onError).not.toHaveBeenCalled();
expect(onCompleted).toHaveBeenCalledOnceWith(Status.ABORTED);
}
});
it('blocking timeout', async () => {
try {
await serverStreaming.call(newRequest(), 10);
fail('Promise should not be resolve');
} catch (err: any) {
expect(err.timeoutMs).toEqual(10);
}
});
it('non-blocking cancel', () => {
const testResponse = newResponse('!!!');
enqueueServerStream(1, serverStreaming.method, testResponse);
const onNext = jasmine.createSpy();
const onCompleted = jasmine.createSpy();
const onError = jasmine.createSpy();
let call = serverStreaming.invoke(newRequest(3), onNext);
expect(onNext).toHaveBeenCalledOnceWith(testResponse);
onNext.calls.reset();
call.cancel();
expect(lastRequest().getType()).toEqual(PacketType.CLIENT_ERROR);
expect(lastRequest().getStatus()).toEqual(Status.CANCELLED);
// Ensure the RPC can be called after being cancelled.
enqueueServerStream(1, serverStreaming.method, testResponse);
enqueueResponse(1, serverStreaming.method, Status.OK);
call = serverStreaming.invoke(newRequest(), onNext, onCompleted, onError);
expect(onNext).toHaveBeenCalledWith(testResponse);
expect(onError).not.toHaveBeenCalled();
expect(onCompleted).toHaveBeenCalledOnceWith(Status.OK);
});
});
describe('ClientStreaming', () => {
let clientStreaming: ClientStreamingMethodStub;
beforeEach(async () => {
clientStreaming = client
.channel()
?.methodStub(
'pw.rpc.test1.TheTestService.SomeClientStreaming'
)! as ClientStreamingMethodStub;
});
it('non-blocking call', () => {
const testResponse = newResponse('-.-');
for (let i = 0; i < 3; i++) {
const onNext = jasmine.createSpy();
const stream = clientStreaming.invoke(onNext);
expect(stream.completed).toBeFalse();
stream.send(newRequest(31));
expect(lastRequest().getType()).toEqual(PacketType.CLIENT_STREAM);
expect(sentPayload(Request).getMagicNumber()).toEqual(31);
expect(stream.completed).toBeFalse();
// Enqueue the server response to be sent after the next message.
enqueueResponse(1, clientStreaming.method, Status.OK, testResponse);
stream.send(newRequest(32));
expect(lastRequest().getType()).toEqual(PacketType.CLIENT_STREAM);
expect(sentPayload(Request).getMagicNumber()).toEqual(32);
expect(onNext).toHaveBeenCalledOnceWith(testResponse);
expect(stream.completed).toBeTrue();
expect(stream.status).toEqual(Status.OK);
expect(stream.error).toBeUndefined();
}
});
it('open', () => {
outputException = Error('Error should be ignored');
const response = newResponse('!!!');
for (let i = 0; i < 3; i++) {
enqueueResponse(1, clientStreaming.method, Status.OK, response);
const onNext = jasmine.createSpy();
const onCompleted = jasmine.createSpy();
const onError = jasmine.createSpy();
const call = clientStreaming.open(onNext, onCompleted, onError);
expect(requests).toHaveSize(0);
processEnqueuedPackets();
expect(onNext).toHaveBeenCalledWith(response);
expect(onError).not.toHaveBeenCalled();
expect(onCompleted).toHaveBeenCalledOnceWith(Status.OK);
}
});
it('blocking timeout', async () => {
try {
await clientStreaming.call([newRequest()], 10);
fail('Promise should not be resolve');
} catch (err: any) {
expect(err.timeoutMs).toEqual(10);
}
});
it('non-blocking call ended by client', () => {
const testResponse = newResponse('0.o');
for (let i = 0; i < 3; i++) {
const onNext = jasmine.createSpy();
const stream = clientStreaming.invoke(onNext);
expect(stream.completed).toBeFalse();
stream.send(newRequest(31));
expect(lastRequest().getType()).toEqual(PacketType.CLIENT_STREAM);
expect(sentPayload(Request).getMagicNumber()).toEqual(31);
expect(stream.completed).toBeFalse();
// Enqueue the server response to be sent after the next message.
enqueueResponse(1, clientStreaming.method, Status.OK, testResponse);
stream.finishAndWait();
expect(lastRequest().getType()).toEqual(PacketType.CLIENT_STREAM_END);
expect(onNext).toHaveBeenCalledOnceWith(testResponse);
expect(stream.completed).toBeTrue();
expect(stream.status).toEqual(Status.OK);
expect(stream.error).toBeUndefined();
}
});
it('non-blocking call cancelled', () => {
for (let i = 0; i < 3; i++) {
const stream = clientStreaming.invoke();
stream.send(newRequest());
expect(stream.cancel()).toBeTrue();
expect(lastRequest().getType()).toEqual(PacketType.CLIENT_ERROR);
expect(lastRequest().getStatus()).toEqual(Status.CANCELLED);
expect(stream.cancel()).toBeFalse();
expect(stream.completed).toBeTrue();
expect(stream.error).toEqual(Status.CANCELLED);
}
});
it('non-blocking call server error', async () => {
for (let i = 0; i < 3; i++) {
const stream = clientStreaming.invoke();
enqueueError(
1,
clientStreaming.method,
Status.INVALID_ARGUMENT,
Status.OK
);
stream.send(newRequest());
await stream
.finishAndWait()
.then(() => {
fail('Promise should not be resolved');
})
.catch(reason => {
expect(reason.status).toEqual(Status.INVALID_ARGUMENT);
});
}
});
it('non-blocking call server error after stream end', async () => {
for (let i = 0; i < 3; i++) {
const stream = clientStreaming.invoke();
// Error will be sent in response to the CLIENT_STREAM_END packet.
enqueueError(
1,
clientStreaming.method,
Status.INVALID_ARGUMENT,
Status.OK
);
await stream
.finishAndWait()
.then(() => {
fail('Promise should not be resolved');
})
.catch(reason => {
expect(reason.status).toEqual(Status.INVALID_ARGUMENT);
});
}
});
it('non-blocking call send after cancelled', () => {
const stream = clientStreaming.invoke();
expect(stream.cancel()).toBeTrue();
expect(() => stream.send(newRequest())).toThrowMatching(
error => error.status === Status.CANCELLED
);
});
it('non-blocking finish after completed', async () => {
const enqueuedResponse = newResponse('?!');
enqueueResponse(
1,
clientStreaming.method,
Status.UNAVAILABLE,
enqueuedResponse
);
const stream = clientStreaming.invoke();
const result = await stream.finishAndWait();
expect(result[1]).toEqual([enqueuedResponse]);
expect(await stream.finishAndWait()).toEqual(result);
expect(await stream.finishAndWait()).toEqual(result);
});
it('non-blocking finish after error', async () => {
enqueueError(1, clientStreaming.method, Status.UNAVAILABLE, Status.OK);
const stream = clientStreaming.invoke();
for (let i = 0; i < 3; i++) {
await stream
.finishAndWait()
.then(() => {
fail('Promise should not be resolved');
})
.catch(reason => {
expect(reason.status).toEqual(Status.UNAVAILABLE);
expect(stream.error).toEqual(Status.UNAVAILABLE);
expect(stream.response).toBeUndefined();
});
}
});
it('non-blocking duplicate calls first is cancelled', () => {
const firstCall = clientStreaming.invoke();
expect(firstCall.completed).toBeFalse();
const secondCall = clientStreaming.invoke();
expect(firstCall.error).toEqual(Status.CANCELLED);
expect(secondCall.completed).toBeFalse();
});
});
describe('BidirectionalStreaming', () => {
let bidiStreaming: BidirectionalStreamingMethodStub;
beforeEach(async () => {
bidiStreaming = client
.channel()
?.methodStub(
'pw.rpc.test1.TheTestService.SomeBidiStreaming'
)! as BidirectionalStreamingMethodStub;
});
it('blocking call', async () => {
const testRequests = [newRequest(123), newRequest(456)];
sendResponsesAfterPackets = 3;
enqueueResponse(1, bidiStreaming.method, Status.NOT_FOUND);
const results = await bidiStreaming.call(testRequests);
expect(results[0]).toEqual(Status.NOT_FOUND);
expect(results[1]).toEqual([]);
});
it('blocking server error', async () => {
const testRequests = [newRequest(123)];
enqueueError(1, bidiStreaming.method, Status.NOT_FOUND, Status.OK);
await bidiStreaming
.call(testRequests)
.then(() => {
fail('Promise should not be resolved');
})
.catch(reason => {
expect(reason.status).toEqual(Status.NOT_FOUND);
});
});
it('non-blocking call', () => {
const rep1 = newResponse('!!!');
const rep2 = newResponse('?');
for (let i = 0; i < 3; i++) {
const testResponses: Array<Message> = [];
const stream = bidiStreaming.invoke(response => {
testResponses.push(response);
});
expect(stream.completed).toBeFalse();
stream.send(newRequest(55));
expect(lastRequest().getType()).toEqual(PacketType.CLIENT_STREAM);
expect(sentPayload(Request).getMagicNumber()).toEqual(55);
expect(stream.completed).toBeFalse();
expect(testResponses).toEqual([]);
enqueueServerStream(1, bidiStreaming.method, rep1);
enqueueServerStream(1, bidiStreaming.method, rep2);
stream.send(newRequest(66));
expect(lastRequest().getType()).toEqual(PacketType.CLIENT_STREAM);
expect(sentPayload(Request).getMagicNumber()).toEqual(66);
expect(stream.completed).toBeFalse();
expect(testResponses).toEqual([rep1, rep2]);
enqueueResponse(1, bidiStreaming.method, Status.OK);
stream.send(newRequest(77));
expect(stream.completed).toBeTrue();
expect(testResponses).toEqual([rep1, rep2]);
expect(stream.status).toEqual(Status.OK);
expect(stream.error).toBeUndefined();
}
});
it('open', () => {
outputException = Error('Error should be ignored');
const response1 = newResponse('!!!');
const response2 = newResponse('?');
for (let i = 0; i < 3; i++) {
enqueueServerStream(1, bidiStreaming.method, response1);
enqueueServerStream(1, bidiStreaming.method, response2);
enqueueResponse(1, bidiStreaming.method, Status.OK);
const onNext = jasmine.createSpy();
const onCompleted = jasmine.createSpy();
const onError = jasmine.createSpy();
const call = bidiStreaming.open(onNext, onCompleted, onError);
expect(requests).toHaveSize(0);
processEnqueuedPackets();
expect(onNext).toHaveBeenCalledWith(response1);
expect(onNext).toHaveBeenCalledWith(response2);
expect(onError).not.toHaveBeenCalled();
expect(onCompleted).toHaveBeenCalledOnceWith(Status.OK);
}
});
it('blocking timeout', async () => {
try {
await bidiStreaming.call([newRequest()], 10);
fail('Promise should not be resolve');
} catch (err: any) {
expect(err.timeoutMs).toEqual(10);
}
});
it('non-blocking server error', async () => {
const response = newResponse('!!!');
for (let i = 0; i < 3; i++) {
const testResponses: Array<Message> = [];
const stream = bidiStreaming.invoke(response => {
testResponses.push(response);
});
expect(stream.completed).toBeFalse();
enqueueServerStream(1, bidiStreaming.method, response);
stream.send(newRequest(55));
expect(stream.completed).toBeFalse();
expect(testResponses).toEqual([response]);
enqueueError(1, bidiStreaming.method, Status.OUT_OF_RANGE, Status.OK);
stream.send(newRequest(999));
expect(stream.completed).toBeTrue();
expect(testResponses).toEqual([response]);
expect(stream.status).toBeUndefined();
expect(stream.error).toEqual(Status.OUT_OF_RANGE);
await stream
.finishAndWait()
.then(() => {
fail('Promise should not be resolved');
})
.catch(reason => {
expect(reason.status).toEqual(Status.OUT_OF_RANGE);
});
}
});
it('non-blocking server error after stream end', async () => {
for (let i = 0; i < 3; i++) {
const stream = bidiStreaming.invoke();
// Error is sent in response to CLIENT_STREAM_END packet.
enqueueError(
1,
bidiStreaming.method,
Status.INVALID_ARGUMENT,
Status.OK
);
await stream
.finishAndWait()
.then(() => {
fail('Promise should not be resolved');
})
.catch(reason => {
expect(reason.status).toEqual(Status.INVALID_ARGUMENT);
});
}
});
it('non-blocking send after cancelled', async () => {
const stream = bidiStreaming.invoke();
expect(stream.cancel()).toBeTrue();
try {
stream.send(newRequest());
fail('send should have failed');
} catch (e: any) {
expect(e.status).toBe(Status.CANCELLED);
}
});
it('non-blocking finish after completed', async () => {
const response = newResponse('!?');
enqueueServerStream(1, bidiStreaming.method, response);
enqueueResponse(1, bidiStreaming.method, Status.UNAVAILABLE);
const stream = bidiStreaming.invoke();
const result = await stream.finishAndWait();
expect(result[1]).toEqual([response]);
expect(await stream.finishAndWait()).toEqual(result);
expect(await stream.finishAndWait()).toEqual(result);
});
it('non-blocking finish after error', async () => {
const response = newResponse('!?');
enqueueServerStream(1, bidiStreaming.method, response);
enqueueError(1, bidiStreaming.method, Status.UNAVAILABLE, Status.OK);
const stream = bidiStreaming.invoke();
for (let i = 0; i < 3; i++) {
await stream
.finishAndWait()
.then(() => {
fail('Promise should not be resolved');
})
.catch(reason => {
expect(reason.status).toEqual(Status.UNAVAILABLE);
expect(stream.error).toEqual(Status.UNAVAILABLE);
});
}
});
it('non-blocking duplicate calls first is cancelled', () => {
const firstCall = bidiStreaming.invoke();
expect(firstCall.completed).toBeFalse();
const secondCall = bidiStreaming.invoke();
expect(firstCall.error).toEqual(Status.CANCELLED);
expect(secondCall.completed).toBeFalse();
});
});
}); | the_stack |
import { colors, fs, path, ts } from "../../../deps.ts";
import { isURL } from "../../../_util.ts";
import { DependencyType, ModuleData } from "../../plugin.ts";
import type { Import } from "../../plugin.ts";
function hasModifier(
modifiers: ts.ModifiersArray,
modifier: ts.SyntaxKind,
) {
return modifiers.find((moduleSpecifier: ts.Modifier) =>
moduleSpecifier.kind === modifier
);
}
/**
* extracts dependency paths and specifiers, defaults and namespaces
*/
export function typescriptExtractDependenciesTransformer(
moduleData: ModuleData,
) {
function addImport(filePath: string, type: DependencyType): Import {
const imports = moduleData.dependencies[filePath] ||= {};
return imports[type] ||= {};
}
return (context: ts.TransformationContext) => {
const visitor = (sourceFile: ts.SourceFile): ts.Visitor => {
const visit: ts.Visitor = (node: ts.Node) => {
let filePath = sourceFile.fileName;
if (ts.isImportDeclaration(node)) {
const importClause = node.importClause;
const moduleSpecifier = node.moduleSpecifier;
const isTypeOnly = importClause?.isTypeOnly;
if (moduleSpecifier && ts.isStringLiteral(moduleSpecifier)) {
filePath = moduleSpecifier.text;
}
const entry = addImport(filePath, DependencyType.Import);
if (importClause) {
if (importClause.namedBindings) {
if (ts.isNamespaceImport(importClause.namedBindings)) {
// import * as x from "./x.ts"
if (isTypeOnly) {
entry.types ||= {};
entry.types["*"] = importClause.namedBindings.name.text;
} else {
entry.namespaces ||= [];
entry.namespaces.push(
importClause.namedBindings.name.text,
);
}
}
if (ts.isNamedImports(importClause.namedBindings)) {
// import { x } from "./x.ts"
importClause.namedBindings.elements.forEach((element) => {
// import { x as k } from "./x.ts"
const identifier = (element.propertyName?.text ||
element.name.text) as string;
const name = element.name.text;
if (isTypeOnly) {
entry.types ||= {};
entry.types[name] = identifier;
} else {
entry.specifiers ||= {};
entry.specifiers[name] = identifier;
}
});
}
} else if (importClause.name) {
// import x from "./x.ts"
const name = importClause.name.text;
if (isTypeOnly) {
entry.types ||= {};
entry.types[name] = name;
} else {
entry.defaults ||= [];
entry.defaults.push(
name,
);
}
}
}
return node;
} else if (ts.isExportDeclaration(node)) {
const isTypeOnly = node.isTypeOnly;
const moduleSpecifier = node.moduleSpecifier;
if (moduleSpecifier && ts.isStringLiteral(moduleSpecifier)) {
filePath = moduleSpecifier.text;
}
const passthrough = moduleSpecifier &&
filePath !== sourceFile.fileName;
const entry = passthrough
? addImport(filePath, DependencyType.Import)
: moduleData.export; // basically imports and re-exports again
const exportClause = node.exportClause;
if (exportClause) {
if (ts.isNamespaceExport(exportClause)) {
// export * as x from "./x.ts"
const name = exportClause.name.text;
if (isTypeOnly) {
entry.types ||= {};
entry.types["*"] = name;
} else {
entry.namespaces ||= [];
entry.namespaces.push(name);
moduleData.export.specifiers ||= {};
moduleData.export.specifiers[name] = name;
}
} else if (ts.isNamedExports(exportClause)) {
exportClause.elements.forEach((element) => {
const propertyName = (element.propertyName?.text ||
element.name.text) as string;
const name = element.name.text;
if (isTypeOnly) {
// export type { x } from "./x.ts" or export type { x as y } from "./x.ts"
entry.types ||= {};
entry.types[name] = propertyName;
moduleData.export.types ||= {};
moduleData.export.types[name] = passthrough
? name
: propertyName;
} else {
// export { x } from "./x.ts" or export { x as y } from "./x.ts"
entry.specifiers ||= {};
entry.specifiers[name] = propertyName;
moduleData.export.specifiers ||= {};
moduleData.export.specifiers[name] = passthrough
? name
: propertyName;
}
});
}
} else {
// export * from "./x.ts"
if (!isTypeOnly) {
entry.namespaces ||= [];
entry.namespaces.push("*"); // has no alias for namespace, therefore undefined as value
moduleData.export.namespaces ||= [];
moduleData.export.namespaces.push(filePath);
}
}
return node;
} else if (ts.isExportAssignment(node)) {
// export default "abc"
const entry = moduleData.export;
if (ts.isIdentifier(node.expression)) {
entry.default = node.expression.text;
} else {
entry.default = true;
}
return node;
} else if (ts.isVariableStatement(node)) {
if (
node.modifiers &&
hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword)
) {
// export const x = "x"
const entry = moduleData.export;
node.declarationList.declarations.forEach((declaration) => {
if (ts.isIdentifier(declaration.name)) {
const propertyName = declaration.name.text;
const name = declaration.name.text;
entry.specifiers ||= {};
entry.specifiers[name] = propertyName;
} else if (ts.isObjectBindingPattern(declaration.name)) {
declaration.name.elements.forEach((element) => {
if (ts.isIdentifier(element.name)) {
const propertyName = (element.propertyName &&
ts.isIdentifier(element.propertyName) &&
(element.propertyName?.text) ||
element.name.text) as string;
const name = element.name.text;
entry.specifiers ||= {};
entry.specifiers[name] = propertyName;
}
});
}
});
}
} else if (ts.isFunctionDeclaration(node)) {
if (
node.name &&
node.modifiers &&
hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword)
) {
const _export = moduleData.export;
if (
hasModifier(node.modifiers, ts.SyntaxKind.DefaultKeyword)
) {
// export default function x() {}
_export.default = node.name.text;
} else if (ts.isIdentifier(node.name)) {
// export function x() {}
const identifier = node.name.text;
const name = node.name.text;
_export.specifiers ||= {};
_export.specifiers[name] = identifier;
}
}
} else if (ts.isClassDeclaration(node)) {
if (
node.name &&
node.modifiers &&
hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword)
) {
const entry = moduleData.export;
if (
hasModifier(node.modifiers, ts.SyntaxKind.DefaultKeyword)
) {
// export default class X {}
entry.default = node.name.text;
} else if (ts.isIdentifier(node.name)) {
// export class X {}
const propertyName = node.name.text;
const name = node.name.text;
entry.specifiers ||= {};
entry.specifiers[name] = propertyName;
}
}
} else if (ts.isInterfaceDeclaration(node)) {
if (
node.modifiers &&
hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword)
) {
const entry = moduleData.export;
// export interface x {}
const name = node.name.text;
entry.types ||= {};
entry.types[name] = name;
}
} else if (ts.isTypeAliasDeclaration(node)) {
if (
node.modifiers &&
hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword)
) {
const entry = moduleData.export;
// export interface x {}
const name = node.name.text;
entry.types ||= {};
entry.types[name] = name;
}
} else if (
ts.isCallExpression(node) &&
node.expression.kind === ts.SyntaxKind.ImportKeyword
) {
const argument = node.arguments[0];
if (ts.isStringLiteral(argument)) {
// import("./x.ts")
filePath = argument.text;
addImport(filePath, DependencyType.DynamicImport);
} else {
console.warn(
colors.yellow("Warning"),
`The argument in dynamic import is not a static string. Cannot resolve '${
node.getFullText(sourceFile)
}' in '${sourceFile.fileName}' at position ${node.pos}.`,
);
}
} else if (
ts.isCallExpression(node) && ts.isIdentifier(node.expression) &&
node.expression.text === "fetch"
) {
const argument = node.arguments[0];
if (ts.isStringLiteral(argument)) {
const filePath = argument.text;
// if is external file, do not add as dependency
if (
!isURL(filePath) &&
fs.existsSync(
path.join(path.dirname(sourceFile.fileName), filePath),
)
) {
addImport(filePath, DependencyType.Fetch);
}
}
} else if (
ts.isNewExpression(node) && ts.isIdentifier(node.expression) &&
node.expression.text === "Worker"
) {
const argument = node.arguments?.[0];
if (argument && ts.isStringLiteral(argument)) {
const filePath = argument.text;
addImport(filePath, DependencyType.WebWorker);
}
} else if (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === "register" &&
ts.isPropertyAccessExpression(node.expression.expression) &&
node.expression.expression.name.text === "serviceWorker"
) {
const argument = node.arguments?.[0];
if (argument && ts.isStringLiteral(argument)) {
const filePath = argument.text;
addImport(filePath, DependencyType.ServiceWorker);
}
} else if (ts.isEnumDeclaration(node)) {
if (
node.modifiers &&
hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword)
) {
const entry = moduleData.export;
// export enum x {}
const identifier = node.name.text;
const name = node.name.text;
entry.specifiers ||= {};
entry.specifiers[name] = identifier;
}
}
return ts.visitEachChild(node, visit, context);
};
return visit;
};
return (node: ts.Node) => {
return ts.visitNode(node, visitor(node as ts.SourceFile));
};
};
}
export function extractDependenciesFromSourceFile(
sourceFile: ts.SourceFile,
compilerOptions?: ts.CompilerOptions,
) {
const moduleData: ModuleData = {
dependencies: {},
export: {},
};
ts.transform(
sourceFile,
[typescriptExtractDependenciesTransformer(moduleData)],
compilerOptions,
);
return moduleData;
}
export function extractDependencies(
fileName: string,
sourceText: string,
compilerOptions?: ts.CompilerOptions,
) {
const sourceFile = ts.createSourceFile(
fileName,
sourceText,
ts.ScriptTarget.Latest,
);
return extractDependenciesFromSourceFile(sourceFile, compilerOptions);
} | the_stack |
import type * as hb from "homebridge";
import type * as hap from "hap-nodejs";
import * as miio from "miio-api";
import { PlatformAccessory } from "../platform";
import { Humidifier } from "./factory";
import { AnyCharacteristicConfig } from "./features";
import { Protocol } from "./protocols";
import { ValueOf } from "./utils";
import { Logger } from "./logger";
/**
* Base class for all humidifiers, all humidifiers must inherit from this class.
*
* @typeParam PropsType key-value type containing all supported device
* properties types. For better defaults it is recommended to use
* device properties names as keys is possible.
*/
export class BaseHumidifier<PropsType extends BasePropsType>
implements Humidifier {
private readonly protocol: Protocol<PropsType>;
private readonly features: Array<AnyCharacteristicConfig<PropsType>>;
private readonly log: Logger;
private props: GetEntry<PropsType>[];
private cache: PropsType;
/**
* @param protocol device protocol.
* @param features device characteristics configurations.
* @param log logger.
*/
constructor(
protocol: Protocol<PropsType>,
features: Array<AnyCharacteristicConfig<PropsType>>,
log: Logger,
) {
this.protocol = protocol;
this.features = features;
this.log = log;
this.props = [];
this.cache = {} as PropsType;
}
/**
* Adds services and characteristics to the accessory.
* This method should be overwritten in child classes to add
* all necessary services and characteristics.
*
* @param accessory homebridge accessory
*/
configureAccessory(accessory: PlatformAccessory): void {
this.features.forEach((feature) => {
this.register(accessory, feature);
});
const enabledServices = new Set(
this.features.map(
(feature) =>
feature.service.UUID + (feature.name ? feature.name.subtype : ""),
),
);
// Cleanup disabled services and characteristics.
accessory.services.forEach((service) => {
if (!enabledServices.has(service.getServiceId())) {
this.log.debug("Removing service", service.getServiceId());
accessory.removeService(service);
}
const enabledCharacteristics = new Set(
this.features
.filter(
(it) =>
it.service.UUID + (it.name ? it.name.subtype : "") ===
service.getServiceId(),
)
.map((it) => it.characteristic.UUID),
);
service.characteristics.forEach((char) => {
if (!enabledCharacteristics.has(char.UUID)) {
this.log.debug("Removing characteristic", char.UUID);
service.removeCharacteristic(char);
}
});
});
}
/**
* Function to use in polling.
*
* Requests all registered device properties and stores them in cache
* to return later in `CharacteristicGetCallback`. Also asynchronously
* updates corresponding HomeKit characteristics.
*/
public async update(): Promise<void> {
try {
this.cache = await this.protocol.getProps(
this.props.map((prop) => prop.key),
);
this.props.forEach((prop) => {
const propValue = this.cache[prop.key];
prop.values.forEach((value) => {
const charValue = value.map(propValue);
this.log.debug(
`Updating property "${prop.key}": ${propValue} -> ${charValue}`,
);
value.characteristic.updateValue(charValue);
});
});
} catch (err) {
this.log.error(
`Fail to get device properties. ${err.constructor.name}: ${err.message}`,
);
if (err instanceof miio.ProtocolError) {
this.log.warn(
"Got ProtocolError which indicates use of an invalid token. Please, check that provided token is correct!",
);
}
}
}
/**
* Registers characteristic for the given accessory and service.
*/
register<PropsKey extends keyof PropsType>(
accessory: PlatformAccessory,
config: CharacteristicConfig<PropsType, PropsKey, PropsType[PropsKey]>,
): void {
let service;
if (config.name) {
service =
accessory.getService(config.name.displayName) ||
accessory.addService(
config.service,
config.name.displayName,
config.name.subtype,
);
} else {
service =
accessory.getService(config.service) ||
accessory.addService(config.service);
}
const characteristic = service.getCharacteristic(config.characteristic);
if (config.props) {
characteristic.setProps(config.props);
}
if ("value" in config) {
if (typeof config.value === "function") {
// Callback.
characteristic.on("get", config.value);
} else {
// Static value.
characteristic.setValue(config.value);
}
} else {
// Dynamic characteristic.
const getMap = config.get?.map
? (config.get.map as GetMapFunc<PropsType>)
: (it: PrimitiveType) => it; // by default return the same value.
const entry = this.props.find((prop) => prop.key === config.key);
if (entry) {
// If prop entry is already saved, just add new characteristic to it.
entry.values.push({
characteristic: characteristic,
map: getMap,
});
} else {
// Save prop entry.
this.props.push({
key: config.key,
values: [
{
characteristic: characteristic,
map: getMap,
},
],
});
}
characteristic.on("get", (callback: hb.CharacteristicGetCallback) => {
this.getProp(config.key, getMap, callback);
});
if (config.set) {
const setEntry: SetEntry<PropsType> = {
key: config.key,
call: config.set.call,
characteristic: characteristic,
map: config.set.map
? config.set.map
: (it: hb.CharacteristicValue) => it as ValueOf<PropsType>, // by default use the same value.
beforeSet: config.set.beforeSet,
afterSet: config.set.afterSet,
};
characteristic.on(
"set",
async (
value: hb.CharacteristicValue,
callback: hb.CharacteristicSetCallback,
) => {
return await this.setProp(setEntry, value, callback);
},
);
}
}
}
/**
* Function which is used as homebridge `CharacteristicGetCallback` for
* all registered characteristics.
*
* Returns last cached property value. This method don't make
* device call because some devices are slow to respond and if we
* will request every prop from device here HomeKit will become unresponsive.
*
* @param key property identifier.
* @param map function that converts property value to characteristic.
* @param callback characteristic get callback.
*/
private getProp(
key: keyof PropsType,
map: (it: ValueOf<PropsType>) => hb.CharacteristicValue,
callback: hb.CharacteristicGetCallback,
): void {
this.log.debug(`Getting property "${key}"`);
callback(null, map(this.cache[key]));
}
/**
* Function which used as homebridge `CharacteristicSetCallback` for
* all registered characteristics.
*
* This function in contrast to `getProp` makes device call.
*
* @param entry `SetEntry` object for prop.
* @param value value to set for property.
* @param callback characteristic set callback.
*/
private async setProp(
entry: SetEntry<PropsType>,
value: hb.CharacteristicValue,
callback: hb.CharacteristicSetCallback,
) {
this.log.debug(`Setting property "${entry.key}" to ${value}`);
try {
let skipSet;
if (entry.beforeSet) {
skipSet = await entry.beforeSet({
value,
characteristic: entry.characteristic,
protocol: this.protocol,
});
}
const mappedValue = entry.map(value);
if (skipSet !== true) {
await this.protocol.setProp(entry.key, entry.call, mappedValue);
}
if (entry.afterSet) {
await entry.afterSet({
value,
mappedValue,
characteristic: entry.characteristic,
protocol: this.protocol,
});
}
callback();
} catch (err) {
this.log.error(
`Fail to set device property "${entry.key}". ${err.constructor.name}: ${err.message}`,
);
callback(err);
}
}
}
/**
* Device property value type.
*/
export type PrimitiveType = string | number | boolean;
/**
* Base props type.
* `PropsType` of child class must this type.
*/
export type BasePropsType = { [key: string]: PrimitiveType };
/**
* Function that maps device property value to corresponding characteristic value.
*/
export type GetMapFunc<PropsType> = (
it: ValueOf<PropsType>,
) => hb.CharacteristicValue;
/**
* Function that maps characteristic value to corresponding device property value.
*/
export type SetMapFunc<PropsType> = (
it: hb.CharacteristicValue,
) => ValueOf<PropsType>;
/**
* Function that is called before settings the device property.
*/
export type BeforeSetFunc<PropsType> = (
args: BeforeSetFuncArgs<PropsType>,
) => boolean | Promise<boolean> | void | Promise<void>;
export type BeforeSetFuncArgs<PropsType> = {
value: hb.CharacteristicValue;
characteristic: hb.Characteristic;
protocol: Protocol<PropsType>;
};
/**
* Function that is called after settings the device property.
*/
export type AfterSetFunc<PropsType> = (
args: AfterSetFuncArgs<PropsType>,
) => void | Promise<void>;
export type AfterSetFuncArgs<PropsType> = {
value: hb.CharacteristicValue;
mappedValue: PrimitiveType;
characteristic: hb.Characteristic;
protocol: Protocol<PropsType>;
};
/**
* GetEntry contains all required information
* to get property from device, convert it to HomeKit characteristic value
* and update corresponding accessory characteristic.
*/
export type GetEntry<PropsType> = {
// Property identifier.
key: keyof PropsType;
values: Array<{
// Accessories characteristics that must be updated with device property value.
characteristic: hb.Characteristic;
// Function that converts device property to corresponding characteristic value.
map: (it: ValueOf<PropsType>) => hb.CharacteristicValue;
}>;
};
/**
* GetEntry contains all information required to
* convert HomeKit characteristic value to device property
* and set it on the device.
*/
export type SetEntry<PropsType> = {
// Property identifier.
key: keyof PropsType;
// Accessory characteristic.
characteristic: hb.Characteristic;
// Name of device call that updates the property.
call: string;
// Function that converts characteristic value to corresponding device property value.
map: (it: hb.CharacteristicValue) => ValueOf<PropsType>;
// Function that is called before settings the device property.
// Can be used to add some extra logic.
beforeSet?: BeforeSetFunc<PropsType>;
// Function that is called after settings the device property.
// Can be used to add some extra logic.
afterSet?: AfterSetFunc<PropsType>;
};
/**
* Useful type aliases.
*/
export type Characteristic = hb.WithUUID<new () => hap.Characteristic>;
export type Service = hb.WithUUID<typeof hap.Service>;
/**
* CharacteristicConfig is used to register characteristic for accessory.
*/
export type CharacteristicConfig<PropsType, PropKey, PropValue> =
| CharacteristicConfigStatic
| CharacteristicConfigDynamic<PropsType, PropKey, PropValue>;
export type CharacteristicConfigStatic = {
// HomeKit service.
service: Service;
// HomeKit service name (required if we have multiple services of the same type).
name?: {
displayName: string;
subtype: string;
};
// HomeKit characteristic.
characteristic: Characteristic;
// HomeKit characteristic properties if required.
props?: Partial<hb.CharacteristicProps>;
// HomeKit characteristic value.
value:
| hb.CharacteristicValue
| ((callback: hb.CharacteristicGetCallback) => void);
};
export type CharacteristicConfigDynamic<PropsType, PropKey, PropValue> = {
// HomeKit service.
service: Service;
// HomeKit service name (required if we have multiple services of the same type).
name?: {
displayName: string;
subtype: string;
};
// HomeKit characteristic.
characteristic: Characteristic;
// HomeKit characteristic properties if required.
props?: Partial<hb.CharacteristicProps>;
// Device props key. Used as property identifier.
key: PropKey;
// Characteristic get config.
get?: {
// Function that converts device property value to the corresponding
// HomeKit characteristic value.
// If not provided the same value will be used.
map?: (it: PropValue) => hb.CharacteristicValue;
};
// Characteristic set config.
set?: {
// Set characteristic call name.
call: string;
// Function that converts HomeKit characteristic value
// to the corresponding device property value.
// If not provided the same value will be used.
map?: (it: hb.CharacteristicValue) => PropValue;
// Function that is called before settings the device property.
// Can be used to add some extra logic.
// You can return "true" to skip property set call.
beforeSet?: BeforeSetFunc<PropsType>;
// Function that is called before settings the device property.
// Can be used to add some extra logic.
afterSet?: AfterSetFunc<PropsType>;
};
}; | the_stack |
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable, forkJoin } from 'rxjs';
import {} from 'rxjs/Observable';
import { JhiEventManager, JhiAlertService } from 'ng-jhipster';
import { IWireTapEndpoint, WireTapEndpoint, ComponentType } from 'app/shared/model/wire-tap-endpoint.model';
import { IService, Service } from 'app/shared/model/service.model';
import { IHeader, Header } from 'app/shared/model/header.model';
import { Services } from '../../shared/camel/service-connections';
import { WireTapEndpointService } from './wire-tap-endpoint.service';
import { ServiceService } from '../service';
import { HeaderService } from '../header';
import { Components, typesLinks } from '../../shared/camel/component-type';
import { FlowService } from '../flow/flow.service';
import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
import { Option } from '../flow';
import { HttpResponse } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Component({
selector: 'jhi-wire-tap-endpoint-update',
templateUrl: './wire-tap-endpoint-update.component.html'
})
export class WireTapEndpointUpdateComponent implements OnInit {
wireTapEndpoint: IWireTapEndpoint;
service: Service;
isSaving: boolean;
typeCamelLink: string;
wikiDocUrl: string;
camelDocUrl: string;
typeAssimblyLink: string;
endpointOptions: Array<Option> = [];
wireTapForm: FormGroup;
headers: Header[];
services: Service[];
filteredService: Service[];
serviceCreated: boolean;
headerCreated: boolean;
serviceType: string;
uriPlaceholder: string;
uriPopoverMessage: string;
wiretapComponentOptions: any;
constructor(
private jhiAlertService: JhiAlertService,
private wireTapEndpointService: WireTapEndpointService,
private serviceService: ServiceService,
private headerService: HeaderService,
private flowService: FlowService,
public servicesList: Services,
private eventManager: JhiEventManager,
private route: ActivatedRoute,
private router: Router,
public components: Components
) {}
ngOnInit() {
this.wireTapEndpoint = new WireTapEndpoint();
this.isSaving = false;
this.initializeEndpointData();
this.route.params.subscribe(params => {
this.load(params['id']);
});
}
private load(id) {
if (id) {
forkJoin(
this.wireTapEndpointService.find(id),
this.serviceService.query(),
this.headerService.query(),
this.flowService.getWikiDocUrl(),
this.flowService.getCamelDocUrl()
).subscribe(([wireTapEndpoint, services, headers, wikiDocUrl, camelDocUrl]) => {
this.wireTapEndpoint = wireTapEndpoint.body;
this.services = services.body;
this.serviceCreated = this.services.length > 0;
this.headers = headers.body;
this.headerCreated = this.headers.length > 0;
this.wikiDocUrl = wikiDocUrl.url;
this.camelDocUrl = camelDocUrl.url;
this.updateEndpointData();
this.setTypeLink();
this.getOptions();
});
} else {
forkJoin(
this.serviceService.query(),
this.headerService.query(),
this.flowService.getWikiDocUrl(),
this.flowService.getCamelDocUrl()
).subscribe(([services, headers, wikiDocUrl, camelDocUrl]) => {
this.wireTapEndpoint.type = ComponentType.FILE;
this.services = services.body;
this.serviceCreated = this.services.length > 0;
this.headers = headers.body;
this.headerCreated = this.headers.length > 0;
this.wikiDocUrl = wikiDocUrl.body;
this.camelDocUrl = camelDocUrl.body;
this.updateEndpointData();
this.setTypeLink();
this.getOptions();
});
}
}
save() {
this.isSaving = true;
this.setDataFromForm();
this.setEndpointOptions();
this.isSaving = false;
if (this.wireTapEndpoint.id) {
this.subscribeToSaveResponse(this.wireTapEndpointService.update(this.wireTapEndpoint));
} else {
this.subscribeToSaveResponse(this.wireTapEndpointService.create(this.wireTapEndpoint));
}
}
setDataFromForm() {
const flowControls = this.wireTapForm.controls;
this.wireTapEndpoint.id = flowControls.id.value;
this.wireTapEndpoint.type = flowControls.type.value;
this.wireTapEndpoint.uri = flowControls.uri.value;
this.wireTapEndpoint.headerId = flowControls.header.value;
this.wireTapEndpoint.serviceId = flowControls.service.value ? flowControls.service.value : null;
}
setEndpointOptions() {
this.wireTapEndpoint.options = '';
let index = 0;
this.endpointOptions.forEach((option, i) => {
let formOptions: FormGroup = <FormGroup>(<FormArray>this.wireTapForm.controls.options).controls[i];
option.key = formOptions.controls.key.value;
option.value = formOptions.controls.value.value;
if (option.key && option.value) {
this.wireTapEndpoint.options += index > 0 ? `&${option.key}=${option.value}` : `${option.key}=${option.value}`;
index++;
}
});
}
previousState() {
window.history.back();
}
setTypeLink(e?) {
if (typeof e !== 'undefined') {
this.wireTapEndpoint.type = e;
}
let type = typesLinks.find(x => x.name === this.wireTapEndpoint.type.toString());
this.wireTapForm.controls.service.setValue('');
this.filterServices();
this.typeAssimblyLink = this.wikiDocUrl + type.assimblyTypeLink;
this.typeCamelLink = this.camelDocUrl + type.camelTypeLink;
this.uriPlaceholder = type.uriPlaceholder;
this.uriPopoverMessage = type.uriPopoverMessage;
this.wireTapForm.patchValue({ type: type.name });
let componentType = this.wireTapForm.controls.type.value;
componentType = componentType.toLowerCase();
// get options keys
this.getComponentOptions(componentType).subscribe(data => {
this.wiretapComponentOptions = Object.keys(data.properties);
});
this.enableFields(this.wireTapForm);
}
enableFields(endpointForm) {
let componentHasService = this.servicesList.getServiceType(endpointForm.controls.componentType.value);
if (endpointForm.controls.componentType.value === 'WASTEBIN') {
endpointForm.controls.uri.disable();
endpointForm.controls.options.disable();
endpointForm.controls.service.disable();
endpointForm.controls.header.disable();
} else if (componentHasService) {
endpointForm.controls.uri.enable();
endpointForm.controls.options.enable();
endpointForm.controls.header.enable();
endpointForm.controls.service.enable();
} else {
endpointForm.controls.uri.enable();
endpointForm.controls.options.enable();
endpointForm.controls.header.enable();
endpointForm.controls.service.disable();
}
}
getOptions() {
if (this.wireTapEndpoint.id) {
if (!this.wireTapEndpoint.options) {
this.wireTapEndpoint.options = '';
}
const options = this.wireTapEndpoint.options.split('&');
options.forEach((option, index) => {
const kv = option.split('=');
const o = new Option();
o.key = kv[0];
o.value = kv[1];
let formOptions = <FormArray>this.wireTapForm.controls.options;
if (typeof formOptions.controls[index] === 'undefined') {
formOptions.push(this.initializeOption());
}
formOptions.controls[index].patchValue({
key: o.key,
value: o.value
});
this.endpointOptions.push(o);
});
} else {
this.addOption();
}
}
getComponentOptions(componentType: String): any {
return this.flowService.getComponentOptions(1, componentType).pipe(
map(options => {
return options.body;
})
);
}
createOrEditHeader() {
this.wireTapEndpoint.headerId = this.wireTapForm.controls.header.value;
this.wireTapEndpoint.headerId
? this.router.navigate(['/', { outlets: { popup: 'header/' + this.wireTapEndpoint.headerId + '/edit' } }], {
fragment: 'showEditHeaderButton'
})
: this.router.navigate(['/', { outlets: { popup: ['header-new'] } }], { fragment: 'showEditHeaderButton' });
this.eventManager.subscribe('headerModified', res => this.setHeader(res));
}
setHeader(id) {
this.headerService.query().subscribe(
res => {
this.headers = res.body;
this.headerCreated = this.headers.length > 0;
this.wireTapEndpoint.headerId = this.headers.find(h => h.id === id.content).id;
this.wireTapForm.controls.header.patchValue(this.wireTapEndpoint.headerId);
},
res => this.onError(res.body)
);
}
createOrEditService() {
typeof this.wireTapEndpoint.serviceId === 'undefined' || this.wireTapEndpoint.serviceId === null
? this.router.navigate(['/', { outlets: { popup: ['service-new'] } }], { fragment: this.serviceType })
: this.router.navigate(['/', { outlets: { popup: 'service/' + this.wireTapEndpoint.serviceId + '/edit' } }], {
fragment: this.serviceType
});
this.eventManager.subscribe('serviceModified', res => this.setService(res));
}
setService(id) {
this.serviceService.query().subscribe(
res => {
this.services = res.body;
this.serviceCreated = this.services.length > 0;
this.service = this.services.find(s => s.id === id.content);
this.wireTapEndpoint.serviceId = this.service.id;
this.wireTapForm.controls.service.patchValue(this.wireTapEndpoint.serviceId);
this.filterServices();
},
res => this.onError(res.json)
);
}
filterServices() {
this.serviceType = this.servicesList.getServiceType(this.wireTapEndpoint.type);
this.filteredService = this.services.filter(f => f.type === this.serviceType);
if (this.filteredService.length > 0 && this.wireTapEndpoint.serviceId) {
this.wireTapForm.controls.service.setValue(this.filteredService.find(fs => fs.id === this.wireTapEndpoint.serviceId).id);
}
}
validateOptions(i: number) {
let option: FormGroup = <FormGroup>(<FormArray>this.wireTapForm.controls.options).controls[i];
if (option.value.key || option.value.value) {
option.controls.key.setValidators([Validators.required]);
option.controls.value.setValidators([Validators.required]);
} else {
option.controls.key.clearValidators();
option.controls.value.clearValidators();
}
option.controls.key.updateValueAndValidity();
option.controls.value.updateValueAndValidity();
}
addOption() {
(<FormArray>this.wireTapForm.controls.options).push(this.initializeOption());
this.endpointOptions.push(new Option());
}
removeOption(option: Option) {
const index = this.endpointOptions.indexOf(option);
(<FormArray>this.wireTapForm.controls.options).removeAt(index);
this.endpointOptions.splice(index, 1);
}
private initializeEndpointData() {
this.wireTapForm = new FormGroup({
id: new FormControl(this.wireTapEndpoint.id),
type: new FormControl(this.wireTapEndpoint.type, Validators.required),
uri: new FormControl(this.wireTapEndpoint.uri, Validators.required),
options: new FormArray([this.initializeOption()]),
service: new FormControl(this.wireTapEndpoint.serviceId),
header: new FormControl(this.wireTapEndpoint.headerId)
});
}
private initializeOption(): FormGroup {
return new FormGroup({
key: new FormControl(null),
value: new FormControl(null)
});
}
private updateEndpointData() {
if (this.wireTapEndpoint !== null) {
this.wireTapForm.patchValue({
id: this.wireTapEndpoint.id,
type: this.wireTapEndpoint.type,
uri: this.wireTapEndpoint.uri
});
}
if (this.wireTapEndpoint.serviceId !== null) {
this.wireTapForm.patchValue({
service: this.wireTapEndpoint.serviceId
});
}
if (this.wireTapEndpoint.headerId !== null) {
this.wireTapForm.patchValue({
header: this.wireTapEndpoint.headerId
});
}
}
private subscribeToSaveResponse(result: Observable<HttpResponse<IWireTapEndpoint>>) {
result.subscribe(data => {
if (data.ok) {
this.onSaveSuccess(data.body);
} else {
this.onSaveError();
}
});
}
private onSaveSuccess(result: WireTapEndpoint) {
/* this.wireTapEndpoint = result;
this.initializeEndpointData();
this.getOptions();
this.isSaving = false; */
this.router.navigate(['./wire-tap-endpoint']);
}
private onSaveError() {
this.isSaving = false;
}
private onError(error: any) {
this.jhiAlertService.error(error.message, null, null);
}
trackServiceById(index: number, item: Service) {
return item.id;
}
trackHeaderById(index: number, item: Header) {
return item.id;
}
} | the_stack |
import { Nullable } from "../../../shared/types";
import { Scene } from "babylonjs";
import { LGraphNode, LiteGraph, LLink, SerializedLGraphNode, Vector2, LGraphCanvas, WidgetCallback, IWidget } from "litegraph.js";
import { Tools } from "../tools/tools";
import { undoRedo } from "../tools/undo-redo";
import { NodeUtils } from "./utils";
declare module "litegraph.js" {
export interface LGraphNode {
widgets?: IWidget[];
}
}
export enum CodeGenerationOutputType {
Constant = 0,
Variable,
Function,
CallbackFunction,
Condition,
FunctionWithCallback,
}
export enum CodeGenerationExecutionType {
Start = 0,
Update,
Properties,
}
export enum ELinkErrorType {
/**
* Defines a link error raised when user wants to connect multiple nodes for an "EVENT".
*/
MultipleEvent = 0,
}
export interface ICodeGenerationOutput {
/**
* Defines the type of the output.
*/
type: CodeGenerationOutputType;
/**
* Defines the generated code as string for the overall node.
*/
code: string;
/**
* Defines the code generated for each output of the node.
*/
outputsCode?: {
/**
* Defines the code generated by the output.
*/
code?: string;
/**
* Defines wether or not the output is the name of the variable in "this".
*/
thisVariable?: boolean;
}[];
/**
* Defines where the execution should appear (onStart or onUpdate?).
*/
executionType?: CodeGenerationExecutionType;
/**
* In case of a variable, this contains the name of the variable that is being generated an its value.
*/
variable?: {
/**
* Defines the name of the variable.
*/
name: string;
/**
* Defines the type of the variable.
*/
type: string;
/**
* Defines the default value of the variable.
*/
value: string;
/**
* Defines wether or not the variable is visibile in the inspector.
*/
visibleInInspector?: boolean;
}
requires?: {
/**
* Defines the name of the module to require.
*/
module: string;
/**
* Defines the classes the require from the module.
*/
classes: string[];
}[];
}
export interface INodeContextMenuOption {
/**
* Defines the label of the extra option in the context menu.
*/
label: string;
/**
* Defines the callback caleld on the menu has been clicked.
*/
onClick: () => void;
}
export abstract class GraphNode<TProperties = Record<string, any>> extends LGraphNode {
/**
* Defines all the available properties of the node.
*/
public properties: TProperties;
/**
* Defines wether or not a break point is set on the node.
*/
public hasBeakPoint: boolean = false;
/**
* Defines wether or not the node is paused on its breakpoint.
*/
public pausedOnBreakPoint: boolean = false;
/**
* Defines the id of the node to be used internally.
*/
public readonly internalId: string = Tools.RandomId();
/**
* Defines the callback called on a widget changes.
*/
public onWidgetChange: Nullable<() => void> = null;
/**
* @hidden
*/
public _lastPosition: Vector2 = [0, 0];
private _resumeFn: Nullable<() => void> = null;
private _mouseOver: boolean = false;
private _isExecuting: boolean = false;
private _callingWidgetCallback: boolean = false;
/**
* Constructor.
* @param title defines the title of the node.
*/
public constructor(title?: string) {
super(title);
}
/**
* Returns the current scene where the graph is running.
*/
public getScene(): Scene {
return (this.graph as any).scene;
}
/**
* Called on the graph is being started.
*/
public onStart(): void {
// Nothing to do by default.
}
/**
* Called on the graph is being stopped.
*/
public onStop(): void {
this.pausedOnBreakPoint = false;
this._isExecuting = false;
NodeUtils.PausedNode = null;
}
/**
* Configures the node from an object containing the serialized infos.
* @param infos defines the JSON representation of the node.
*/
public configure(infos: SerializedLGraphNode): void {
super.configure(infos);
this.widgets?.forEach((w) => {
if (!w.name) { return; }
if (this.properties[w.name]) {
w.value = this.properties[w.name];
}
});
this._lastPosition[0] = this.pos[0];
this._lastPosition[1] = this.pos[1];
}
/**
* Retrieves the input data (data traveling through the connection) from one slot
* @param slot defines the slot id to get its input data.
* @param force_update defines wether or not to force the connected node of this slot to output data into this link
*/
public getInputData<T = any>(slot: number, force_update?: boolean): T {
let force = force_update ?? false;
for (const linkId in this.graph?.links ?? { }) {
const link = this.graph!.links[linkId];
if (link.target_id === this.id && link.target_slot === slot) {
const originNode = this.graph!.getNodeById(link.origin_id);
if (originNode && originNode.mode === LiteGraph.ALWAYS) {
force = true;
break;
}
}
}
return super.getInputData(slot, /* slot > 0 ? true : false */ force);
}
/**
* On connections changed for this node, change its mode according to the new connections.
* @param type input (1) or output (2).
* @param slot the slot which has been modified.
* @param added if the connection is newly added.
* @param link the link object informations.
* @param input the input object to check its type etc.
*/
public onConnectionsChange(type: number, _: number, added: boolean, link: LLink, input: any): void {
if (this.mode === LiteGraph.NEVER) { return; }
// Changed output type?
if (link?.type && type === LiteGraph.INPUT && input?.linkedOutput) {
const outputIndex = this.outputs.findIndex((o) => o.name === input.linkedOutput);
if (outputIndex !== -1) {
const parentNode = this.graph!.getNodeById(link.origin_id);
if (parentNode) {
this.outputs[outputIndex].type = parentNode.outputs[link.origin_slot].type;
}
this.updateConnectedNodesFromOutput(outputIndex);
}
}
// Change mode?
if (link && type === LiteGraph.INPUT && input.type === LiteGraph.EVENT) {
if (added && input.type === LiteGraph.EVENT) {
this.mode = LiteGraph.ON_TRIGGER;
} else {
this.mode = LiteGraph.ALWAYS;
}
}
NodeUtils.SetColor(this);
}
/**
* Called on a property changed.
* @param name defines the name of the property that changed.
* @param value defines the new value of the property.
*/
public propertyChanged(name: string, value: any): boolean {
for (const w of this.widgets ?? []) {
if (w.name !== name) { continue; }
w.value = value;
if (w.callback) {
this._callingWidgetCallback = true;
w.callback(value, this.graph?.list_of_graphcanvas[0]!, this, this.pos);
this._callingWidgetCallback = false;
}
break;
}
return true;
}
/**
* Adds a new widget to the node.
* @param type defines the type of widget.
* @param name defines the name of the widget.
* @param value defines the default value of the widget.
* @param callback defines the callback called on the widget changed.
* @param options defines the widget options.
*/
public addWidget<T extends IWidget>(type: T["type"], name: string, value: T["value"], callback?: WidgetCallback<T>, options?: T["options"]): T {
const originalCallback = callback as any;
let timeout: Nullable<number> = null;
let initialValue: any;
setTimeout(() => {
// Call this after the configure.
const split = name.split(".");
if (split.length > 1) {
const p = Tools.GetEffectiveProperty<any>(this.properties, name);
initialValue = p[split[split.length - 1]];
} else {
initialValue = this.properties[name];
}
}, 0);
callback = (v, g, n, p, e) => {
if (originalCallback) { originalCallback(v, g, n, p, e); }
if (this.onWidgetChange) { this.onWidgetChange(); }
if (this._callingWidgetCallback) { return; }
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(() => {
const oldValue = initialValue;
const newValue = v;
initialValue = v;
undoRedo.push({
common: () => {
this.setDirtyCanvas(true, true);
if (this.onWidgetChange) { this.onWidgetChange(); }
},
undo: () => {
originalCallback(oldValue, g, n, p, e);
this.propertyChanged(name, oldValue);
},
redo: () => {
originalCallback(newValue, g, n, p, e);
this.propertyChanged(name, newValue);
},
});
}, 500) as any;
};
return super.addWidget(type, name, value, callback, options);
}
/**
* Triggers an slot event in this node.
* @param slot the index of the output slot.
* @param param defines the parameters to send to the target slot.
* @param link_id in case you want to trigger and specific output link in a slot.
*/
public async triggerSlot(slot: number, param?: any, link_id?: number): Promise<void> {
if (this.graph!.hasPaused) {
await this.waitForBreakPoint();
}
return super.triggerSlot(slot, param ?? null, link_id);
}
/**
* Called on the node is being executed.
*/
public async onExecute(): Promise<void> {
if (this._isExecuting) {
return;
}
this._isExecuting = true;
while (this.graph!.hasPaused) {
await this.waitForBreakPoint();
}
if (this.hasBeakPoint) {
this.graph!.hasPaused = true;
this.pausedOnBreakPoint = true;
this.focusOn();
this.getScene()?.render();
NodeUtils.PausedNode = this;
await this.waitForBreakPoint();
NodeUtils.PausedNode = null;
}
try {
await this.execute();
} catch (e) {
console.error(e);
}
while (this.graph!.hasPaused) {
await this.waitForBreakPoint();
}
this._isExecuting = false;
}
/**
* In case of a breakpoint, resumes the graph.
*/
public resume(): void {
if (this._resumeFn) {
this._resumeFn();
}
this._resumeFn = null;
}
/**
* Sets the graph canvas to focus on this node.
*/
public focusOn(): void {
const graphCanvas = this.graph!.list_of_graphcanvas[0];
if (!graphCanvas) { return; }
const start = graphCanvas.ds.offset.slice();
graphCanvas.centerOnNode(this as any);
const end = graphCanvas.ds.offset.slice();
graphCanvas.ds.offset[0] = start[0];
graphCanvas.ds.offset[1] = start[1];
const anim = {
get x() { return graphCanvas.ds.offset[0]; },
set x(x: number) { graphCanvas.ds.offset[0] = x; graphCanvas.setDirty(true, true); },
get y() { return graphCanvas.ds.offset[1]; },
set y(y: number) { graphCanvas.ds.offset[1] = y; graphCanvas.setDirty(true, true); },
};
jQuery(anim).animate({ x: end[0], y: end[1] }, 750, "swing");
}
/**
* Called on the node is being executed.
*/
public abstract execute(): void | Promise<void>;
/**
* Generates the code of the node.
* @param parent defines the parent node that has been generated.
*/
public abstract generateCode(...inputs: ICodeGenerationOutput[]): ICodeGenerationOutput;
/**
* Waits until the graph is resumed.
*/
public waitForBreakPoint(): Promise<void> {
if (!this.graph) { return Promise.resolve(); }
return new Promise<void>((resolve) => this._resumeFn = resolve);
}
/**
* Draws the foreground of the node.
*/
public onDrawForeground(canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D): void {
// Collapsed?
if (this.flags["collapsed"]) { return; }
// Mode?
if (this.mode !== LiteGraph.ON_TRIGGER) { return; }
ctx = canvas as any as CanvasRenderingContext2D;
if (this.hasBeakPoint) {
if (this.pausedOnBreakPoint) {
ctx.save();
ctx.beginPath();
ctx.moveTo(this.size[0] - 20, -25);
ctx.lineTo(this.size[0] - 20, -5);
ctx.lineTo(this.size[0] - 5, -15);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
ctx.restore();
} else {
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arc(this.size[0] - 20, -15, 10, 0, Math.PI * 2);
ctx.fillStyle = `rgba(${this.pausedOnBreakPoint ? 255 : 100}, 0, 0, 255)`;
ctx.fill();
ctx.closePath();
ctx.restore();
}
} else if (this._mouseOver) {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = "#ff0000";
ctx.arc(this.size[0] - 20, -15, 10, 0, Math.PI * 2);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
}
/**
* Called each time the background is drawn.
* @param ctx defines the rendering context of the canvas.
*/
public onDrawBackground(canvas: HTMLCanvasElement, _: CanvasRenderingContext2D): void {
// Nothing to do now...
if (this.flags["collapsed"]) { return; }
this.drawBackground(canvas as any);
}
/**
* Called each time the background is drawn.
* @param ctx defines the rendering context of the canvas.
*/
public drawBackground(_: CanvasRenderingContext2D): void {
// Nothin to do now...
}
/**
* Called on the mouse is down on the node.
* @param event defines the reference to the mouse original event.
* @param pos defines the position.
* @param graphCanvas defines the canvas where the node is drawn.
*/
public onMouseDown(event: MouseEvent, pos: Vector2, graphCanvas: LGraphCanvas): void {
if (super.onMouseDown) {
super.onMouseDown(event, pos, graphCanvas);
}
// Collapsed?
if (this.flags["collapsed"]) { return; }
// Mode?
if (this.mode !== LiteGraph.ON_TRIGGER) { return; }
if (pos[0] >= this.size[0] - 30 && pos[1] <= 5) {
if (this.graph) {
this.graph.list_of_graphcanvas[0].canvas.style.cursor = "";
}
if (this.pausedOnBreakPoint) {
NodeUtils.ResumeExecution();
} else {
this.hasBeakPoint = !this.hasBeakPoint;
}
}
}
/**
* Called on the mouse enters the node.
* @param event defines the reference to the mouse original event.
* @param pos defines the position.
* @param graphCanvas defines the canvas where the node is drawn.
*/
public onMouseMove(_: MouseEvent, pos: Vector2, __: LGraphCanvas): void {
// Collapsed?
if (this.flags["collapsed"]) { return; }
// Mode?
if (this.mode !== LiteGraph.ON_TRIGGER) { return; }
if (pos[0] >= this.size[0] - 30 && pos[1] <= 5) {
setTimeout(() => this.graph!.list_of_graphcanvas[0].canvas.style.cursor = "pointer", 0);
}
}
/**
* Called on the mouse enters the node.
* @param event defines the reference to the mouse original event.
* @param pos defines the position.
* @param graphCanvas defines the canvas where the node is drawn.
*/
public onMouseEnter(event: MouseEvent, pos: Vector2, graphCanvas: LGraphCanvas): void {
if (super.onMouseEnter) {
super.onMouseEnter(event, pos, graphCanvas);
}
this._mouseOver = true;
}
/**
* Called on the mouse leaves the node.
* @param event defines the reference to the mouse original event.
* @param pos defines the position.
* @param graphCanvas defines the canvas where the node is drawn.
*/
public onMouseLeave(event: MouseEvent, pos: Vector2, graphCanvas: LGraphCanvas): void {
if (super.onMouseLeave) {
super.onMouseLeave(event, pos, graphCanvas);
}
this._mouseOver = false;
}
/**
* Called on the node is right-clicked in the Graph Editor.
* This is used to show extra options in the context menu.
*/
public getContextMenuOptions?(): INodeContextMenuOption[];
/**
* Returns the list of nodes connected to the given output.
* @param outputId defines the Id of the output.
*/
public getConnectedNodesFromOutput(outputId: number): { node: GraphNode; inputId: number; }[] {
if (!this.graph) { return []; }
const result: { node: GraphNode; inputId: number; }[] = [];
for (const linkId in this.graph.links) {
const link = this.graph.links[linkId];
if (link.origin_id !== this.id || link.origin_slot !== outputId) {
continue;
}
const node = this.graph.getNodeById(link.target_id) as GraphNode;
if (node) {
result.push({ node, inputId: link.target_slot });
}
}
return result;
}
/**
* Updates the given output's children nodes.
* @param outputId defines the Id of the output that has been updated.
*/
public updateConnectedNodesFromOutput(outputId: number): void {
const connected = this.getConnectedNodesFromOutput(outputId);
connected.forEach((c) => this.connect(outputId, c.node, c.inputId));
}
} | the_stack |
import FS from 'fs';
import Path from 'path';
import Util from 'util';
import type Stream from 'stream';
import ChildProcess from 'child_process';
import Config from '../config';
import GM from 'gm';
import Rimraf from 'rimraf';
import type { Database } from '../types';
import type { Media, SegmentMetadata } from '@vimtur/common';
import { ImportUtils, Quality } from './import-utils';
export class Transcoder {
private database: Database;
public constructor(database: Database) {
this.database = database;
}
public async createVideoThumbnail(media: Media): Promise<void> {
if (media.type !== 'video') {
throw new Error('Cannot create video thumbnail for non-video media');
}
if (!media.metadata) {
throw new Error(`Can't create thumbnail for media without metadata`);
}
await ImportUtils.mkdir(Config.get().cachePath);
await ImportUtils.mkdir(`${Config.get().cachePath}/thumbnails`);
const path = this.getThumbnailPath(media);
const args = ['-y', '-vf', 'thumbnail,scale=200:-1', '-frames:v', '1'];
if (!media.metadata.length) {
throw new Error(`Can't get thumbnail for video with no length`);
}
const inputOptions: string[] = [];
if (media.metadata.length > 10) {
const offset = Math.ceil(media.metadata.length / 4);
inputOptions.push('-ss');
inputOptions.push(`00:00:${offset >= 60 ? 59 : offset.toFixed(2)}`);
}
await ImportUtils.transcode({
input: media.absolutePath,
output: path,
outputOptions: args,
inputOptions,
});
}
public async createVideoPreview(media: Media): Promise<void> {
if (media.type !== 'video') {
throw new Error('Cannot create video thumbnail for non-video media');
}
if (!media.metadata || media.metadata.length === undefined) {
throw new Error(`Can't create thumbnail for media without metadata`);
}
await ImportUtils.mkdir(Config.get().cachePath);
await ImportUtils.mkdir(`${Config.get().cachePath}/previews`);
const fps = Config.get().transcoder.videoPreviewFps;
const count = Math.max(1, Math.floor(media.metadata.length / fps));
const height = Config.get().transcoder.videoPreviewHeight;
const maxPerColumn = Config.get().transcoder.videoPreviewMaxHeight / height;
const columns = Math.ceil(count / maxPerColumn);
const cellsPerColumn = Math.ceil(count / columns);
console.log(
`Creating preview. Count (${count}), Columns (${columns}), Cells Per Column (${cellsPerColumn}) - ${media.path}`,
);
const args = [
'-y',
'-vf',
`fps=1/${fps},scale=-1:${height},tile=${columns}x${cellsPerColumn}`,
'-frames:v',
'1',
];
const path = this.getPreviewPath(media);
await ImportUtils.transcode({
input: media.absolutePath,
output: path,
outputOptions: args,
});
}
public async optimisePng(path: string): Promise<void> {
await Util.promisify(ChildProcess.exec)(
`pngquant --speed 8 --force ${path} -o ${path}.optimised`,
);
await Util.promisify(ChildProcess.exec)(`mv ${path}.optimised ${path}`);
}
public getThumbnailPath(media: Media): string {
return `${Config.get().cachePath}/thumbnails/${media.hash}.png`;
}
public getPreviewPath(media: Media): string {
return `${Config.get().cachePath}/previews/${media.hash}.png`;
}
public async createImageThumbnail(media: Media): Promise<void> {
if (media.type !== 'gif' && media.type !== 'still') {
throw new Error('Cannot create image thumbnail for non-image media');
}
await ImportUtils.mkdir(Config.get().cachePath);
await ImportUtils.mkdir(`${Config.get().cachePath}/thumbnails`);
const output = this.getThumbnailPath(media);
const gm = GM.subClass({ nativeAutoOrient: true, imageMagick: true })(
media.absolutePath + (media.type === 'gif' ? '[0]' : ''),
)
.autoOrient()
.resize(200, 200);
await new Promise<void>((resolve, reject) => {
gm.write(output, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
public async streamMedia(
media: Media,
start: number,
end: number,
stream: Stream.Writable,
targetHeight: number,
realtime: boolean,
): Promise<void> {
if (!media.metadata || !media.metadata.length) {
throw new Error(`Can't transcode media without metadata`);
}
if (end > media.metadata.length) {
throw new Error('Requested end after end of video');
}
const inputOptions = ['-copyts'];
if (start) {
inputOptions.push(...['-ss', String(start)]);
}
inputOptions.push(...['-t', String(end - start)]);
const audioCodec = ['-acodec', 'aac', '-ac', '1', '-strict', '-2'];
const videoCodec = ['-vcodec'];
if (
media.metadata.codec === 'h264' &&
(!targetHeight || targetHeight === media.metadata.height) &&
Config.get().transcoder.maxCopyEnabled
) {
videoCodec.push(...['copy']);
} else {
const qualityRaw = ImportUtils.calculateBandwidthFromQuality(
targetHeight || media.metadata.height,
media,
true,
);
const quality = `${Math.ceil(qualityRaw / 1000000)}M`;
const qualityBuffer = `${Math.ceil((qualityRaw * 2) / 1000000)}M`;
videoCodec.push(
...[
'libx264',
'-bsf:v',
'h264_mp4toannexb',
'-tune',
'film',
...(realtime
? ['-quality', 'realtime', '-preset', 'ultrafast']
: ['-quality', 'good', '-preset', 'medium']),
'-maxrate',
quality,
'-bufsize',
qualityBuffer,
],
);
}
// To deal with strange overflows in corner cases.
videoCodec.push(...['-max_muxing_queue_size', '9999']);
const scale =
targetHeight && targetHeight !== media.metadata.height
? ['-vf', `scale=-2:${targetHeight}`]
: [];
const args = ['-y', ...audioCodec, ...scale, ...videoCodec, '-f', 'mpegts', '-muxdelay', '0'];
// If not realtime then transcode as low priority.
await ImportUtils.transcode({
input: media.absolutePath,
output: stream,
outputOptions: args,
inputOptions,
important: realtime,
});
}
public async transcodeMedia(media: Media): Promise<void> {
if (!media.metadata) {
throw new Error(`Can't transcode media set without metadata`);
}
const desiredCaches = ImportUtils.getMediaDesiredQualities(
media,
Config.get().transcoder.cacheQualities,
);
const actualCaches = media.metadata.qualityCache ?? [];
const missingQualities: Quality[] = [];
for (const quality of desiredCaches) {
if (!actualCaches.find((el) => quality.quality === el)) {
missingQualities.push(quality);
}
}
if (missingQualities.length) {
console.log(`${media.hash}: ${missingQualities.length} missing quality caches detected.`);
await ImportUtils.mkdir(`${Config.get().cachePath}/${media.hash}`);
for (const quality of missingQualities) {
await this.transcodeMediaToQuality(media, quality);
}
}
// Find redundant caches.
const redundant = ImportUtils.getRedundanctCaches(desiredCaches, actualCaches);
if (redundant.length) {
console.log(`${media.hash}: ${redundant.length} redundant caches detected.`);
for (const quality of redundant) {
console.log(`${media.hash}: Removing quality ${quality}p...`);
await Util.promisify(Rimraf)(`${Config.get().cachePath}/${media.hash}/${quality}p`);
media.metadata.qualityCache!.splice(media.metadata.qualityCache!.indexOf(quality), 1);
}
console.log(`${media.hash}: Saving quality list...`);
await this.database.saveMedia(media.hash, {
metadata: {
qualityCache: media.metadata.qualityCache,
},
});
}
}
public async getStreamPlaylist(media: Media, quality: number): Promise<string> {
if (!media.metadata) {
throw new Error('Cannot get playlist for media without metadata');
}
// If it's cached then return the cached index.
// This block copes with legacy caches.
if (media.metadata.qualityCache && media.metadata.qualityCache.includes(quality)) {
const indexPath = Path.resolve(
Config.get().cachePath,
media.hash,
`${quality}p`,
'index.m3u8',
);
if (await ImportUtils.exists(indexPath)) {
const cached = await Util.promisify(FS.readFile)(indexPath);
return cached.toString();
}
}
const segments = await this.getStreamSegments(media);
return ImportUtils.generateStreamPlaylist(media, segments);
}
public async getStreamSegments(media: Media): Promise<SegmentMetadata> {
const segments = media.metadata?.segments ?? (await ImportUtils.generateSegments(media));
if (Config.get().transcoder.enableCachingKeyframes && !media.metadata?.segments) {
await this.database.saveMedia(media.hash, {
metadata: {
segments,
},
});
}
return segments;
}
private async transcodeMediaToQuality(media: Media, requestedQuality: Quality): Promise<void> {
if (!media.metadata) {
throw new Error(`Can't transcode media without metadata`);
}
const targetHeight = requestedQuality.quality;
console.log(
`${media.hash}: ${media.path} (source ${media.metadata.height}p) - Transcoding to ${targetHeight}p...`,
);
media.metadata.qualityCache = media.metadata.qualityCache ?? [];
if (media.metadata.qualityCache.includes(targetHeight)) {
console.log(`${media.hash}: Already cached at ${targetHeight}p.`);
return;
}
media.metadata.qualityCache.push(targetHeight);
await ImportUtils.deleteFolder(`${Config.get().cachePath}/${media.hash}/${targetHeight}p`);
await ImportUtils.mkdir(`${Config.get().cachePath}/${media.hash}/${targetHeight}p`);
const segmentMetadata = await this.getStreamSegments(media);
for (const segment of segmentMetadata.standard) {
const filename = `${Config.get().cachePath}/${media.hash}/${targetHeight}p/data.ts?start=${
segment.start
}&end=${segment.end}`;
await this.streamMedia(
media,
segment.start,
segment.end,
FS.createWriteStream(filename),
requestedQuality.quality,
false,
);
}
console.log(`Saving metadata for ${media.absolutePath}`);
// This try block is to avoid it being marked as corrupted if it fails schema validation.
try {
await this.database.saveMedia(media.hash, {
metadata: media.metadata,
});
} catch (err) {
console.log('Failed to save media metadata.', err, media);
}
}
} | the_stack |
import { Nodes } from './nodes';
import { isValidType } from './types/typeHelpers';
import { Scope } from './Scope';
export type Valtype = 'i32' | 'i64' | 'f32' | 'f64' | 'u32' | 'label';
export enum NativeTypes {
i32 = 'i32',
i64 = 'i64',
f32 = 'f32',
f64 = 'f64',
anyfunc = 'anyfunc',
func = 'func',
void = 'void'
}
export abstract class Type {
nativeType?: NativeTypes;
get binaryenType(): Valtype | void {
switch (this.nativeType) {
case NativeTypes.func:
case NativeTypes.i32:
return 'i32';
case NativeTypes.f32:
return 'f32';
case NativeTypes.f64:
return 'f64';
case NativeTypes.i64:
return 'i64';
case NativeTypes.void:
return undefined;
default:
throw new Error(`Type ${this} (${this.constructor.name}) returned a undefined binaryenType`);
}
}
equals(otherType: Type) {
if (!otherType) {
return false;
}
return otherType === this;
}
canBeAssignedTo(otherType: Type, ctx: Scope): boolean {
if (this.equals(otherType)) {
return true;
}
if (otherType instanceof TypeAlias) {
return this.canBeAssignedTo(otherType.of, ctx);
}
if (otherType instanceof UnionType) {
if (otherType.of.some($ => this.canBeAssignedTo($, ctx))) {
return true;
}
}
if (otherType instanceof IntersectionType) {
return otherType.of.some($ => this.canBeAssignedTo($, ctx));
}
if (otherType instanceof AnyType) {
return true;
}
if (otherType instanceof SelfType) {
const resolved = ctx.get('Self');
const type = TypeHelpers.getNodeType(resolved.referencedNode);
if (type && type instanceof TypeType) {
return this.canBeAssignedTo(type.of, ctx);
}
}
return false;
}
abstract toString(): string;
abstract inspect(levels: number): string;
abstract schema(): Record<string, Type>;
abstract getSchemaValue(name: string, ctx: Scope): any;
}
export function areEqualTypes(typeA: Type | null | void, typeB: Type | null | void): boolean {
if (!typeA && !typeB) {
return true;
}
if (typeA && typeB && typeA.equals(typeB)) {
return true;
}
return false;
}
export class FunctionSignatureType extends Type {
readonly nativeType: NativeTypes = NativeTypes.func;
readonly parameterTypes: Type[] = [];
readonly parameterNames: string[] = [];
returnType?: Type;
canBeAssignedTo(type: Type, ctx: Scope): boolean {
if (type instanceof FunctionSignatureType) {
if (this.parameterTypes.length !== type.parameterTypes.length) return false;
if (
// can the return type be assigned?
!this.returnType ||
!type.returnType ||
!this.returnType.canBeAssignedTo(type.returnType, ctx)
) {
return false;
}
if (
// can every parameter be assigned?
this.parameterTypes.some(
($, $$) => !$ || !type.parameterTypes[$$] || !$.canBeAssignedTo(type.parameterTypes[$$], ctx)
)
) {
return false;
}
return true;
}
if (type instanceof IntersectionType) {
return type.of.every($ => this.canBeAssignedTo($, ctx));
}
return super.canBeAssignedTo(type, ctx);
}
equals(type: Type) {
if (!type) return false;
if (!(type instanceof FunctionSignatureType)) return false;
if (this.parameterTypes.length !== type.parameterTypes.length) return false;
if (!areEqualTypes(this.returnType, type.returnType)) return false;
if (this.parameterTypes.some(($, $$) => !areEqualTypes($, type.parameterTypes[$$]))) return false;
return true;
}
toString() {
const params = this.parameterTypes.map((type, ix) => {
const name = this.parameterNames && this.parameterNames[ix];
return (name ? name + ': ' : '') + (type || '?');
});
return `fun(${params.join(', ')}) -> ${this.returnType ? this.returnType : '?'}`;
}
inspect(_depth: number) {
const params = this.parameterTypes.map(type => {
if (!type) {
return '(?)';
} else {
return type.inspect(0);
}
});
return `(fun (${params.join(' ')}) ${(this.returnType && this.returnType.inspect(0)) || '?'})`;
}
schema() {
return {};
}
getSchemaValue(name: string) {
throw new Error(`Cannot read schema property ${name} of ${this.inspect(10)}`);
}
}
export class FunctionType extends Type {
readonly nativeType: NativeTypes = NativeTypes.func;
readonly signature: FunctionSignatureType = new FunctionSignatureType();
constructor(public name: Nodes.NameIdentifierNode) {
super();
}
equals(type: Type): boolean {
if (!type) return false;
if (!(type instanceof FunctionType)) return false;
if (this.name !== type.name) return false;
if (!this.signature.equals(type.signature)) return false;
return true;
}
canBeAssignedTo(type: Type, ctx: Scope): boolean {
if (type instanceof FunctionType) {
return this.signature.canBeAssignedTo(type.signature, ctx);
} else if (type instanceof FunctionSignatureType) {
return this.signature.canBeAssignedTo(type, ctx);
}
return false;
}
toString() {
return this.signature.toString();
}
inspect(_depth: number) {
const params = this.signature.parameterNames.map((_, ix) => {
const type = this.signature.parameterTypes && this.signature.parameterTypes[ix];
if (!type) {
return '(?)';
} else {
return type.inspect(0);
}
});
return `(fun ${JSON.stringify(this.name.name)} (${params.join(' ')}) ${(this.signature.returnType &&
this.signature.returnType.inspect(0)) ||
'?'})`;
}
schema() {
return {};
}
getSchemaValue(name: string) {
throw new Error(`Cannot read schema property ${name} of ${this.inspect(10)}`);
}
}
export class StructType extends Type {
nativeType: NativeTypes = NativeTypes.i64;
constructor(public parameters: Nodes.ParameterNode[]) {
super();
}
equals(type: Type): boolean {
return type === this;
}
toString() {
return '%struct';
}
canBeAssignedTo(otherType: Type, ctx: Scope) {
if (super.canBeAssignedTo(otherType, ctx)) {
return true;
}
if (RefType.isRefTypeStrict(otherType)) {
return true;
}
return false;
}
typeSimilarity(to: Type, depth: number = 1): number {
if (this.equals(to)) {
return 1 / depth;
}
return 0;
}
inspect(level: number) {
const types =
level > 1
? this.parameters
.map($ => {
const type = $.parameterType && TypeHelpers.getNodeType($.parameterType);
return ' ' + $.parameterName.name + ': ' + (type ? type.inspect(level - 1) : '(?)');
})
.join('')
: '';
return `(struct${types})`;
}
schema() {
return {
byteSize: StackType.of('u32', NativeTypes.i32, 4)
};
}
getSchemaValue(name: string) {
if (name === 'byteSize') {
return 8;
}
throw new Error(`Cannot read schema property ${name} of ${this.inspect(10)}`);
}
}
export class StackType extends Type {
private static nativeTypes = new Map<string, StackType>();
private constructor(public typeName: string, public nativeType: NativeTypes, public byteSize: number) {
super();
}
static of(name: string, nativeType: NativeTypes, byteSize: number): StackType {
const key = '_' + name + '_' + nativeType + '_' + byteSize;
let ret = StackType.nativeTypes.get(key);
if (!ret) {
ret = new StackType(name, nativeType, byteSize);
StackType.nativeTypes.set(key, ret);
}
return ret;
}
equals(other: Type): boolean {
return other === this;
}
canBeAssignedTo(other: Type, ctx: Scope) {
const otherType = getUnderlyingTypeFromAlias(other);
if (
otherType instanceof StackType &&
otherType.nativeType === this.nativeType &&
otherType.typeName === this.typeName &&
otherType.byteSize === this.byteSize
) {
return true;
}
return super.canBeAssignedTo(other, ctx);
}
toString() {
return this.typeName;
}
inspect() {
return '(native ' + this.typeName + ')';
}
schema() {
return {
byteSize: StackType.of('u32', NativeTypes.i32, 4),
allocationSize: StackType.of('u32', NativeTypes.i32, 4),
stackSize: StackType.of('u32', NativeTypes.i32, 4)
};
}
getSchemaValue(name: string) {
if (name === 'byteSize') {
return this.byteSize;
} else if (name === 'stackSize') {
return this.byteSize;
} else if (name === 'allocationSize') {
return this.byteSize;
}
throw new Error(`Cannot read schema property ${name} of ${this.inspect()}`);
}
}
const u32 = StackType.of('u32', NativeTypes.i32, 4);
const voidType = StackType.of('void', NativeTypes.void, 0);
export class RefType extends Type {
static instance: RefType = new RefType();
nativeType: NativeTypes = NativeTypes.i64;
readonly byteSize = 8;
protected constructor() {
super();
}
// returns true when otherType is explicityly RefType.instance
static isRefTypeStrict(otherType: Type) {
return getUnderlyingTypeFromAlias(otherType) === RefType.instance;
}
toString() {
return 'ref';
}
inspect() {
return '(ref ?)';
}
canBeAssignedTo(otherType: Type, _ctx: Scope): boolean {
return RefType.isRefTypeStrict(otherType);
}
typeSimilarity(to: Type, depth: number = 1): number {
if (this.equals(to)) {
return 1 / depth;
}
return 0;
}
equals(otherType: Type): boolean {
if (!otherType) return false;
return RefType.isRefTypeStrict(otherType);
}
schema() {
return {
byteSize: StackType.of('u32', NativeTypes.i32, 4),
stackSize: StackType.of('u32', NativeTypes.i32, 4),
allocationSize: StackType.of('u32', NativeTypes.i32, 4)
};
}
getSchemaValue(name: string) {
if (name === 'byteSize') {
return 8;
} else if (name === 'stackSize') {
return 8;
} else if (name === 'allocationSize') {
return 8;
}
throw new Error(`Cannot read schema property ${name} of ${this.inspect()}`);
}
}
export class IntersectionType extends Type {
nativeType: NativeTypes = NativeTypes.anyfunc;
constructor(public of: Type[] = []) {
super();
}
toString() {
if (this.of.length === 0) return '(empty intersection)';
return this.of.map($ => ($ || '?').toString()).join(' & ');
}
canBeAssignedTo(other: Type, ctx: Scope) {
if (other instanceof IntersectionType) {
// intersections can be assigned only if every type of
// the other intersection can be assigned by some of the types of this intersection
return other.of.every(otherType => this.of.some(thisType => thisType.canBeAssignedTo(otherType, ctx)));
}
if (this.equals(other)) {
return true;
}
return this.of.some($ => $.canBeAssignedTo(other, ctx));
}
inspect(levels: number = 0) {
return '(intersection ' + this.of.map($ => ($ ? $.inspect(levels - 1) : '(?)')).join(' ') + ')';
}
simplify(): Type {
const newTypes: Type[] = [];
function collectIntersection($: Type) {
if ($ instanceof IntersectionType) {
$.of.forEach($ => {
collectIntersection($);
});
} else {
if (!newTypes.some($1 => areEqualTypes($, $1))) {
newTypes.push($);
}
}
}
this.of.forEach(collectIntersection);
if (newTypes.length === 1) {
return newTypes[0];
} else {
return new IntersectionType(newTypes);
}
}
equals(other: Type): boolean {
if (!other) return false;
return (
other instanceof IntersectionType &&
this.of.length === other.of.length &&
this.of.every(($, ix) => areEqualTypes($, other.of[ix]))
);
}
schema() {
return {};
}
getSchemaValue(name: string) {
throw new Error(`Cannot read schema property ${name} of ${this.inspect(10)}`);
}
}
export function getUnderlyingTypeFromAlias(type: Type): Type {
if (type instanceof TypeAlias) {
return getUnderlyingTypeFromAlias(type.of);
} else {
return type;
}
}
export class UnionType extends Type {
get binaryenType(): Valtype {
const nativeTypes = new Set<Valtype>();
this.of.forEach($ => {
if (NeverType.isNeverType($)) return;
nativeTypes.add($.binaryenType as Valtype);
});
if (nativeTypes.size === 0) {
throw new Error('Cannot find a suitable low level type for ' + this.toString() + ' (0)');
}
if (nativeTypes.size === 1) {
return nativeTypes.values().next().value;
} else {
throw new Error('Cannot find a suitable low level type for ' + this.toString());
}
}
constructor(public of: Type[] = [], public readonly simplified = false) {
super();
}
static of(x: Type[] | Type): UnionType {
if (x instanceof UnionType) {
return x;
} else if (x instanceof Type) {
return new UnionType([x], true);
} else if (x instanceof Array) {
return new UnionType(x);
}
throw new Error('Cannot create UnionType');
}
toString() {
if (this.of.length === 0) return '(empty union)';
return this.of.map($ => ($ || '?').toString()).join(' | ');
}
inspect(levels: number = 0) {
if (this.of.length === 0) return `(union EMPTY)`;
return '(union ' + this.of.map($ => ($ ? $.inspect(levels - 1) : '(?)')).join(' ') + ')';
}
canBeAssignedTo(otherType: Type, ctx: Scope) {
return this.of.every($ => $.canBeAssignedTo(otherType, ctx));
}
equals(other: Type): boolean {
if (!other) return false;
return (
other instanceof UnionType &&
this.of.length === other.of.length &&
this.of.every(($, ix) => areEqualTypes($, other.of[ix]))
);
}
/**
* This method expands the union type made by other union types into a single
* union made of the atoms of every member of the initial union. Recursively.
*/
expand(ctx: Scope): Type {
const newSet = new Set<Type>();
function add(typeToAdd: Type) {
const candidate = getUnderlyingTypeFromAlias(typeToAdd);
if (candidate instanceof UnionType) {
// If it is an union, we must expand it for each atom
candidate.of.forEach($ => add($));
} else {
// finalize if already present
if (newSet.has(typeToAdd)) {
return;
}
for (let $ of newSet) {
// finalize if we already have a type A == B && B == A
if ($.equals(typeToAdd) && typeToAdd.equals($)) {
return;
}
}
newSet.add(typeToAdd);
}
}
this.of.forEach(add);
const newTypes = Array.from(newSet.values());
return new UnionType(newTypes).simplify(ctx);
}
/**
* This method removes an element from the union
* @param type type to subtract
*/
subtract(type: Type | null, ctx: Scope): Type {
if (!type) return this;
const removingRefType = RefType.isRefTypeStrict(type);
if (!this.simplified) {
return UnionType.of(this.expand(ctx)).subtract(type, ctx);
}
const newSet = new Set<Type>();
for (let $ of this.of) {
if ((!removingRefType && RefType.isRefTypeStrict($)) || !$.canBeAssignedTo(type, ctx)) {
newSet.add($);
}
}
if (newSet.size === 0) {
return InjectableTypes.never;
}
const newTypes = Array.from(newSet.values());
if (newTypes.length === 1) {
return newTypes[0];
}
return new UnionType(newTypes);
}
/**
* This method simplifies the union type. e.g:
*
* type T0 = A | A | A | B
* type T0Simplified = A | B
*
* It removes types present in unions
*
* type T1 = T0Simplified | B | C | A
* type T1Simplified = T0Simplified | C
*
*
*/
simplify(ctx: Scope) {
if (this.of.length === 1) {
return this.of[0];
}
let newTypes: Type[] = [];
this.of.forEach($ => {
if (NeverType.isNeverType($)) return;
if (!newTypes.some($1 => areEqualTypes($1, $)) && $) {
newTypes.push($);
}
});
if (newTypes.length === 0) {
return InjectableTypes.never;
}
let unions: UnionType[] = [];
function collectUnion($: Type) {
const candidate = getUnderlyingTypeFromAlias($);
if (candidate instanceof UnionType) {
if (!unions.includes(candidate)) {
unions.push(candidate);
candidate.of.forEach($ => {
collectUnion($);
});
}
}
}
// Collect unions
newTypes.forEach(collectUnion);
// This are the unions that generate some conflict with other unions,
// therefore we need to expand those unions to the atoms
const blackListedUnionAtoms: Type[] = [];
const unionsToRemove: UnionType[] = [];
// Find the conflictive atoms
unions.forEach((union, ix) => {
const expanded = UnionType.of(union.expand(ctx));
const hasConflict = expanded.of.some(atom => unions.some(($, $$) => $$ !== ix && atom.canBeAssignedTo($, ctx)));
if (hasConflict) {
blackListedUnionAtoms.push(...expanded.of);
// we are removing the union, it might have elements not present in the
// newTypes, we add them
expanded.of.forEach($ => {
if (!newTypes.some($1 => $1.equals($))) {
newTypes.push($);
}
});
unionsToRemove.push(union);
}
});
unions = unions.filter($ => !unionsToRemove.includes($));
// Eliminate types present in unions
newTypes.forEach((newType, i) => {
const candidate = getUnderlyingTypeFromAlias(newType);
if (unionsToRemove.includes(candidate as any)) {
(newTypes as any)[i] = null;
return;
}
if (RefType.isRefTypeStrict(candidate) || blackListedUnionAtoms.some(x => candidate.canBeAssignedTo(x, ctx))) {
return;
}
if (unions.some(union => !union.equals(candidate) && candidate.canBeAssignedTo(union, ctx))) {
(newTypes as any)[i] = null;
}
});
// Remove eliminated types
newTypes = newTypes.filter($ => !!$);
if (newTypes.length === 1) {
return newTypes[0];
} else {
return new UnionType(newTypes, true);
}
}
schema() {
return {
byteSize: u32,
stackSize: u32
};
}
getSchemaValue(name: string, ctx: Scope) {
if (name === 'byteSize') {
const nativeTypes = new Set<number>();
this.of.forEach($ => {
if (NeverType.isNeverType($)) return;
nativeTypes.add($.getSchemaValue('byteSize', ctx));
});
if (nativeTypes.size === 0) {
throw new Error('Cannot find a consistent byteSize in ' + this.inspect(100) + ' (0)');
}
if (nativeTypes.size === 1) {
return nativeTypes.values().next().value;
} else {
throw new Error('Cannot find a consistent byteSize in ' + this.inspect(100));
}
} else if (name === 'allocationSize') {
return 8;
} else if (name === 'stackSize') {
return 8;
}
throw new Error(`Cannot read schema property ${name} of ${this.inspect(10)}`);
}
}
function mapAinB<X, Y>(a: Map<X, Y>, b: Map<X, Y>) {
for (let [key, value] of a) {
if (!b.has(key)) return false;
if (b.get(key) !== value) return false;
}
return true;
}
function areMapsEqual<X, Y>(a: Map<X, Y>, b: Map<X, Y>): boolean {
if (a.size !== b.size) return false;
if (!mapAinB(a, b)) return false;
if (!mapAinB(b, a)) return false;
return true;
}
export class TypeAlias extends Type {
get binaryenType() {
return this.of.binaryenType;
}
get nativeType(): NativeTypes {
return this.of.nativeType as NativeTypes;
}
discriminant: number | null = null;
traits: Map<Nodes.ImplDirective, TraitType> = new Map();
constructor(public name: Nodes.NameIdentifierNode, public readonly of: Type) {
super();
}
canBeAssignedTo(other: Type, ctx: Scope): boolean {
// | if (other instanceof TraitType) {
// | for (let [, trait] of this.traits) {
// | if (trait.equals(other)) {
// | return true;
// | }
// | }
// | }
if (other instanceof SelfType) {
const resolved = ctx.get('Self');
const type = TypeHelpers.getNodeType(resolved.referencedNode);
if (type && type instanceof TypeType) {
return this.canBeAssignedTo(type.of, ctx);
}
}
return this.of.canBeAssignedTo(other, ctx);
}
equals(other: Type): boolean {
if (!(other instanceof TypeAlias)) return false;
if (other.name !== this.name) return false;
if (other.discriminant !== this.discriminant) return false;
if (!areMapsEqual(this.traits, other.traits)) {
return false;
}
if (!areEqualTypes(this.of, other.of)) return false;
return true;
}
toString(): string {
return this.name.name;
}
inspect(levels: number = 0) {
const ofString = levels > 0 ? ' ' + (this.of ? this.of.inspect(levels - 1) : '(?)') : '';
return `(alias ${this.name.name}${ofString})`;
}
schema() {
const result: Record<string, Type> = {
...this.of.schema(),
discriminant: u32
};
const baseType = getUnderlyingTypeFromAlias(this);
if (baseType instanceof StructType) {
result['allocationSize'] = u32;
result['stackSize'] = u32;
const properties = this.getOrderedProperties();
properties.forEach(prop => {
result[`property$${prop.index}_offset`] = u32;
result[`property$${prop.index}_allocationSize`] = u32;
});
}
return result;
}
getSchemaValue(name: string, ctx: Scope) {
if (name === 'discriminant') {
if (this.discriminant === null) {
throw new Error('empty discriminant');
}
return this.discriminant;
} else {
const baseType = getUnderlyingTypeFromAlias(this);
if (baseType instanceof StructType) {
if (name === 'stackSize') {
return 8;
} else if (name === 'allocationSize') {
const properties = this.getOrderedProperties();
let offset = 0;
for (let prop of properties) {
const fn = getNonVoidFunction(TypeHelpers.getNodeType(prop.name) as IntersectionType, ctx);
offset += fn!.signature.returnType!.getSchemaValue('byteSize', ctx);
}
return offset;
} else if (name.startsWith('property$')) {
const properties = this.getOrderedProperties();
const index = parseInt(name.substr('property$'.length), 10);
const property = properties.find($ => $.index === index);
if (!property) {
throw new Error('cannot find property index ' + index);
}
if (name.endsWith('_offset')) {
let offset = 0;
for (let prop of properties) {
if (prop.index === index) {
break;
}
const fn = getNonVoidFunction(TypeHelpers.getNodeType(prop.name) as IntersectionType, ctx);
offset += fn!.signature.returnType!.getSchemaValue('stackSize', ctx);
}
return offset;
} else if (name.endsWith('_allocationSize')) {
const fn = getNonVoidFunction(TypeHelpers.getNodeType(property.name) as IntersectionType, ctx);
return fn!.signature.returnType!.getSchemaValue('allocationSize', ctx);
}
}
}
}
return this.of.getSchemaValue(name, ctx);
}
getTypeMember(name: string, getType: (node: Nodes.Node) => Type | null): [Nodes.NameIdentifierNode, Type][] {
const ret: [Nodes.NameIdentifierNode, Type][] = [];
for (let impl of this.name.impls) {
const resolvedName = impl.namespaceNames.get(name);
if (resolvedName) {
const memberType = getType(resolvedName);
if (!isValidType(memberType)) {
return [];
}
ret.push([resolvedName, memberType]);
}
}
if (this.of instanceof TypeAlias) {
ret.push(...this.of.getTypeMember(name, getType));
}
return ret;
}
private getOrderedProperties() {
const properties: Array<{ index: number; name: Nodes.NameIdentifierNode }> = [];
// TODO: review this.
for (let impl of this.name.impls) {
for (let [name, nameIdentifierNode] of impl.namespaceNames) {
if (name.startsWith('property$')) {
const index = parseInt(name.substr('property$'.length), 10);
properties.push({ index, name: nameIdentifierNode });
}
}
}
properties.sort((a, b) => {
if (a.index > b.index) {
return 1;
} else {
return -1;
}
});
return properties;
}
}
export class TraitType extends Type {
get binaryenType() {
return undefined;
}
get nativeType(): NativeTypes {
return NativeTypes.void;
}
constructor(public traitNode: Nodes.TraitDirectiveNode) {
super();
}
canBeAssignedTo(other: Type, _ctx: Scope): boolean {
return this === other;
}
equals(other: Type): boolean {
return other === this;
}
toString(): string {
return this.traitNode.traitName.name;
}
inspect(levels: number = 0) {
const subtypes: string[] = [];
if (levels > 1) {
this.traitNode.namespaceNames.forEach((value, key) => {
const t = TypeHelpers.getNodeType(value);
subtypes.push('[' + key + ': ' + (t ? t.inspect(levels - 1) : 'null') + ']');
});
}
return `(trait ${this.traitNode.traitName.name}${subtypes.map($ => ' ' + $).join('')})`;
}
getSignatureOf(name: string): Type | null {
const declName = this.traitNode.namespaceNames.get(name);
if (!declName) return null;
return TypeHelpers.getNodeType(declName);
}
schema() {
const result: Record<string, Type> = {};
return result;
}
getSchemaValue(name: string) {
throw new Error(`Cannot read schema property ${name} of ${this.inspect()}`);
}
}
function getNonVoidFunction(type: IntersectionType, ctx: Scope): FunctionType | null {
const functions = type.of as FunctionType[];
for (let fn of functions) {
if (fn.signature.returnType && !voidType.canBeAssignedTo(fn.signature.returnType, ctx)) {
return fn;
}
}
return null;
}
export class TypeType extends Type {
static memMap = new WeakMap<Type, TypeType>();
private constructor(public readonly of: Type) {
super();
}
static of(of: Type) {
let ret = this.memMap.get(of);
if (!ret) {
ret = new TypeType(of);
this.memMap.set(of, ret);
}
return ret;
}
canBeAssignedTo(other: Type, ctx: Scope): boolean {
const otherType = getUnderlyingTypeFromAlias(other);
if (otherType instanceof TypeType) {
return this.of.canBeAssignedTo(otherType.of, ctx);
}
return false;
}
equals(other: Type): boolean {
if (!other) return false;
return other instanceof TypeType && areEqualTypes(other.of, this.of);
}
inspect(levels: number = 0) {
return `(type ${this.of.inspect(levels - 1)})`;
}
toString() {
return `Type<${this.of}>`;
}
schema() {
return this.of.schema();
}
getSchemaValue(name: string, ctx: Scope) {
return this.of.getSchemaValue(name, ctx);
}
}
// https://en.wikipedia.org/wiki/Bottom_type
// https://en.wikipedia.org/wiki/Fail-stop
export class NeverType extends Type {
static isNeverType(otherType: Type) {
return getUnderlyingTypeFromAlias(otherType) instanceof NeverType;
}
get nativeType() {
return NativeTypes.void;
}
toString(): string {
return 'never';
}
inspect(): string {
return '(never)';
}
equals(other: Type) {
if (NeverType.isNeverType(other)) {
return true;
}
if (other instanceof UnionType) {
if (other.of.length === 0) {
return true;
}
if (other.of.length === 1 && this.equals(other.of[0])) {
return true;
}
}
return super.equals(other);
}
canBeAssignedTo(_: Type, _ctx: Scope) {
return true;
}
schema() {
return {};
}
getSchemaValue(name: string) {
throw new Error(`Cannot read schema property ${name} of ${this.inspect()}`);
}
}
export class SelfType extends Type {
get nativeType() {
return NativeTypes.anyfunc;
}
constructor(public traitType: TraitType) {
super();
}
toString(): string {
return 'Self';
}
inspect(): string {
return `(self ${this.traitType.inspect(0)})`;
}
canBeAssignedTo(_: Type, _ctx: Scope) {
console.log(_ctx.inspect(true), _.inspect(1));
return false;
}
schema() {
return {};
}
getSchemaValue(name: string) {
throw new Error(`Cannot read schema property ${name} of ${this.inspect()}`);
}
}
// https://en.wikipedia.org/wiki/Top_type
export class AnyType extends Type {
get nativeType() {
return NativeTypes.anyfunc;
}
toString(): string {
return 'any';
}
inspect(): string {
return '(any)';
}
canBeAssignedTo(_: Type, _ctx: Scope) {
return false;
}
schema() {
return {};
}
getSchemaValue(name: string) {
throw new Error(`Cannot read schema property ${name} of ${this.inspect()}`);
}
}
export const InjectableTypes = Object.assign(Object.create(null) as unknown, {
void: voidType,
ref: RefType.instance,
never: new NeverType(),
AnyType: TypeType.of(new AnyType()),
Any: new AnyType()
});
export const UNRESOLVED_TYPE = new NeverType();
export namespace TypeHelpers {
const ofTypeSymbol = Symbol('ofType');
export function getNodeType(node: Nodes.Node): Type | null {
if (!node) return null;
return (node as any)[ofTypeSymbol] || null;
}
export function setNodeType(node: Nodes.Node, type: Type | null): void {
(node as any)[ofTypeSymbol] = type;
node.isTypeResolved = isValidType(type);
}
} | the_stack |
import { Controller } from 'egg'
import { WxPayApiConifgKit, WX_DOMAIN, WX_API_TYPE, WxPayApiConfig, PayKit, WxPay, Kits, WX_TRADE_TYPE, SIGN_TYPE, HttpKit, RequestMethod } from 'tnwx'
import * as fs from 'fs'
import * as path from 'path'
import * as x509 from 'x509'
export default class WxPayController extends Controller {
public async index() {
const { ctx } = this
let type: number = parseInt(ctx.query.type)
let config: WxPayApiConfig = WxPayApiConifgKit.getConfig
let ip = ctx.request.ip
console.log(`type: ${type}, ip:${ip}`)
switch (type) {
case 100:
// 获取配置
try {
const cert = x509.parseCert(config.certPath)
console.log(`证书序列号:${cert.serial}`)
ctx.body = cert
} catch (error) {
console.log(error)
}
break
case 0:
// 获取配置
try {
ctx.body = JSON.stringify(config)
} catch (error) {
console.log(error)
}
break
case 1:
// 获取沙箱环境 key
try {
let data = await WxPay.getSignKey(config.mchId, config.apiKey, SIGN_TYPE.SIGN_TYPE_MD5)
ctx.body = await Kits.xml2obj(data)
} catch (error) {
console.log(error)
}
break
case 2:
// 统一下单
try {
let reqObj = {
appid: config.appId,
mch_id: config.mchId,
nonce_str: Kits.generateStr(), //生成随机字符串
body: 'IJPay 让支付触手可及',
attach: 'TNWX 微信系开发脚手架',
out_trade_no: Kits.generateStr(),
total_fee: 666,
spbill_create_ip: ip,
notify_url: 'https://gitee.com/Javen205/TNWX',
trade_type: WX_TRADE_TYPE.JSAPI,
sign_type: SIGN_TYPE.SIGN_TYPE_HMACSHA256
}
let xml = await Kits.generateSignedXml(reqObj, config.apiKey, SIGN_TYPE.SIGN_TYPE_HMACSHA256)
let data = await HttpKit.getHttpDelegate.httpPost(WX_DOMAIN.CHINA.concat(WX_API_TYPE.UNIFIED_ORDER), xml)
// ctx.set('Content-Type', 'text/xml')
// ctx.body = data
ctx.body = await Kits.xml2obj(data)
} catch (error) {
console.log(error)
}
break
case 3:
// 双向证书 退款
try {
let refundObj = {
appid: config.appId,
mch_id: config.mchId,
nonce_str: Kits.generateStr(), //生成随机字符串
out_trade_no: Kits.generateStr(),
out_refund_no: Kits.generateStr(),
total_fee: 666,
refund_fee: 100,
sign_type: SIGN_TYPE.SIGN_TYPE_HMACSHA256
}
let xml = await Kits.generateSignedXml(refundObj, config.apiKey, SIGN_TYPE.SIGN_TYPE_HMACSHA256)
let pfx: Buffer = fs.readFileSync(config.certP12Path)
let data = await HttpKit.getHttpDelegate.httpPostWithCert(WX_DOMAIN.CHINA.concat(WX_API_TYPE.REFUND), xml, pfx, config.mchId)
ctx.body = await Kits.xml2obj(data)
} catch (error) {
console.log(error)
}
break
case 4:
// Api-v3 get 请求
try {
let result = await PayKit.v3(
RequestMethod.GET,
WX_DOMAIN.CHINA, //
WX_API_TYPE.GET_CERTIFICATES,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath)
)
console.log(`result.data:${result.data}`)
// 应答报文主体
let data = JSON.stringify(result.data)
// 应答状态码
console.log(`status:${result.status}`)
console.log(`data:${data}`)
// http 请求头
let headers = result.headers
// 证书序列号
let serial = headers['wechatpay-serial']
// 应答时间戳
let timestamp = headers['wechatpay-timestamp']
// 应答随机串
let nonce = headers['wechatpay-nonce']
// 应答签名
let signature = headers['wechatpay-signature']
console.log(`serial:\n${serial}`)
console.log(`timestamp:\n${timestamp}`)
console.log(`nonce:\n${nonce}`)
console.log(`signature:\n${signature}`)
// 根据序列号查证书 验证签名
// let verifySignature: boolean = PayKit.verifySignature(signature, data, nonce, timestamp, fs.readFileSync(ctx.app.config.WxPayConfig.wxCertPath))
let verifySignature: boolean = PayKit.verifySign(headers, data, fs.readFileSync(ctx.app.config.WxPayConfig.wxCertPath))
console.log(`verifySignature:${verifySignature}`)
ctx.body = data
} catch (error) {
console.log(error)
}
break
case 5:
// Api-v3 get 请求 有参数
try {
let params: Map<string, string> = new Map()
params.set('service_id', '500001')
params.set('appid', 'wxd678efh567hg6787')
params.set('openid', 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o')
let result = await PayKit.v3(
RequestMethod.GET,
WX_DOMAIN.CHINA, //
WX_API_TYPE.PAY_SCORE_USER_SERVICE_STATE,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath),
'',
params
)
console.log(`status:${result.status}`)
ctx.body = result.data
} catch (error) {
console.log(error)
}
break
case 6:
// Api-v3 delete 请求
try {
let result = await PayKit.v3(
RequestMethod.DELETE,
WX_DOMAIN.CHINA, //
WX_API_TYPE.MERCHANT_SERVICE_COMPLAINTS_NOTIFICATIONS,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath)
)
ctx.body = `status:${result.status}`
} catch (error) {
console.log(error)
}
break
case 7:
// Api-v3 post 请求
try {
let data: string = JSON.stringify({
url: 'https://gitee.com/javen205/TNWX'
})
console.log(`data:${data}`)
let result = await PayKit.v3(
RequestMethod.POST,
WX_DOMAIN.CHINA, //
WX_API_TYPE.MERCHANT_SERVICE_COMPLAINTS_NOTIFICATIONS,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath),
data
)
console.log(`status:${result.status}`)
ctx.body = result.data
} catch (error) {
console.log(error)
}
break
case 8:
// 证书和回调报文解密
let certPath = '/Users/Javen/cert/platform_cert.pem'
try {
let decrypt = PayKit.aes256gcmDecrypt(
config.apiKey3,
ctx.app.config.AEAD_AES_256_GCM.nonce,
ctx.app.config.AEAD_AES_256_GCM.associated_data,
ctx.app.config.AEAD_AES_256_GCM.ciphertext
)
// 保存证书
fs.writeFileSync(certPath, decrypt)
ctx.body = decrypt
} catch (error) {
console.log(error)
}
break
case 9:
// 微信公众号、微信小程序预付订单二次签名
try {
let data = WxPay.prepayIdCreateSign('prepayId', config.appId, config.apiKey, SIGN_TYPE.SIGN_TYPE_HMACSHA256)
ctx.body = data
} catch (error) {
console.log(error)
}
break
case 10:
// APP支付二次签名
try {
let data = WxPay.appPrepayIdCreateSign('prepayId', config.appId, config.mchId, config.apiKey, SIGN_TYPE.SIGN_TYPE_HMACSHA256)
ctx.body = data
} catch (error) {
console.log(error)
}
break
case 11:
// 文件上传
try {
let filePath = '/Users/Javen/Documents/pic/wxpay.png'
let sha256 = Kits.sha256x(fs.readFileSync(filePath))
let filename = path.basename(filePath)
console.log(sha256)
console.log(filename)
let data: string = JSON.stringify({
filename,
sha256
})
console.log(`data:${data}`)
let result = await PayKit.exeUpload(
WX_DOMAIN.CHINA, //
WX_API_TYPE.MERCHANT_UPLOAD_MEDIA,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath),
filePath,
data
)
console.log(`status:${result.status}`)
ctx.body = result.data
} catch (error) {
console.log(error)
}
break
case 12:
try {
let data: string = JSON.stringify({
appid: config.appId,
mchid: config.mchId,
description: 'TNWX 微信支付-扫码支付',
out_trade_no: Kits.generateStr(),
notify_url: config.getDomin,
amount: {
total: 800
}
})
console.log(`data:${data}`)
let result = await PayKit.v3(
RequestMethod.POST,
WX_DOMAIN.CHINA,
WX_API_TYPE.NATIVE_PAY,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath),
data
)
console.log(`status:${result.status}`)
ctx.body = result.data
} catch (error) {
console.log(error)
}
break;
case 13:
try {
let data: string = JSON.stringify({
appid: config.appId,
mchid: config.mchId,
description: 'TNWX 微信支付-JSAPI支付',
out_trade_no: Kits.generateStr(),
notify_url: config.getDomin,
amount: {
total: 800
},
payer: {
openid: 'o-_-itxuXeGW3O1cxJ7FXNmq8Wf8'
}
})
console.log(`data:${data}`)
let result = await PayKit.v3(
RequestMethod.POST,
WX_DOMAIN.CHINA,
WX_API_TYPE.JS_API_PAY,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath),
data
)
let status = result.status
let prepayId: string, paySign: string
if (status === 200) {
prepayId = result.data.prepay_id
let appId: string = config.appId
let timeStamp: string = parseInt((Date.now() / 1000).toString()) + ''
let nonceStr: string = Kits.generateStr()
let ext: string = 'prepayId='.concat(prepayId)
paySign = WxPay.createSign([appId, timeStamp, nonceStr, ext], fs.readFileSync(config.keyPath))
let json = JSON.stringify({
appId: appId,
timeStamp: timeStamp,
nonceStr: nonceStr,
package: ext,
signType: 'RSA',
paySign: paySign,
})
ctx.body = json
return
}
ctx.body = result.data
} catch (error) {
console.log(error)
}
break;
case 14:
try {
let data: string = JSON.stringify({
appid: config.appId,
mchid: config.mchId,
description: 'TNWX 微信支付-H5支付',
out_trade_no: Kits.generateStr(),
notify_url: config.getDomin,
amount: {
total: 800
},
scene_info: {
payer_client_ip: ip,
h5_info: {
type: 'Wap'
}
}
})
console.log(`data:${data}`)
let result = await PayKit.v3(
RequestMethod.POST,
WX_DOMAIN.CHINA,
WX_API_TYPE.H5_PAY,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath),
data
)
console.log(`status:${result.status}`)
ctx.body = result.data
} catch (error) {
console.log(error)
}
break;
case 15:
try {
let data: string = JSON.stringify({
url: 'https://gitee.com/javen205/IJPay'
})
console.log(`data:${data}`)
let result = await PayKit.v3(
RequestMethod.POST,
WX_DOMAIN.CHINA,
WX_API_TYPE.MERCHANT_SERVICE_COMPLAINTS_NOTIFICATIONS,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath),
data
)
console.log(`status:${result.status}`)
ctx.body = result.data
} catch (error) {
console.log(error)
}
break;
case 16:
try {
let data: string = JSON.stringify({
url: 'https://gitee.com/javen205/IJPay'
})
console.log(`data:${data}`)
let result = await PayKit.v3(
RequestMethod.PUT,
WX_DOMAIN.CHINA,
WX_API_TYPE.MERCHANT_SERVICE_COMPLAINTS_NOTIFICATIONS,
config.mchId,
x509.parseCert(config.certPath).serial,
fs.readFileSync(config.keyPath),
data
)
console.log(`status:${result.status}`)
ctx.body = result.data
} catch (error) {
console.log(error)
}
break;
default:
break
}
}
} | the_stack |
// prettier-ignore
export const fontA02 = new Uint8Array([
/* 0 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 1 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 2 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 3 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 4 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 5 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 6 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 7 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 8 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 9 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 10 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 11 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 12 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 13 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 14 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 15 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 32 */ 0, 2, 6, 14, 30, 14, 6, 2,
/* 33 */ 0, 8, 12, 14, 15, 14, 12, 8,
/* 34 */ 0, 18, 9, 27, 0, 0, 0, 0,
/* 35 */ 0, 27, 18, 9, 0, 0, 0, 0,
/* 36 */ 0, 4, 14, 31, 0, 4, 14, 31,
/* 37 */ 0, 31, 14, 4, 0, 31, 14, 4,
/* 38 */ 0, 0, 14, 31, 31, 31, 14, 0,
/* 39 */ 0, 16, 16, 20, 18, 31, 2, 4,
/* 40 */ 0, 4, 14, 21, 4, 4, 4, 4,
/* 41 */ 0, 4, 4, 4, 4, 21, 14, 4,
/* 42 */ 0, 0, 4, 8, 31, 8, 4, 0,
/* 43 */ 0, 0, 4, 2, 31, 2, 4, 0,
/* 44 */ 0, 8, 4, 2, 4, 8, 0, 31,
/* 45 */ 0, 2, 4, 8, 4, 2, 0, 31,
/* 46 */ 0, 0, 4, 4, 14, 14, 31, 0,
/* 47 */ 0, 0, 31, 14, 14, 4, 4, 0,
/* 48 */ 0, 0, 0, 0, 0, 0, 0, 0,
/* 49 */ 0, 4, 4, 4, 4, 0, 0, 4,
/* 50 */ 0, 10, 10, 10, 0, 0, 0, 0,
/* 51 */ 0, 10, 10, 31, 10, 31, 10, 10,
/* 52 */ 0, 4, 30, 5, 14, 20, 15, 4,
/* 53 */ 0, 3, 19, 8, 4, 2, 25, 24,
/* 54 */ 0, 6, 9, 5, 2, 21, 9, 22,
/* 55 */ 0, 6, 4, 2, 0, 0, 0, 0,
/* 56 */ 0, 8, 4, 2, 2, 2, 4, 8,
/* 57 */ 0, 2, 4, 8, 8, 8, 4, 2,
/* 58 */ 0, 0, 4, 21, 14, 21, 4, 0,
/* 59 */ 0, 0, 4, 4, 31, 4, 4, 0,
/* 60 */ 0, 0, 0, 0, 0, 6, 4, 2,
/* 61 */ 0, 0, 0, 0, 31, 0, 0, 0,
/* 62 */ 0, 0, 0, 0, 0, 0, 6, 6,
/* 63 */ 0, 0, 16, 8, 4, 2, 1, 0,
/* 64 */ 0, 14, 17, 25, 21, 19, 17, 14,
/* 65 */ 0, 4, 6, 4, 4, 4, 4, 14,
/* 66 */ 0, 14, 17, 16, 8, 4, 2, 31,
/* 67 */ 0, 31, 8, 4, 8, 16, 17, 14,
/* 68 */ 0, 8, 12, 10, 9, 31, 8, 8,
/* 69 */ 0, 31, 1, 15, 16, 16, 17, 14,
/* 70 */ 0, 12, 2, 1, 15, 17, 17, 14,
/* 71 */ 0, 31, 17, 16, 8, 4, 4, 4,
/* 72 */ 0, 14, 17, 17, 14, 17, 17, 14,
/* 73 */ 0, 14, 17, 17, 30, 16, 8, 6,
/* 74 */ 0, 0, 6, 6, 0, 6, 6, 0,
/* 75 */ 0, 0, 6, 6, 0, 6, 4, 2,
/* 76 */ 0, 8, 4, 2, 1, 2, 4, 8,
/* 77 */ 0, 0, 0, 31, 0, 31, 0, 0,
/* 78 */ 0, 2, 4, 8, 16, 8, 4, 2,
/* 79 */ 0, 14, 17, 16, 8, 4, 0, 4,
/* 80 */ 0, 14, 17, 16, 22, 21, 21, 14,
/* 81 */ 0, 4, 10, 17, 17, 31, 17, 17,
/* 82 */ 0, 15, 17, 17, 15, 17, 17, 15,
/* 83 */ 0, 14, 17, 1, 1, 1, 17, 14,
/* 84 */ 0, 7, 9, 17, 17, 17, 9, 7,
/* 85 */ 0, 31, 1, 1, 15, 1, 1, 31,
/* 86 */ 0, 31, 1, 1, 15, 1, 1, 1,
/* 87 */ 0, 14, 17, 1, 29, 17, 17, 30,
/* 88 */ 0, 17, 17, 17, 31, 17, 17, 17,
/* 89 */ 0, 14, 4, 4, 4, 4, 4, 14,
/* 90 */ 0, 28, 8, 8, 8, 8, 9, 6,
/* 91 */ 0, 17, 9, 5, 3, 5, 9, 17,
/* 92 */ 0, 1, 1, 1, 1, 1, 1, 31,
/* 93 */ 0, 17, 27, 21, 21, 17, 17, 17,
/* 94 */ 0, 17, 17, 19, 21, 25, 17, 17,
/* 95 */ 0, 14, 17, 17, 17, 17, 17, 14,
/* 96 */ 0, 15, 17, 17, 15, 1, 1, 1,
/* 97 */ 0, 14, 17, 17, 17, 21, 9, 22,
/* 98 */ 0, 15, 17, 17, 15, 5, 9, 17,
/* 99 */ 0, 14, 17, 1, 14, 16, 17, 14,
/* 100 */ 0, 31, 4, 4, 4, 4, 4, 4,
/* 101 */ 0, 17, 17, 17, 17, 17, 17, 14,
/* 102 */ 0, 17, 17, 17, 17, 17, 10, 4,
/* 103 */ 0, 17, 17, 17, 21, 21, 21, 10,
/* 104 */ 0, 17, 17, 10, 4, 10, 17, 17,
/* 105 */ 0, 17, 17, 17, 10, 4, 4, 4,
/* 106 */ 0, 31, 16, 8, 4, 2, 1, 31,
/* 107 */ 0, 14, 2, 2, 2, 2, 2, 14,
/* 108 */ 0, 0, 1, 2, 4, 8, 16, 0,
/* 109 */ 0, 14, 8, 8, 8, 8, 8, 14,
/* 110 */ 0, 4, 10, 17, 0, 0, 0, 0,
/* 111 */ 0, 0, 0, 0, 0, 0, 0, 31,
/* 112 */ 0, 2, 4, 8, 0, 0, 0, 0,
/* 113 */ 0, 0, 0, 14, 16, 30, 17, 30,
/* 114 */ 0, 1, 1, 13, 19, 17, 17, 15,
/* 115 */ 0, 0, 0, 14, 1, 1, 17, 14,
/* 116 */ 0, 16, 16, 22, 25, 17, 17, 30,
/* 117 */ 0, 0, 0, 14, 17, 31, 1, 14,
/* 118 */ 0, 12, 18, 2, 7, 2, 2, 2,
/* 119 */ 0, 0, 0, 30, 17, 30, 16, 14,
/* 120 */ 0, 1, 1, 13, 19, 17, 17, 17,
/* 121 */ 0, 4, 0, 4, 6, 4, 4, 14,
/* 122 */ 0, 8, 0, 12, 8, 8, 9, 6,
/* 123 */ 0, 1, 1, 9, 5, 3, 5, 9,
/* 124 */ 0, 6, 4, 4, 4, 4, 4, 14,
/* 125 */ 0, 0, 0, 11, 21, 21, 21, 21,
/* 126 */ 0, 0, 0, 13, 19, 17, 17, 17,
/* 127 */ 0, 0, 0, 14, 17, 17, 17, 14,
/* 128 */ 0, 0, 0, 15, 17, 15, 1, 1,
/* 129 */ 0, 0, 0, 22, 25, 30, 16, 16,
/* 130 */ 0, 0, 0, 13, 19, 1, 1, 1,
/* 131 */ 0, 0, 0, 14, 1, 14, 16, 15,
/* 132 */ 0, 2, 2, 7, 2, 2, 18, 12,
/* 133 */ 0, 0, 0, 17, 17, 17, 25, 22,
/* 134 */ 0, 0, 0, 17, 17, 17, 10, 4,
/* 135 */ 0, 0, 0, 17, 17, 21, 21, 10,
/* 136 */ 0, 0, 0, 17, 10, 4, 10, 17,
/* 137 */ 0, 0, 0, 17, 17, 30, 16, 14,
/* 138 */ 0, 0, 0, 31, 8, 4, 2, 31,
/* 139 */ 0, 8, 4, 4, 2, 4, 4, 8,
/* 140 */ 0, 4, 4, 4, 4, 4, 4, 4,
/* 141 */ 0, 2, 4, 4, 8, 4, 4, 2,
/* 142 */ 0, 0, 0, 0, 22, 9, 0, 0,
/* 143 */ 0, 4, 10, 17, 17, 17, 31, 0,
/* 144 */ 0, 31, 17, 1, 15, 17, 17, 15,
/* 145 */ 30, 20, 20, 18, 17, 31, 17, 17,
/* 146 */ 0, 21, 21, 21, 14, 21, 21, 21,
/* 147 */ 0, 15, 16, 16, 12, 16, 16, 15,
/* 148 */ 0, 17, 17, 25, 21, 19, 17, 17,
/* 149 */ 10, 4, 17, 17, 25, 21, 19, 17,
/* 150 */ 0, 30, 20, 20, 20, 20, 21, 18,
/* 151 */ 0, 31, 17, 17, 17, 17, 17, 17,
/* 152 */ 0, 17, 17, 17, 10, 4, 2, 1,
/* 153 */ 0, 17, 17, 17, 17, 17, 31, 16,
/* 154 */ 0, 17, 17, 17, 30, 16, 16, 16,
/* 155 */ 0, 0, 21, 21, 21, 21, 21, 31,
/* 156 */ 0, 21, 21, 21, 21, 21, 31, 16,
/* 157 */ 0, 3, 2, 2, 14, 18, 18, 14,
/* 158 */ 0, 17, 17, 17, 19, 21, 21, 19,
/* 159 */ 0, 14, 17, 20, 26, 16, 17, 14,
/* 160 */ 0, 0, 0, 18, 21, 9, 9, 22,
/* 161 */ 0, 4, 12, 20, 20, 4, 7, 7,
/* 162 */ 0, 31, 17, 1, 1, 1, 1, 1,
/* 163 */ 0, 0, 0, 31, 10, 10, 10, 25,
/* 164 */ 0, 31, 1, 2, 4, 2, 1, 31,
/* 165 */ 0, 0, 0, 30, 9, 9, 9, 6,
/* 166 */ 12, 20, 28, 20, 20, 23, 27, 24,
/* 167 */ 0, 0, 16, 14, 5, 4, 4, 8,
/* 168 */ 0, 4, 14, 14, 14, 31, 4, 0,
/* 169 */ 0, 14, 17, 17, 31, 17, 17, 14,
/* 170 */ 0, 0, 14, 17, 17, 17, 10, 27,
/* 171 */ 0, 12, 18, 4, 10, 17, 17, 14,
/* 172 */ 0, 0, 0, 26, 21, 11, 0, 0,
/* 173 */ 0, 0, 10, 31, 31, 31, 14, 4,
/* 174 */ 0, 0, 0, 14, 1, 6, 17, 14,
/* 175 */ 0, 14, 17, 17, 17, 17, 17, 17,
/* 176 */ 0, 27, 27, 27, 27, 27, 27, 27,
/* 177 */ 0, 4, 0, 0, 4, 4, 4, 4,
/* 178 */ 0, 4, 14, 5, 5, 21, 14, 4,
/* 179 */ 0, 12, 2, 2, 7, 2, 18, 13,
/* 180 */ 0, 0, 17, 14, 10, 14, 17, 0,
/* 181 */ 0, 17, 10, 31, 4, 31, 4, 4,
/* 182 */ 0, 4, 4, 4, 0, 4, 4, 4,
/* 183 */ 0, 12, 18, 4, 10, 4, 9, 6,
/* 184 */ 0, 8, 20, 4, 31, 4, 5, 2,
/* 185 */ 0, 31, 17, 21, 29, 21, 17, 31,
/* 186 */ 0, 14, 16, 30, 17, 30, 0, 31,
/* 187 */ 0, 0, 20, 10, 5, 10, 20, 0,
/* 188 */ 0, 9, 21, 21, 23, 21, 21, 9,
/* 189 */ 0, 30, 17, 17, 30, 20, 18, 17,
/* 190 */ 0, 31, 17, 21, 17, 25, 21, 31,
/* 191 */ 0, 4, 2, 6, 0, 0, 0, 0,
/* 192 */ 6, 9, 9, 9, 6, 0, 0, 0,
/* 193 */ 0, 4, 4, 31, 4, 4, 0, 31,
/* 194 */ 6, 9, 4, 2, 15, 0, 0, 0,
/* 195 */ 7, 8, 6, 8, 7, 0, 0, 0,
/* 196 */ 7, 9, 7, 1, 9, 29, 9, 24,
/* 197 */ 0, 17, 17, 17, 25, 23, 1, 1,
/* 198 */ 0, 30, 25, 25, 30, 24, 24, 24,
/* 199 */ 0, 0, 0, 0, 6, 6, 0, 0,
/* 200 */ 0, 0, 0, 10, 17, 21, 21, 10,
/* 201 */ 2, 3, 2, 2, 7, 0, 0, 0,
/* 202 */ 0, 14, 17, 17, 17, 14, 0, 31,
/* 203 */ 0, 0, 5, 10, 20, 10, 5, 0,
/* 204 */ 17, 9, 5, 10, 13, 10, 30, 8,
/* 205 */ 17, 9, 5, 10, 21, 16, 8, 28,
/* 206 */ 3, 2, 3, 18, 27, 20, 28, 16,
/* 207 */ 0, 4, 0, 4, 2, 1, 17, 14,
/* 208 */ 2, 4, 4, 10, 17, 31, 17, 17,
/* 209 */ 8, 4, 4, 10, 17, 31, 17, 17,
/* 210 */ 4, 10, 0, 14, 17, 31, 17, 17,
/* 211 */ 22, 9, 0, 14, 17, 31, 17, 17,
/* 212 */ 10, 0, 4, 10, 17, 31, 17, 17,
/* 213 */ 4, 10, 4, 14, 17, 31, 17, 17,
/* 214 */ 0, 28, 6, 5, 29, 7, 5, 29,
/* 215 */ 14, 17, 1, 1, 17, 14, 8, 12,
/* 216 */ 2, 4, 0, 31, 1, 15, 1, 31,
/* 217 */ 8, 4, 0, 31, 1, 15, 1, 31,
/* 218 */ 4, 10, 0, 31, 1, 15, 1, 31,
/* 219 */ 0, 10, 0, 31, 1, 15, 1, 31,
/* 220 */ 2, 4, 0, 14, 4, 4, 4, 14,
/* 221 */ 8, 4, 0, 14, 4, 4, 4, 14,
/* 222 */ 4, 10, 0, 14, 4, 4, 4, 14,
/* 223 */ 0, 10, 0, 14, 4, 4, 4, 14,
/* 224 */ 0, 14, 18, 18, 23, 18, 18, 14,
/* 225 */ 22, 9, 0, 17, 19, 21, 25, 17,
/* 226 */ 2, 4, 14, 17, 17, 17, 17, 14,
/* 227 */ 8, 4, 14, 17, 17, 17, 17, 14,
/* 228 */ 4, 10, 0, 14, 17, 17, 17, 14,
/* 229 */ 22, 9, 0, 14, 17, 17, 17, 14,
/* 230 */ 10, 0, 14, 17, 17, 17, 17, 14,
/* 231 */ 0, 0, 17, 10, 4, 10, 17, 0,
/* 232 */ 0, 14, 4, 14, 21, 14, 4, 14,
/* 233 */ 2, 4, 17, 17, 17, 17, 17, 14,
/* 234 */ 8, 4, 17, 17, 17, 17, 17, 14,
/* 235 */ 4, 10, 0, 17, 17, 17, 17, 14,
/* 236 */ 10, 0, 17, 17, 17, 17, 17, 14,
/* 237 */ 8, 4, 17, 10, 4, 4, 4, 4,
/* 238 */ 3, 2, 14, 18, 18, 14, 2, 7,
/* 239 */ 0, 12, 18, 18, 14, 18, 18, 13,
/* 240 */ 2, 4, 0, 14, 16, 30, 17, 30,
/* 241 */ 8, 4, 0, 14, 16, 30, 17, 30,
/* 242 */ 4, 10, 0, 14, 16, 30, 17, 30,
/* 243 */ 22, 9, 0, 14, 16, 30, 17, 30,
/* 244 */ 0, 10, 0, 14, 16, 30, 17, 30,
/* 245 */ 4, 10, 4, 14, 16, 30, 17, 30,
/* 246 */ 0, 0, 11, 20, 30, 5, 21, 10,
/* 247 */ 0, 0, 14, 1, 17, 14, 4, 6,
/* 248 */ 2, 4, 0, 14, 17, 31, 1, 14,
/* 249 */ 8, 4, 0, 14, 17, 31, 1, 14,
/* 250 */ 4, 10, 0, 14, 17, 31, 1, 14,
/* 251 */ 0, 10, 0, 14, 17, 31, 1, 14,
/* 252 */ 2, 4, 0, 4, 6, 4, 4, 14,
/* 253 */ 8, 4, 0, 4, 6, 4, 4, 14,
/* 254 */ 4, 10, 0, 4, 6, 4, 4, 14,
/* 255 */ 0, 10, 0, 4, 6, 4, 4, 14,
/* 256 */ 0, 5, 2, 5, 8, 30, 17, 14,
/* 257 */ 22, 9, 0, 13, 19, 17, 17, 17,
/* 258 */ 2, 4, 0, 14, 17, 17, 17, 14,
/* 259 */ 8, 4, 0, 14, 17, 17, 17, 14,
/* 260 */ 0, 4, 10, 0, 14, 17, 17, 14,
/* 261 */ 0, 22, 9, 0, 14, 17, 17, 14,
/* 262 */ 0, 10, 0, 14, 17, 17, 17, 14,
/* 263 */ 0, 0, 4, 0, 31, 0, 4, 0,
/* 264 */ 0, 8, 4, 14, 21, 14, 4, 2,
/* 265 */ 2, 4, 0, 17, 17, 17, 25, 22,
/* 266 */ 8, 4, 0, 17, 17, 17, 25, 22,
/* 267 */ 4, 10, 0, 17, 17, 17, 25, 22,
/* 268 */ 0, 10, 0, 17, 17, 17, 25, 22,
/* 269 */ 0, 8, 4, 17, 17, 30, 16, 14,
/* 270 */ 0, 6, 4, 12, 20, 12, 4, 14,
/* 271 */ 0, 10, 0, 17, 17, 30, 16, 14,
]); | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ArtistTestsQueryVariables = {
isPad: boolean;
};
export type ArtistTestsQueryResponse = {
readonly artist: {
readonly " $fragmentRefs": FragmentRefs<"Artist_artist">;
} | null;
};
export type ArtistTestsQueryRawResponse = {
readonly artist: ({
readonly internalID: string;
readonly slug: string;
readonly has_metadata: boolean | null;
readonly counts: ({
readonly artworks: number | null;
readonly partner_shows: number | null;
readonly related_artists: number | null;
readonly articles: number | null;
readonly follows: number | null;
}) | null;
readonly id: string;
readonly isFollowed: boolean | null;
readonly name: string | null;
readonly nationality: string | null;
readonly birthday: string | null;
readonly is_display_auction_link: boolean | null;
readonly bio: string | null;
readonly blurb: string | null;
readonly related: ({
readonly artists: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly id: string;
readonly href: string | null;
readonly name: string | null;
readonly counts: ({
readonly forSaleArtworks: number | null;
readonly artworks: number | null;
}) | null;
readonly image: ({
readonly url: string | null;
}) | null;
}) | null;
}) | null> | null;
}) | null;
}) | null;
readonly articles: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly id: string;
readonly thumbnail_title: string | null;
readonly href: string | null;
readonly author: ({
readonly name: string | null;
readonly id: string | null;
}) | null;
readonly thumbnail_image: ({
readonly url: string | null;
}) | null;
}) | null;
}) | null> | null;
}) | null;
readonly currentShows: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly id: string;
readonly slug: string;
readonly href: string | null;
readonly is_fair_booth: boolean | null;
readonly cover_image: ({
readonly url: string | null;
}) | null;
readonly kind: string | null;
readonly name: string | null;
readonly exhibition_period: string | null;
readonly status_update: string | null;
readonly status: string | null;
readonly partner: ({
readonly __typename: "Partner";
readonly id: string | null;
readonly name: string | null;
} | {
readonly __typename: "ExternalPartner";
readonly id: string | null;
readonly name: string | null;
} | {
readonly __typename: string | null;
readonly id: string | null;
}) | null;
readonly location: ({
readonly city: string | null;
readonly id: string | null;
}) | null;
}) | null;
}) | null> | null;
}) | null;
readonly upcomingShows: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly id: string;
readonly slug: string;
readonly href: string | null;
readonly is_fair_booth: boolean | null;
readonly cover_image: ({
readonly url: string | null;
}) | null;
readonly kind: string | null;
readonly name: string | null;
readonly exhibition_period: string | null;
readonly status_update: string | null;
readonly status: string | null;
readonly partner: ({
readonly __typename: "Partner";
readonly id: string | null;
readonly name: string | null;
} | {
readonly __typename: "ExternalPartner";
readonly id: string | null;
readonly name: string | null;
} | {
readonly __typename: string | null;
readonly id: string | null;
}) | null;
readonly location: ({
readonly city: string | null;
readonly id: string | null;
}) | null;
}) | null;
}) | null> | null;
}) | null;
readonly artworks: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly id: string;
readonly slug: string;
readonly image: ({
readonly aspectRatio: number;
readonly url: string | null;
readonly aspect_ratio: number;
}) | null;
readonly title: string | null;
readonly date: string | null;
readonly sale_message: string | null;
readonly is_biddable: boolean | null;
readonly is_acquireable: boolean | null;
readonly is_offerable: boolean | null;
readonly sale: ({
readonly is_auction: boolean | null;
readonly is_closed: boolean | null;
readonly display_timely_at: string | null;
readonly id: string | null;
}) | null;
readonly sale_artwork: ({
readonly current_bid: ({
readonly display: string | null;
}) | null;
readonly id: string | null;
}) | null;
readonly artists: ReadonlyArray<({
readonly name: string | null;
readonly id: string | null;
}) | null> | null;
readonly partner: ({
readonly name: string | null;
readonly id: string | null;
}) | null;
readonly href: string | null;
readonly __typename: "Artwork";
}) | null;
readonly cursor: string;
readonly id: string | null;
}) | null> | null;
readonly pageInfo: {
readonly hasNextPage: boolean;
readonly startCursor: string | null;
readonly endCursor: string | null;
};
readonly id: string | null;
}) | null;
readonly pastSmallShows?: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly slug: string;
readonly href: string | null;
readonly is_fair_booth: boolean | null;
readonly cover_image: ({
readonly url: string | null;
}) | null;
readonly kind: string | null;
readonly name: string | null;
readonly exhibition_period: string | null;
readonly status_update: string | null;
readonly status: string | null;
readonly partner: ({
readonly __typename: "Partner";
readonly id: string | null;
readonly name: string | null;
} | {
readonly __typename: "ExternalPartner";
readonly id: string | null;
readonly name: string | null;
} | {
readonly __typename: string | null;
readonly id: string | null;
}) | null;
readonly location: ({
readonly city: string | null;
readonly id: string | null;
}) | null;
readonly id: string | null;
}) | null;
}) | null> | null;
}) | null;
readonly pastLargeShows?: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly id: string;
readonly slug: string;
readonly href: string | null;
readonly is_fair_booth: boolean | null;
readonly cover_image: ({
readonly url: string | null;
}) | null;
readonly kind: string | null;
readonly name: string | null;
readonly exhibition_period: string | null;
readonly status_update: string | null;
readonly status: string | null;
readonly partner: ({
readonly __typename: "Partner";
readonly id: string | null;
readonly name: string | null;
} | {
readonly __typename: "ExternalPartner";
readonly id: string | null;
readonly name: string | null;
} | {
readonly __typename: string | null;
readonly id: string | null;
}) | null;
readonly location: ({
readonly city: string | null;
readonly id: string | null;
}) | null;
}) | null;
}) | null> | null;
}) | null;
}) | null;
};
export type ArtistTestsQuery = {
readonly response: ArtistTestsQueryResponse;
readonly variables: ArtistTestsQueryVariables;
readonly rawResponse: ArtistTestsQueryRawResponse;
};
/*
query ArtistTestsQuery(
$isPad: Boolean!
) {
artist(id: "andy-warhol") {
...Artist_artist
id
}
}
fragment Artist_artist on Artist {
internalID
slug
has_metadata: hasMetadata
counts {
artworks
partner_shows: partnerShows
related_artists: relatedArtists
articles
}
...ArtistHeader_artist
...ArtistAbout_artist
...ArtistShows_artist
...ArtistArtworks_artist
}
fragment ArtistHeader_artist on Artist {
id
internalID
slug
isFollowed
name
nationality
birthday
counts {
follows
}
}
fragment ArtistAbout_artist on Artist {
has_metadata: hasMetadata
is_display_auction_link: isDisplayAuctionLink
slug
...Biography_artist
related {
artists: artistsConnection(first: 16) {
edges {
node {
...RelatedArtists_artists
id
}
}
}
}
articles: articlesConnection(first: 10) {
edges {
node {
...Articles_articles
id
}
}
}
}
fragment ArtistShows_artist on Artist {
currentShows: showsConnection(status: "running", first: 10) {
edges {
node {
...VariableSizeShowsList_shows
id
}
}
}
upcomingShows: showsConnection(status: "upcoming", first: 10) {
edges {
node {
...VariableSizeShowsList_shows
id
}
}
}
pastSmallShows: showsConnection(status: "closed", first: 20) @skip(if: $isPad) {
edges {
node {
...SmallList_shows
id
}
}
}
pastLargeShows: showsConnection(status: "closed", first: 20) @include(if: $isPad) {
edges {
node {
...VariableSizeShowsList_shows
id
}
}
}
}
fragment ArtistArtworks_artist on Artist {
id
artworks: filterArtworksConnection(first: 10, sort: "-decayed_merch", aggregations: [TOTAL]) {
edges {
node {
id
__typename
}
cursor
}
...InfiniteScrollArtworksGrid_connection
pageInfo {
endCursor
hasNextPage
}
id
}
}
fragment InfiniteScrollArtworksGrid_connection on ArtworkConnectionInterface {
pageInfo {
hasNextPage
startCursor
endCursor
}
edges {
__typename
node {
slug
id
image {
aspectRatio
}
...ArtworkGridItem_artwork
}
... on Node {
id
}
}
}
fragment ArtworkGridItem_artwork on Artwork {
title
date
sale_message: saleMessage
is_biddable: isBiddable
is_acquireable: isAcquireable
is_offerable: isOfferable
slug
sale {
is_auction: isAuction
is_closed: isClosed
display_timely_at: displayTimelyAt
id
}
sale_artwork: saleArtwork {
current_bid: currentBid {
display
}
id
}
image {
url(version: "large")
aspect_ratio: aspectRatio
}
artists(shallow: true) {
name
id
}
partner {
name
id
}
href
}
fragment VariableSizeShowsList_shows on Show {
id
...ArtistShow_show
}
fragment SmallList_shows on Show {
...ArtistShow_show
}
fragment ArtistShow_show on Show {
slug
href
is_fair_booth: isFairBooth
cover_image: coverImage {
url(version: "large")
}
...Metadata_show
}
fragment Metadata_show on Show {
kind
name
exhibition_period: exhibitionPeriod
status_update: statusUpdate
status
partner {
__typename
... on Partner {
name
}
... on ExternalPartner {
name
id
}
... on Node {
id
}
}
location {
city
id
}
}
fragment Biography_artist on Artist {
bio
blurb
}
fragment RelatedArtists_artists on Artist {
id
...RelatedArtist_artist
}
fragment Articles_articles on Article {
id
...Article_article
}
fragment Article_article on Article {
thumbnail_title: thumbnailTitle
href
author {
name
id
}
thumbnail_image: thumbnailImage {
url(version: "large")
}
}
fragment RelatedArtist_artist on Artist {
href
name
counts {
forSaleArtworks
artworks
}
image {
url(version: "large")
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"kind": "LocalArgument",
"name": "isPad",
"type": "Boolean!",
"defaultValue": null
}
],
v1 = [
{
"kind": "Literal",
"name": "id",
"value": "andy-warhol"
}
],
v2 = {
"kind": "ScalarField",
"alias": null,
"name": "slug",
"args": null,
"storageKey": null
},
v3 = {
"kind": "ScalarField",
"alias": null,
"name": "artworks",
"args": null,
"storageKey": null
},
v4 = {
"kind": "ScalarField",
"alias": null,
"name": "id",
"args": null,
"storageKey": null
},
v5 = {
"kind": "ScalarField",
"alias": null,
"name": "name",
"args": null,
"storageKey": null
},
v6 = {
"kind": "ScalarField",
"alias": null,
"name": "href",
"args": null,
"storageKey": null
},
v7 = {
"kind": "ScalarField",
"alias": null,
"name": "url",
"args": [
{
"kind": "Literal",
"name": "version",
"value": "large"
}
],
"storageKey": "url(version:\"large\")"
},
v8 = [
(v7/*: any*/)
],
v9 = {
"kind": "Literal",
"name": "first",
"value": 10
},
v10 = [
(v5/*: any*/),
(v4/*: any*/)
],
v11 = {
"kind": "ScalarField",
"alias": "is_fair_booth",
"name": "isFairBooth",
"args": null,
"storageKey": null
},
v12 = {
"kind": "LinkedField",
"alias": "cover_image",
"name": "coverImage",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": (v8/*: any*/)
},
v13 = {
"kind": "ScalarField",
"alias": null,
"name": "kind",
"args": null,
"storageKey": null
},
v14 = {
"kind": "ScalarField",
"alias": "exhibition_period",
"name": "exhibitionPeriod",
"args": null,
"storageKey": null
},
v15 = {
"kind": "ScalarField",
"alias": "status_update",
"name": "statusUpdate",
"args": null,
"storageKey": null
},
v16 = {
"kind": "ScalarField",
"alias": null,
"name": "status",
"args": null,
"storageKey": null
},
v17 = {
"kind": "ScalarField",
"alias": null,
"name": "__typename",
"args": null,
"storageKey": null
},
v18 = [
(v5/*: any*/)
],
v19 = {
"kind": "LinkedField",
"alias": null,
"name": "partner",
"storageKey": null,
"args": null,
"concreteType": null,
"plural": false,
"selections": [
(v17/*: any*/),
(v4/*: any*/),
{
"kind": "InlineFragment",
"type": "Partner",
"selections": (v18/*: any*/)
},
{
"kind": "InlineFragment",
"type": "ExternalPartner",
"selections": (v18/*: any*/)
}
]
},
v20 = {
"kind": "LinkedField",
"alias": null,
"name": "location",
"storageKey": null,
"args": null,
"concreteType": "Location",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "city",
"args": null,
"storageKey": null
},
(v4/*: any*/)
]
},
v21 = [
{
"kind": "LinkedField",
"alias": null,
"name": "edges",
"storageKey": null,
"args": null,
"concreteType": "ShowEdge",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "node",
"storageKey": null,
"args": null,
"concreteType": "Show",
"plural": false,
"selections": [
(v4/*: any*/),
(v2/*: any*/),
(v6/*: any*/),
(v11/*: any*/),
(v12/*: any*/),
(v13/*: any*/),
(v5/*: any*/),
(v14/*: any*/),
(v15/*: any*/),
(v16/*: any*/),
(v19/*: any*/),
(v20/*: any*/)
]
}
]
}
],
v22 = [
{
"kind": "Literal",
"name": "aggregations",
"value": [
"TOTAL"
]
},
(v9/*: any*/),
{
"kind": "Literal",
"name": "sort",
"value": "-decayed_merch"
}
],
v23 = [
{
"kind": "Literal",
"name": "first",
"value": 20
},
{
"kind": "Literal",
"name": "status",
"value": "closed"
}
];
return {
"kind": "Request",
"fragment": {
"kind": "Fragment",
"name": "ArtistTestsQuery",
"type": "Query",
"metadata": null,
"argumentDefinitions": (v0/*: any*/),
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "artist",
"storageKey": "artist(id:\"andy-warhol\")",
"args": (v1/*: any*/),
"concreteType": "Artist",
"plural": false,
"selections": [
{
"kind": "FragmentSpread",
"name": "Artist_artist",
"args": null
}
]
}
]
},
"operation": {
"kind": "Operation",
"name": "ArtistTestsQuery",
"argumentDefinitions": (v0/*: any*/),
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "artist",
"storageKey": "artist(id:\"andy-warhol\")",
"args": (v1/*: any*/),
"concreteType": "Artist",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "internalID",
"args": null,
"storageKey": null
},
(v2/*: any*/),
{
"kind": "ScalarField",
"alias": "has_metadata",
"name": "hasMetadata",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "counts",
"storageKey": null,
"args": null,
"concreteType": "ArtistCounts",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "ScalarField",
"alias": "partner_shows",
"name": "partnerShows",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "related_artists",
"name": "relatedArtists",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "articles",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "follows",
"args": null,
"storageKey": null
}
]
},
(v4/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "isFollowed",
"args": null,
"storageKey": null
},
(v5/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "nationality",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "birthday",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "is_display_auction_link",
"name": "isDisplayAuctionLink",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "bio",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "blurb",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "related",
"storageKey": null,
"args": null,
"concreteType": "ArtistRelatedData",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": "artists",
"name": "artistsConnection",
"storageKey": "artistsConnection(first:16)",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 16
}
],
"concreteType": "ArtistConnection",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "edges",
"storageKey": null,
"args": null,
"concreteType": "ArtistEdge",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "node",
"storageKey": null,
"args": null,
"concreteType": "Artist",
"plural": false,
"selections": [
(v4/*: any*/),
(v6/*: any*/),
(v5/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "counts",
"storageKey": null,
"args": null,
"concreteType": "ArtistCounts",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "forSaleArtworks",
"args": null,
"storageKey": null
},
(v3/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "image",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": (v8/*: any*/)
}
]
}
]
}
]
}
]
},
{
"kind": "LinkedField",
"alias": "articles",
"name": "articlesConnection",
"storageKey": "articlesConnection(first:10)",
"args": [
(v9/*: any*/)
],
"concreteType": "ArticleConnection",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "edges",
"storageKey": null,
"args": null,
"concreteType": "ArticleEdge",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "node",
"storageKey": null,
"args": null,
"concreteType": "Article",
"plural": false,
"selections": [
(v4/*: any*/),
{
"kind": "ScalarField",
"alias": "thumbnail_title",
"name": "thumbnailTitle",
"args": null,
"storageKey": null
},
(v6/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "author",
"storageKey": null,
"args": null,
"concreteType": "Author",
"plural": false,
"selections": (v10/*: any*/)
},
{
"kind": "LinkedField",
"alias": "thumbnail_image",
"name": "thumbnailImage",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": (v8/*: any*/)
}
]
}
]
}
]
},
{
"kind": "LinkedField",
"alias": "currentShows",
"name": "showsConnection",
"storageKey": "showsConnection(first:10,status:\"running\")",
"args": [
(v9/*: any*/),
{
"kind": "Literal",
"name": "status",
"value": "running"
}
],
"concreteType": "ShowConnection",
"plural": false,
"selections": (v21/*: any*/)
},
{
"kind": "LinkedField",
"alias": "upcomingShows",
"name": "showsConnection",
"storageKey": "showsConnection(first:10,status:\"upcoming\")",
"args": [
(v9/*: any*/),
{
"kind": "Literal",
"name": "status",
"value": "upcoming"
}
],
"concreteType": "ShowConnection",
"plural": false,
"selections": (v21/*: any*/)
},
{
"kind": "LinkedField",
"alias": "artworks",
"name": "filterArtworksConnection",
"storageKey": "filterArtworksConnection(aggregations:[\"TOTAL\"],first:10,sort:\"-decayed_merch\")",
"args": (v22/*: any*/),
"concreteType": "FilterArtworksConnection",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "edges",
"storageKey": null,
"args": null,
"concreteType": "FilterArtworksEdge",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "node",
"storageKey": null,
"args": null,
"concreteType": "Artwork",
"plural": false,
"selections": [
(v4/*: any*/),
(v2/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "image",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "aspectRatio",
"args": null,
"storageKey": null
},
(v7/*: any*/),
{
"kind": "ScalarField",
"alias": "aspect_ratio",
"name": "aspectRatio",
"args": null,
"storageKey": null
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "title",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "date",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "sale_message",
"name": "saleMessage",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "is_biddable",
"name": "isBiddable",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "is_acquireable",
"name": "isAcquireable",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "is_offerable",
"name": "isOfferable",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "sale",
"storageKey": null,
"args": null,
"concreteType": "Sale",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": "is_auction",
"name": "isAuction",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "is_closed",
"name": "isClosed",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "display_timely_at",
"name": "displayTimelyAt",
"args": null,
"storageKey": null
},
(v4/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": "sale_artwork",
"name": "saleArtwork",
"storageKey": null,
"args": null,
"concreteType": "SaleArtwork",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": "current_bid",
"name": "currentBid",
"storageKey": null,
"args": null,
"concreteType": "SaleArtworkCurrentBid",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "display",
"args": null,
"storageKey": null
}
]
},
(v4/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "artists",
"storageKey": "artists(shallow:true)",
"args": [
{
"kind": "Literal",
"name": "shallow",
"value": true
}
],
"concreteType": "Artist",
"plural": true,
"selections": (v10/*: any*/)
},
{
"kind": "LinkedField",
"alias": null,
"name": "partner",
"storageKey": null,
"args": null,
"concreteType": "Partner",
"plural": false,
"selections": (v10/*: any*/)
},
(v6/*: any*/),
(v17/*: any*/)
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "cursor",
"args": null,
"storageKey": null
},
(v4/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "pageInfo",
"storageKey": null,
"args": null,
"concreteType": "PageInfo",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "hasNextPage",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "startCursor",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "endCursor",
"args": null,
"storageKey": null
}
]
},
(v4/*: any*/)
]
},
{
"kind": "LinkedHandle",
"alias": "artworks",
"name": "filterArtworksConnection",
"args": (v22/*: any*/),
"handle": "connection",
"key": "ArtistArtworksGrid_artworks",
"filters": [
"sort",
"aggregations"
]
},
{
"kind": "Condition",
"passingValue": false,
"condition": "isPad",
"selections": [
{
"kind": "LinkedField",
"alias": "pastSmallShows",
"name": "showsConnection",
"storageKey": "showsConnection(first:20,status:\"closed\")",
"args": (v23/*: any*/),
"concreteType": "ShowConnection",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "edges",
"storageKey": null,
"args": null,
"concreteType": "ShowEdge",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "node",
"storageKey": null,
"args": null,
"concreteType": "Show",
"plural": false,
"selections": [
(v2/*: any*/),
(v6/*: any*/),
(v11/*: any*/),
(v12/*: any*/),
(v13/*: any*/),
(v5/*: any*/),
(v14/*: any*/),
(v15/*: any*/),
(v16/*: any*/),
(v19/*: any*/),
(v20/*: any*/),
(v4/*: any*/)
]
}
]
}
]
}
]
},
{
"kind": "Condition",
"passingValue": true,
"condition": "isPad",
"selections": [
{
"kind": "LinkedField",
"alias": "pastLargeShows",
"name": "showsConnection",
"storageKey": "showsConnection(first:20,status:\"closed\")",
"args": (v23/*: any*/),
"concreteType": "ShowConnection",
"plural": false,
"selections": (v21/*: any*/)
}
]
}
]
}
]
},
"params": {
"operationKind": "query",
"name": "ArtistTestsQuery",
"id": "7d7098d94a1abc48285b0aa2b68cbe58",
"text": null,
"metadata": {}
}
};
})();
(node as any).hash = '845b9534ea8b9c3b6feb24cf11c76504';
export default node; | the_stack |
export { folder, file, shell, watch, delay } from './task/global/index'
// --------------------------------------------------------------------------
// Hammer
// --------------------------------------------------------------------------
import { Cache } from './cache/index'
import { Build } from './build/index'
import { Asset, resolve } from './resolve/index'
import { watch } from './watch/index'
import { serve } from './serve/index'
import { run } from './run/index'
import { monitor } from './monitor/index'
import { task } from './task/index'
import { Dispose } from './dispose'
import * as path from 'path'
import * as fs from 'fs'
import * as options from './options/index'
class Hammer implements Dispose {
private readonly disposables: Dispose[] = []
constructor(private readonly options: options.Options) { }
// -------------------------------------------------------------
// Build
// -------------------------------------------------------------
private async build(options: options.BuildOptions): Promise<void> {
const cache = new Cache<Asset>({
key: 'sourcePath',
timestamp: 'timestamp'
})
const builder = new Build({
platform: options.platform,
minify: options.minify,
sourcemap: options.sourcemap,
target: options.target,
external: options.external,
esm: options.esm,
bundle: true,
watch: false
})
const assets = [...resolve(options.sourcePaths, options.dist)]
const actions = cache.update(assets)
await builder.update(actions)
this.disposables.push(builder)
}
// -------------------------------------------------------------
// Watch
// -------------------------------------------------------------
private async watch(options: options.WatchOptions): Promise<void> {
const cache = new Cache<Asset>({
key: 'sourcePath',
timestamp: 'timestamp'
})
const builder = new Build({
platform: 'browser',
minify: options.minify,
sourcemap: options.sourcemap,
target: options.target,
external: options.external,
esm: options.esm,
bundle: true,
watch: true
})
const assets = [...resolve(options.sourcePaths, options.dist)]
const actions = cache.update(assets)
await builder.update(actions)
const watcher = watch([...options.sourcePaths, ...assets.map(asset => asset.sourcePath)])
this.disposables.push(watcher)
this.disposables.push(builder)
for await (const _ of watcher) {
const assets = [...resolve(options.sourcePaths, options.dist)]
watcher.add(assets.map(asset => asset.sourcePath))
const actions = cache.update(assets)
await builder.update(actions)
}
}
// -------------------------------------------------------------
// Serve
// -------------------------------------------------------------
private async serve(options: options.ServeOptions): Promise<void> {
const cache = new Cache<Asset>({
key: 'sourcePath',
timestamp: 'timestamp'
})
const builder = new Build({
platform: 'browser',
minify: options.minify,
sourcemap: options.sourcemap,
target: options.target,
external: options.external,
esm: options.esm,
bundle: true,
watch: true
})
const assets = [...resolve(options.sourcePaths, options.dist)]
const actions = cache.update(assets)
await builder.update(actions)
const watcher = watch([...options.sourcePaths, ...assets.map(asset => asset.sourcePath)])
const server = serve(options.dist, options.port)
this.disposables.push(watcher)
this.disposables.push(builder)
this.disposables.push(server)
for await (const _ of watcher) {
const assets = [...resolve(options.sourcePaths, options.dist)]
watcher.add(assets.map(asset => asset.sourcePath))
const actions = cache.update(assets)
await builder.update(actions)
}
}
// -------------------------------------------------------------
// Run
// -------------------------------------------------------------
private async run(options: options.RunOptions): Promise<void> {
const cache = new Cache<Asset>({
key: 'sourcePath',
timestamp: 'timestamp'
})
const builder = new Build({
platform: 'node',
minify: options.minify,
sourcemap: options.sourcemap,
target: options.target,
external: options.external,
esm: options.esm,
bundle: true,
watch: true
})
const assets = [...resolve([options.sourcePath], options.dist)]
const actions = cache.update(assets)
await builder.update(actions)
const watcher = watch([options.sourcePath, ...assets.map(asset => asset.sourcePath)])
const process = run(options.entryPath, options.args)
this.disposables.push(watcher)
this.disposables.push(builder)
this.disposables.push(process)
for await (const _ of watcher) {
const assets = [...resolve([options.sourcePath], options.dist)]
watcher.add(assets.map(asset => asset.sourcePath))
const actions = cache.update(assets)
await builder.update(actions)
}
}
// -------------------------------------------------------------
// Monitor
// -------------------------------------------------------------
private async monitor(options: options.MonitorOptions): Promise<void> {
await monitor(options.sourcePaths, options.arguments)
}
// -------------------------------------------------------------
// Task
// -------------------------------------------------------------
private async task(options: options.TaskOptions): Promise<void> {
await task(options.sourcePath, options.name, options.arguments)
}
private getVersion(): string {
try {
const packagePath = path.join(__dirname, 'package.json')
if (!fs.existsSync(packagePath)) throw Error(`Cannot find package.json at ${packagePath}`)
const contents = fs.readFileSync(packagePath, 'utf-8')
const package_json = JSON.parse(contents)
return package_json.version
} catch (error) {
if(error instanceof Error) {
console.log(error.message)
} else {
console.log(error)
}
return 'Unknown'
}
}
private async version(options: options.VersionOptions): Promise<void> {
console.log(`Hammer: ${this.getVersion()}`)
}
private async help(options: options.HelpOptions): Promise<void> {
const green = '\x1b[90m'
const blue = '\x1b[36m'
const esc = `\x1b[0m`
console.log([
`${blue}Version${esc}: ${this.getVersion()}`,
``,
`${blue}Commands${esc}:`,
``,
` $ hammer ${green}run${esc} <script path> ${blue}<...options>${esc}`,
` $ hammer ${green}build${esc} <file or folder> ${blue}<...options>${esc}`,
` $ hammer ${green}watch${esc} <file or folder> ${blue}<...options>${esc}`,
` $ hammer ${green}serve${esc} <file or folder> ${blue}<...options>${esc}`,
` $ hammer ${green}monitor${esc} <file or folder> ${blue}<shell command>${esc}`,
` $ hammer ${green}task${esc} <name> ${blue}<...arguments>${esc}`,
` $ hammer ${green}version${esc}`,
` $ hammer ${green}help${esc}`,
``,
`${blue}Options${esc}:`,
``,
` ${blue}--target${esc} targets The es build targets.`,
` ${blue}--platform${esc} platform The target platform.`,
` ${blue}--dist${esc} directory The target directory.`,
` ${blue}--port${esc} port The port to listen on.`,
` ${blue}--external${esc} packages Omits external packages.`,
` ${blue}--esm${esc} Use esm module target.`,
` ${blue}--minify${esc} Minifies the output.`,
` ${blue}--sourcemap${esc} Generate sourcemaps.`,
``,
].join(`\n`))
if (options.message) {
console.log([options.message, ''].join('\n'))
}
}
public async execute() {
const start = Date.now()
const blue = '\x1b[36m'
const yellow = '\x1b[33m'
const esc = `\x1b[0m`
switch (this.options.type) {
case 'build': console.log(`${blue}[build]${esc}: ${this.options.sourcePaths.join(' ')}`); break
case 'watch': console.log(`${blue}[watch]${esc}: ${this.options.sourcePaths.join(' ')}`); break
case 'serve': console.log(`${blue}[serve]${esc}: ${this.options.dist} on ${blue}${this.options.port}${esc}`); break
case 'start': console.log(`${blue}[start]${esc}: ${this.options.entryPath} ${this.options.args.join(' ')}`); break
case 'monitor': console.log(`${blue}[monitor]${esc}: ${this.options.sourcePaths.join(' ')}`); break
case 'task': console.log(`${blue}[task]${esc}: ${this.options.name} ${this.options.arguments.join(' ')}`); break
}
switch (this.options.type) {
case 'build': await this.build(this.options); break;
case 'watch': await this.watch(this.options); break;
case 'serve': await this.serve(this.options); break;
case 'start': await this.run(this.options); break;
case 'monitor': await this.monitor(this.options); break;
case 'task': await this.task(this.options); break;
case 'help': await this.help(this.options); break;
case 'version': await this.version(this.options); break;
}
console.log(`${blue}Done${esc}: ${Date.now() - start}ms`)
}
public dispose() {
for (const disposable of this.disposables) {
disposable.dispose()
}
}
}
export function hammer(options: options.Options) {
return new Hammer(options)
} | the_stack |
import { LitElement, html, customElement, property, TemplateResult, CSSResult, css, internalProperty } from 'lit-element';
import { HomeAssistant, LovelaceCardEditor, ActionConfig, LovelaceCardConfig } from 'custom-card-helpers';
import '../types.js';
import { TeslaStyleSolarPowerCardConfig } from '../models/TeslaStyleSolarPowerCardConfig.js';
const options = {
entities: {
icon: 'tune',
name: 'Entities',
secondary: 'Entities for card to make sense, none are required but you should have a few.',
show: false,
},
actions: {
icon: 'gesture-tap-hold',
name: 'Actions',
secondary: 'Perform actions based on tapping/clicking',
show: false,
options: {
tap: {
icon: 'gesture-tap',
name: 'Tap',
secondary: 'Set the action to perform on tap',
show: false,
},
hold: {
icon: 'gesture-tap-hold',
name: 'Hold',
secondary: 'Set the action to perform on hold',
show: false,
},
double_tap: {
icon: 'gesture-double-tap',
name: 'Double Tap',
secondary: 'Set the action to perform on double tap',
show: false,
},
},
},
appearance: {
icon: 'palette',
name: 'Appearance',
secondary: 'Customize the name, icon, etc',
show: false,
},
};
@customElement('tesla-style-solar-power-card-editor')
export class TeslaStyleSolarPowerCardEditor extends LitElement implements LovelaceCardEditor {
@property({ attribute: false }) public hass?: HomeAssistant;
@internalProperty() private _config?: LovelaceCardConfig;
@internalProperty() private _toggle?: boolean;
@internalProperty() private _helpers?: any;
private _initialized = false;
private _entityMap = new Map();
public setConfig(config: LovelaceCardConfig): void {
this._config = config;
// this._fillLineEntityMap();
this.loadCardHelpers();
}
protected shouldUpdate(): boolean {
if (!this._initialized) {
this._initialize();
}
return true;
}
get name(): string {
return this._config?.name || '';
}
// entities
get home_entity(): string {
return this._config?.home_entity || '';
}
get battery_entity(): string {
return this._config?.battery_consumption_entity || '';
}
get grid_entity(): string {
return this._config?.grid_entity || '';
}
get generation_entity(): string {
return this._config?.generation_entity || '';
}
get home_extra_entity(): string {
return this._config?.home_entity || '';
}
get battery_extra_entity(): string {
return this._config?.battery_consumption_entity || '';
}
get grid_extra_entity(): string {
return this._config?.grid_entity || '';
}
get generation_extra_entity(): string {
return this._config?.generation_entity || '';
}
get grid_to_house_entity(): string {
return this._config?.grid_to_house_entity || '';
}
get grid_to_battery_entity(): string {
return this._config?.grid_to_battery_entity || '';
}
get battery_to_grid_in_entity(): string {
return this._config?.battery_to_grid_entity || '';
}
get generation_to_grid_entity(): string {
return this._config?.grid_to_battery_entity || '';
}
get generation_to_house_entity(): string {
return this._config?.generation_entity || '';
}
get generation_to_battery_entity(): string {
return this._config?.generation_yield_entity || '';
}
get appliance1_consumption_entity(): string {
return this._config?.appliance1_consumption_entity || '';
}
get appliance1_extra_entity(): string {
return this._config?.appliance1_state_entity || '';
}
get appliance2_consumption_entity(): string {
return this._config?.appliance2_consumption_entity || '';
}
get appliance2_extra_entity(): string {
return this._config?.appliance2_state_entity || '';
}
get show_w_not_kw(): boolean {
return this._config?.show_w_not_kw || false;
}
get show_warning(): boolean {
return this._config?.show_warning || false;
}
get show_error(): boolean {
return this._config?.show_error || false;
}
get hide_inactive_lines(): boolean {
return this._config?.hide_inactive_lines || false;
}
get tap_action(): ActionConfig {
return this._config?.tap_action || { action: 'more-info' };
}
get hold_action(): ActionConfig {
return this._config?.hold_action || { action: 'none' };
}
get double_tap_action(): ActionConfig {
return this._config?.double_tap_action || { action: 'none' };
}
protected render(): TemplateResult | void {
if (!this.hass || !this._helpers) {
return html``;
}
// The climate more-info has ha-switch and paper-dropdown-menu elements that are lazy loaded unless explicitly done here
this._helpers.importMoreInfoControl('climate');
return html`
<div class="card-config">
<paper-input
.label="${this.hass.localize('ui.panel.lovelace.editor.card.generic.title')} (${this.hass.localize(
'ui.panel.lovelace.editor.card.config.optional'
)})"
.value=${this.name}
.configValue=${'name'}
@value-changed=${this._valueChanged}
></paper-input>
<div class="option" @click=${this._toggleOption} .option=${'entities'}>
<div class="row">
<ha-icon .icon=${`mdi:${options.entities.icon}`}></ha-icon>
<div class="title">${options.entities.name}</div>
</div>
<div class="secondary">${options.entities.secondary}</div>
</div>
${options.entities.show
? html`<div class="values">
${Array.from(this._entityMap).map(entityArr => {
const entityName: keyof TeslaStyleSolarPowerCardConfig = entityArr[0];
const entityFunction = this[`_${entityName}`];
return html`
<ha-entity-picker
label="${entityName}"
@value-changed=${this._valueChanged}
.hass="${this.hass}"
.value="${entityFunction}"
.configValue=${entityName}
@change="${this._valueChanged}"
allow-custom-entity
>
</ha-entity-picker>
`;
})}
</div>`
: ''}
<div class="option" @click=${this._toggleOption} .option=${'actions'}>
<div class="row">
<ha-icon .icon=${`mdi:${options.actions.icon}`}></ha-icon>
<div class="title">${options.actions.name}</div>
</div>
<div class="secondary">${options.actions.secondary}</div>
</div>
${options.actions.show
? html`
<div class="values">
<div class="option" @click=${this._toggleAction} .option=${'tap'}>
<div class="row">
<ha-icon .icon=${`mdi:${options.actions.options.tap.icon}`}></ha-icon>
<div class="title">${options.actions.options.tap.name}</div>
</div>
<div class="secondary">${options.actions.options.tap.secondary}</div>
</div>
${options.actions.options.tap.show
? html`
<div class="values">
<paper-item>Action Editors Coming Soon</paper-item>
</div>
`
: ''}
<div class="option" @click=${this._toggleAction} .option=${'hold'}>
<div class="row">
<ha-icon .icon=${`mdi:${options.actions.options.hold.icon}`}></ha-icon>
<div class="title">${options.actions.options.hold.name}</div>
</div>
<div class="secondary">${options.actions.options.hold.secondary}</div>
</div>
${options.actions.options.hold.show
? html`
<div class="values">
<paper-item>Action Editors Coming Soon</paper-item>
</div>
`
: ''}
<div class="option" @click=${this._toggleAction} .option=${'double_tap'}>
<div class="row">
<ha-icon .icon=${`mdi:${options.actions.options.double_tap.icon}`}></ha-icon>
<div class="title">${options.actions.options.double_tap.name}</div>
</div>
<div class="secondary">${options.actions.options.double_tap.secondary}</div>
</div>
${options.actions.options.double_tap.show
? html`
<div class="values">
<paper-item>Action Editors Coming Soon</paper-item>
</div>
`
: ''}
</div>
`
: ''}
<div class="option" @click=${this._toggleOption} .option=${'appearance'}>
<div class="row">
<ha-icon .icon=${`mdi:${options.appearance.icon}`}></ha-icon>
<div class="title">${options.appearance.name}</div>
</div>
<div class="secondary">${options.appearance.secondary}</div>
</div>
${options.appearance.show
? html`
<div class="values">
<br />
<ha-formfield .label=${`Toggle warning ${this.show_warning ? 'off' : 'on'}`}>
<ha-switch
.checked=${this.show_warning !== false}
.configValue=${'show_warning'}
@change=${this._valueChanged}
></ha-switch>
</ha-formfield>
<ha-formfield .label=${`Toggle error ${this.show_error ? 'off' : 'on'}`}>
<ha-switch .checked=${this.show_error !== false} .configValue=${'show_error'} @change=${this._valueChanged}></ha-switch>
</ha-formfield>
<ha-formfield .label=${`Toggle W instead of kW ${this.show_w_not_kw ? 'off' : 'on'}`}>
<ha-switch
.checked=${this.show_w_not_kw !== false}
.configValue=${'show_w_not_kw'}
@change=${this._valueChanged}
></ha-switch>
</ha-formfield>
<ha-formfield .label=${`Toggle hiding inactive power lines ${this.hide_inactive_lines ? 'off' : 'on'}`}>
<ha-switch
.checked=${this.hide_inactive_lines !== false}
.configValue=${'hide_inactive_lines'}
@change=${this._valueChanged}
></ha-switch>
</ha-formfield>
</div>
`
: ''}
</div>
`;
}
private _initialize(): void {
if (this.hass === undefined) return;
if (this._config === undefined) return;
if (this._helpers === undefined) return;
this._initialized = true;
}
private async loadCardHelpers(): Promise<void> {
this._helpers = await (window as any).loadCardHelpers();
}
private _toggleAction(ev: any): void {
this._toggleThing(ev, options.actions.options);
}
private _toggleOption(ev: any): void {
this._toggleThing(ev, options);
}
private _toggleThing(ev: any, optionList: any): void {
const show = !optionList[ev.target.option].show;
for (const [key] of Object.entries(optionList)) {
optionList[key].show = false;
}
optionList[ev.target.option].show = show;
this._toggle = !this._toggle;
}
private _valueChanged(ev: any): void {
if (!this._config || !this.hass) {
return;
}
const { target } = ev;
if (this[`_${target.configValue}`] === target.value) {
return;
}
if (target.configValue) {
if (target.value === '') {
delete this._config[target.configValue];
} else {
this._config = {
...this._config,
[target.configValue]: target.checked !== undefined ? target.checked : target.value,
};
}
}
// fireEvent(this, 'config-changed', { config: this._config }); // this is breaking the card built when terser is activated
}
private _fillLineEntityMap() {
if (this._config !== undefined) {
this._entityMap.set('home_entity', this._config.home_entity);
this._entityMap.set('grid_entity', this._config.grid_entity);
this._entityMap.set('generation_entity', this._config.generation_entity);
this._entityMap.set('battery_entity', this._config.battery_entity);
this._entityMap.set('grid_to_house_entity', this._config.grid_to_battery_entity);
this._entityMap.set('grid_to_battery_entity', this._config.grid_to_battery_entity);
this._entityMap.set('generation_to_grid_entity', this._config.grid_feed_in_entity);
this._entityMap.set('generation_to_house_entity', this._config.generation_consumption_entity);
this._entityMap.set('generation_to_battery_entity', this._config.generation_to_battery_entity);
this._entityMap.set('battery_to_grid_entity', this._config.generation_consumption_entity);
this._entityMap.set('battery_to_house_entity', this._config.generation_to_battery_entity);
this._entityMap.set('battery_extra_entity', this._config.battery_extra_entity);
this._entityMap.set('appliance1_consumption_entity', this._config.appliance1_entity);
this._entityMap.set('appliance1_state_entity', this._config.appliance1_state_entity);
this._entityMap.set('appliance2_consumption_entity', this._config.appliance2_entity);
this._entityMap.set('appliance2_state_entity', this._config.appliance2_state_entity);
}
}
private _fillIconEntityMap() {
if (this._config !== undefined) {
this._entityMap.set('grid_entity', this._config.grid_entity);
this._entityMap.set('home_entity', this._config.home_entity);
this._entityMap.set('generation_entity', this._config.generation_entity);
this._entityMap.set('battery_entity', this._config.battery_entity);
this._entityMap.set('appliance1_entity', this._config.appliance1_entity);
this._entityMap.set('appliance2_entity', this._config.appliance2_entity);
}
}
static get styles(): CSSResult {
return css`
.option {
padding: 4px 0px;
cursor: pointer;
}
.row {
display: flex;
margin-bottom: -14px;
pointer-events: none;
}
.title {
padding-left: 16px;
margin-top: -6px;
pointer-events: none;
}
.secondary {
padding-left: 40px;
color: var(--secondary-text-color);
pointer-events: none;
}
.values {
padding-left: 16px;
background: var(--secondary-background-color);
display: grid;
}
ha-formfield {
padding-bottom: 8px;
}
`;
}
} | the_stack |
import { Injectable, Type } from '@angular/core';
import { CoreDelegate, CoreDelegateHandler } from '@classes/delegate';
import { AddonModAssignDefaultSubmissionHandler } from './handlers/default-submission';
import { AddonModAssignAssign, AddonModAssignSubmission, AddonModAssignPlugin, AddonModAssignSavePluginData } from './assign';
import { makeSingleton } from '@singletons';
import { CoreWSFile } from '@services/ws';
import { AddonModAssignSubmissionsDBRecordFormatted } from './assign-offline';
import { CoreFormFields } from '@singletons/form';
/**
* Interface that all submission handlers must implement.
*/
export interface AddonModAssignSubmissionHandler extends CoreDelegateHandler {
/**
* Name of the type of submission the handler supports. E.g. 'file'.
*/
type: string;
/**
* Whether the plugin can be edited in offline for existing submissions. In general, this should return false if the
* plugin uses Moodle filters. The reason is that the app only prefetches filtered data, and the user should edit
* unfiltered data.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @return Boolean or promise resolved with boolean: whether it can be edited in offline.
*/
canEditOffline?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
): boolean | Promise<boolean>;
/**
* Check if a plugin has no data.
*
* @param assign The assignment.
* @param plugin The plugin object.
* @return Whether the plugin is empty.
*/
isEmpty?(
assign: AddonModAssignAssign,
plugin: AddonModAssignPlugin,
): boolean;
/**
* Should clear temporary data for a cancelled submission.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
*/
clearTmpData?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
): void;
/**
* This function will be called when the user wants to create a new submission based on the previous one.
* It should add to pluginData the data to send to server based in the data in plugin (previous attempt).
*
* @param assign The assignment.
* @param plugin The plugin object.
* @param pluginData Object where to store the data to send.
* @param userId User ID. If not defined, site's current user.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
copySubmissionData?(
assign: AddonModAssignAssign,
plugin: AddonModAssignPlugin,
pluginData: AddonModAssignSavePluginData,
userId?: number,
siteId?: string,
): void | Promise<void>;
/**
* Delete any stored data for the plugin and submission.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param offlineData Offline data stored.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
deleteOfflineData?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
offlineData: AddonModAssignSubmissionsDBRecordFormatted,
siteId?: string,
): void | Promise<void>;
/**
* Return the Component to use to display the plugin data, either in read or in edit mode.
* It's recommended to return the class of the component, but you can also return an instance of the component.
*
* @param plugin The plugin object.
* @param edit Whether the user is editing.
* @return The component (or promise resolved with component) to use, undefined if not found.
*/
getComponent?(
plugin: AddonModAssignPlugin,
edit?: boolean,
): Type<unknown> | undefined | Promise<Type<unknown> | undefined>;
/**
* Get files used by this plugin.
* The files returned by this function will be prefetched when the user prefetches the assign.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return The files (or promise resolved with the files).
*/
getPluginFiles?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
siteId?: string,
): CoreWSFile[] | Promise<CoreWSFile[]>;
/**
* Get a readable name to use for the plugin.
*
* @param plugin The plugin object.
* @return The plugin name.
*/
getPluginName?(plugin: AddonModAssignPlugin): string;
/**
* Get the size of data (in bytes) this plugin will send to copy a previous submission.
*
* @param assign The assignment.
* @param plugin The plugin object.
* @return The size (or promise resolved with size).
*/
getSizeForCopy?(
assign: AddonModAssignAssign,
plugin: AddonModAssignPlugin,
): number | Promise<number>;
/**
* Get the size of data (in bytes) this plugin will send to add or edit a submission.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
* @return The size (or promise resolved with size).
*/
getSizeForEdit?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
): number | Promise<number>;
/**
* Check if the submission data has changed for this plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
* @return Boolean (or promise resolved with boolean): whether the data has changed.
*/
hasDataChanged?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
): boolean | Promise<boolean>;
/**
* Whether or not the handler is enabled for edit on a site level.
*
* @return Whether or not the handler is enabled for edit on a site level.
*/
isEnabledForEdit?(): boolean | Promise<boolean>;
/**
* Prefetch any required data for the plugin.
* This should NOT prefetch files. Files to be prefetched should be returned by the getPluginFiles function.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
prefetch?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<void>;
/**
* Prepare and add to pluginData the data to send to the server based on the input data.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
* @param pluginData Object where to store the data to send.
* @param offline Whether the user is editing in offline.
* @param userId User ID. If not defined, site's current user.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
prepareSubmissionData?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
pluginData: AddonModAssignSavePluginData,
offline?: boolean,
userId?: number,
siteId?: string,
): void | Promise<void>;
/**
* Prepare and add to pluginData the data to send to the server based on the offline data stored.
* This will be used when performing a synchronization.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param offlineData Offline data stored.
* @param pluginData Object where to store the data to send.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
prepareSyncData?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
offlineData: AddonModAssignSubmissionsDBRecordFormatted,
pluginData: AddonModAssignSavePluginData,
siteId?: string,
): void | Promise<void>;
}
/**
* Delegate to register plugins for assign submission.
*/
@Injectable({ providedIn: 'root' })
export class AddonModAssignSubmissionDelegateService extends CoreDelegate<AddonModAssignSubmissionHandler> {
protected handlerNameProperty = 'type';
constructor(
protected defaultHandler: AddonModAssignDefaultSubmissionHandler,
) {
super('AddonModAssignSubmissionDelegate', true);
}
/**
* Whether the plugin can be edited in offline for existing submissions.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @return Promise resolved with boolean: whether it can be edited in offline.
*/
async canPluginEditOffline(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
): Promise<boolean | undefined> {
return await this.executeFunctionOnEnabled(plugin.type, 'canEditOffline', [assign, submission, plugin]);
}
/**
* Clear some temporary data for a certain plugin because a submission was cancelled.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
*/
clearTmpData(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
): void {
return this.executeFunctionOnEnabled(plugin.type, 'clearTmpData', [assign, submission, plugin, inputData]);
}
/**
* Copy the data from last submitted attempt to the current submission for a certain plugin.
*
* @param assign The assignment.
* @param plugin The plugin object.
* @param pluginData Object where to store the data to send.
* @param userId User ID. If not defined, site's current user.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data has been copied.
*/
async copyPluginSubmissionData(
assign: AddonModAssignAssign,
plugin: AddonModAssignPlugin,
pluginData: AddonModAssignSavePluginData,
userId?: number,
siteId?: string,
): Promise<void | undefined> {
return await this.executeFunctionOnEnabled(
plugin.type,
'copySubmissionData',
[assign, plugin, pluginData, userId, siteId],
);
}
/**
* Delete offline data stored for a certain submission and plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param offlineData Offline data stored.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async deletePluginOfflineData(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
offlineData: AddonModAssignSubmissionsDBRecordFormatted,
siteId?: string,
): Promise<void> {
return await this.executeFunctionOnEnabled(
plugin.type,
'deleteOfflineData',
[assign, submission, plugin, offlineData, siteId],
);
}
/**
* Get the component to use for a certain submission plugin.
*
* @param plugin The plugin object.
* @param edit Whether the user is editing.
* @return Promise resolved with the component to use, undefined if not found.
*/
async getComponentForPlugin(plugin: AddonModAssignPlugin, edit?: boolean): Promise<Type<unknown> | undefined> {
return await this.executeFunctionOnEnabled(plugin.type, 'getComponent', [plugin, edit]);
}
/**
* Get files used by this plugin.
* The files returned by this function will be prefetched when the user prefetches the assign.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the files.
*/
async getPluginFiles(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<CoreWSFile[]> {
const files: CoreWSFile[] | undefined =
await this.executeFunctionOnEnabled(plugin.type, 'getPluginFiles', [assign, submission, plugin, siteId]);
return files || [];
}
/**
* Get a readable name to use for a certain submission plugin.
*
* @param plugin Plugin to get the name for.
* @return Human readable name.
*/
getPluginName(plugin: AddonModAssignPlugin): string | undefined {
return this.executeFunctionOnEnabled(plugin.type, 'getPluginName', [plugin]);
}
/**
* Get the size of data (in bytes) this plugin will send to copy a previous submission.
*
* @param assign The assignment.
* @param plugin The plugin object.
* @return Promise resolved with size.
*/
async getPluginSizeForCopy(assign: AddonModAssignAssign, plugin: AddonModAssignPlugin): Promise<number | undefined> {
return await this.executeFunctionOnEnabled(plugin.type, 'getSizeForCopy', [assign, plugin]);
}
/**
* Get the size of data (in bytes) this plugin will send to add or edit a submission.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
* @return Promise resolved with size.
*/
async getPluginSizeForEdit(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
): Promise<number | undefined> {
return await this.executeFunctionOnEnabled(
plugin.type,
'getSizeForEdit',
[assign, submission, plugin, inputData],
);
}
/**
* Check if the submission data has changed for a certain plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
* @return Promise resolved with true if data has changed, resolved with false otherwise.
*/
async hasPluginDataChanged(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
): Promise<boolean | undefined> {
return await this.executeFunctionOnEnabled(
plugin.type,
'hasDataChanged',
[assign, submission, plugin, inputData],
);
}
/**
* Check if a submission plugin is supported.
*
* @param pluginType Type of the plugin.
* @return Whether it's supported.
*/
isPluginSupported(pluginType: string): boolean {
return this.hasHandler(pluginType, true);
}
/**
* Check if a submission plugin is supported for edit.
*
* @param pluginType Type of the plugin.
* @return Whether it's supported for edit.
*/
async isPluginSupportedForEdit(pluginType: string): Promise<boolean | undefined> {
return await this.executeFunctionOnEnabled(pluginType, 'isEnabledForEdit');
}
/**
* Check if a plugin has no data.
*
* @param assign The assignment.
* @param plugin The plugin object.
* @return Whether the plugin is empty.
*/
isPluginEmpty(assign: AddonModAssignAssign, plugin: AddonModAssignPlugin): boolean | undefined {
return this.executeFunctionOnEnabled(plugin.type, 'isEmpty', [assign, plugin]);
}
/**
* Prefetch any required data for a submission plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async prefetch(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<void> {
return await this.executeFunctionOnEnabled(plugin.type, 'prefetch', [assign, submission, plugin, siteId]);
}
/**
* Prepare and add to pluginData the data to submit for a certain submission plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the submission.
* @param pluginData Object where to store the data to send.
* @param offline Whether the user is editing in offline.
* @param userId User ID. If not defined, site's current user.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when data has been gathered.
*/
async preparePluginSubmissionData(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
pluginData: AddonModAssignSavePluginData,
offline?: boolean,
userId?: number,
siteId?: string,
): Promise<void | undefined> {
return await this.executeFunctionOnEnabled(
plugin.type,
'prepareSubmissionData',
[assign, submission, plugin, inputData, pluginData, offline, userId, siteId],
);
}
/**
* Prepare and add to pluginData the data to send to server to synchronize an offline submission.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param offlineData Offline data stored.
* @param pluginData Object where to store the data to send.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when data has been gathered.
*/
async preparePluginSyncData(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
offlineData: AddonModAssignSubmissionsDBRecordFormatted,
pluginData: AddonModAssignSavePluginData,
siteId?: string,
): Promise<void> {
return this.executeFunctionOnEnabled(
plugin.type,
'prepareSyncData',
[assign, submission, plugin, offlineData, pluginData, siteId],
);
}
}
export const AddonModAssignSubmissionDelegate = makeSingleton(AddonModAssignSubmissionDelegateService); | the_stack |
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core';
import { ReposAPIClientInterface } from './repos-api-client.interface';
import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from '../../types';
import * as models from '../../models';
export const USE_DOMAIN = new InjectionToken<string>('ReposAPIClient_USE_DOMAIN');
export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('ReposAPIClient_USE_HTTP_OPTIONS');
type APIHttpOptions = HttpOptions & {
headers: HttpHeaders;
params: HttpParams;
};
@Injectable()
export class ReposAPIClient implements ReposAPIClientInterface {
readonly options: APIHttpOptions;
readonly domain: string = `https://api.github.com`;
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 } : {})
};
}
/**
* Delete a Repository.
* Deleting a repository requires admin access. If OAuth is used, the delete_repo
* scope is required.
*
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get repository.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Repo>;
getReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Repo>>;
getReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Repo>>;
getReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Repo | HttpResponse<models.Repo> | HttpEvent<models.Repo>> {
const path = `/repos/${args.owner}/${args.repo}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Repo>(`${this.domain}${path}`, options);
}
/**
* Edit repository.
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Repo>;
patchReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Repo>>;
patchReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Repo>>;
patchReposOwnerRepo(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Repo | HttpResponse<models.Repo> | HttpEvent<models.Repo>> {
const path = `/repos/${args.owner}/${args.repo}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.Repo>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List assignees.
* This call lists all the available assignees (owner + collaborators) to which
* issues may be assigned.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoAssignees(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Assignees>;
getReposOwnerRepoAssignees(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Assignees>>;
getReposOwnerRepoAssignees(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Assignees>>;
getReposOwnerRepoAssignees(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Assignees | HttpResponse<models.Assignees> | HttpEvent<models.Assignees>> {
const path = `/repos/${args.owner}/${args.repo}/assignees`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Assignees>(`${this.domain}${path}`, options);
}
/**
* Check assignee.
* You may also check to see if a particular user is an assignee for a repository.
*
* Response generated for [ 204 ] HTTP response code.
*/
getReposOwnerRepoAssigneesAssignee(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesAssigneeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getReposOwnerRepoAssigneesAssignee(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesAssigneeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getReposOwnerRepoAssigneesAssignee(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesAssigneeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getReposOwnerRepoAssigneesAssignee(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesAssigneeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/assignees/${args.assignee}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<void>(`${this.domain}${path}`, options);
}
/**
* Get list of branches
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoBranches(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Branches>;
getReposOwnerRepoBranches(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Branches>>;
getReposOwnerRepoBranches(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Branches>>;
getReposOwnerRepoBranches(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Branches | HttpResponse<models.Branches> | HttpEvent<models.Branches>> {
const path = `/repos/${args.owner}/${args.repo}/branches`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Branches>(`${this.domain}${path}`, options);
}
/**
* Get Branch
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoBranchesBranch(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesBranchParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Branch>;
getReposOwnerRepoBranchesBranch(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesBranchParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Branch>>;
getReposOwnerRepoBranchesBranch(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesBranchParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Branch>>;
getReposOwnerRepoBranchesBranch(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesBranchParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Branch | HttpResponse<models.Branch> | HttpEvent<models.Branch>> {
const path = `/repos/${args.owner}/${args.repo}/branches/${args.branch}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Branch>(`${this.domain}${path}`, options);
}
/**
* List.
* When authenticating as an organization owner of an organization-owned
* repository, all organization owners are included in the list of
* collaborators. Otherwise, only users with access to the repository are
* returned in the collaborators list.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoCollaborators(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getReposOwnerRepoCollaborators(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getReposOwnerRepoCollaborators(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getReposOwnerRepoCollaborators(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
const path = `/repos/${args.owner}/${args.repo}/collaborators`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Users>(`${this.domain}${path}`, options);
}
/**
* Remove collaborator.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/collaborators/${args.user}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Check if user is a collaborator
* Response generated for [ 204 ] HTTP response code.
*/
getReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/collaborators/${args.user}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<void>(`${this.domain}${path}`, options);
}
/**
* Add collaborator.
* Response generated for [ 204 ] HTTP response code.
*/
putReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
putReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
putReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
putReposOwnerRepoCollaboratorsUser(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoCollaboratorsUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/collaborators/${args.user}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.put<void>(`${this.domain}${path}`, null, options);
}
/**
* List commit comments for a repository.
* Comments are ordered by ascending ID.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RepoComments>;
getReposOwnerRepoComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RepoComments>>;
getReposOwnerRepoComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RepoComments>>;
getReposOwnerRepoComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RepoComments | HttpResponse<models.RepoComments> | HttpEvent<models.RepoComments>> {
const path = `/repos/${args.owner}/${args.repo}/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.RepoComments>(`${this.domain}${path}`, options);
}
/**
* Delete a commit comment
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a single commit comment.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.CommitComments>;
getReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.CommitComments>>;
getReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.CommitComments>>;
getReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.CommitComments | HttpResponse<models.CommitComments> | HttpEvent<models.CommitComments>> {
const path = `/repos/${args.owner}/${args.repo}/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.CommitComments>(`${this.domain}${path}`, options);
}
/**
* Update a commit comment.
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.CommitComments>;
patchReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.CommitComments>>;
patchReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.CommitComments>>;
patchReposOwnerRepoCommentsCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.CommitComments | HttpResponse<models.CommitComments> | HttpEvent<models.CommitComments>> {
const path = `/repos/${args.owner}/${args.repo}/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.CommitComments>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List commits on a repository.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoCommits(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Commits>;
getReposOwnerRepoCommits(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Commits>>;
getReposOwnerRepoCommits(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Commits>>;
getReposOwnerRepoCommits(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Commits | HttpResponse<models.Commits> | HttpEvent<models.Commits>> {
const path = `/repos/${args.owner}/${args.repo}/commits`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('since' in args) {
options.params = options.params.set('since', String(args.since));
}
if ('sha' in args) {
options.params = options.params.set('sha', String(args.sha));
}
if ('path' in args) {
options.params = options.params.set('path', String(args.path));
}
if ('author' in args) {
options.params = options.params.set('author', String(args.author));
}
if ('until' in args) {
options.params = options.params.set('until', String(args.until));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Commits>(`${this.domain}${path}`, options);
}
/**
* Get the combined Status for a specific Ref
* The Combined status endpoint is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the blog post for full details.
* To access this endpoint during the preview period, you must provide a custom media type in the Accept header:
* application/vnd.github.she-hulk-preview+json
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoCommitsRefStatus(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsRefStatusParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RefStatus>;
getReposOwnerRepoCommitsRefStatus(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsRefStatusParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RefStatus>>;
getReposOwnerRepoCommitsRefStatus(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsRefStatusParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RefStatus>>;
getReposOwnerRepoCommitsRefStatus(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsRefStatusParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RefStatus | HttpResponse<models.RefStatus> | HttpEvent<models.RefStatus>> {
const path = `/repos/${args.owner}/${args.repo}/commits/${args.ref}/status`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.RefStatus>(`${this.domain}${path}`, options);
}
/**
* Get a single commit.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoCommitsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Commit>;
getReposOwnerRepoCommitsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Commit>>;
getReposOwnerRepoCommitsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Commit>>;
getReposOwnerRepoCommitsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Commit | HttpResponse<models.Commit> | HttpEvent<models.Commit>> {
const path = `/repos/${args.owner}/${args.repo}/commits/${args.shaCode}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Commit>(`${this.domain}${path}`, options);
}
/**
* List comments for a single commitList comments for a single commit.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoCommitsShaCodeComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RepoComments>;
getReposOwnerRepoCommitsShaCodeComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RepoComments>>;
getReposOwnerRepoCommitsShaCodeComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RepoComments>>;
getReposOwnerRepoCommitsShaCodeComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RepoComments | HttpResponse<models.RepoComments> | HttpEvent<models.RepoComments>> {
const path = `/repos/${args.owner}/${args.repo}/commits/${args.shaCode}/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.RepoComments>(`${this.domain}${path}`, options);
}
/**
* Create a commit comment.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoCommitsShaCodeComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.CommitComments>;
postReposOwnerRepoCommitsShaCodeComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.CommitComments>>;
postReposOwnerRepoCommitsShaCodeComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.CommitComments>>;
postReposOwnerRepoCommitsShaCodeComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.CommitComments | HttpResponse<models.CommitComments> | HttpEvent<models.CommitComments>> {
const path = `/repos/${args.owner}/${args.repo}/commits/${args.shaCode}/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.CommitComments>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Compare two commits
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoCompareBaseIdHeadId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCompareBaseIdHeadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.CompareCommits>;
getReposOwnerRepoCompareBaseIdHeadId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCompareBaseIdHeadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.CompareCommits>>;
getReposOwnerRepoCompareBaseIdHeadId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCompareBaseIdHeadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.CompareCommits>>;
getReposOwnerRepoCompareBaseIdHeadId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCompareBaseIdHeadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.CompareCommits | HttpResponse<models.CompareCommits> | HttpEvent<models.CompareCommits>> {
const path = `/repos/${args.owner}/${args.repo}/compare/${args.baseId}...${args.headId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.CompareCommits>(`${this.domain}${path}`, options);
}
/**
* Delete a file.
* This method deletes a file in a repository.
*
* Response generated for [ 200 ] HTTP response code.
*/
deleteReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.DeleteFile>;
deleteReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.DeleteFile>>;
deleteReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.DeleteFile>>;
deleteReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.DeleteFile | HttpResponse<models.DeleteFile> | HttpEvent<models.DeleteFile>> {
const path = `/repos/${args.owner}/${args.repo}/contents/${args.path}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<models.DeleteFile>(`${this.domain}${path}`, options);
}
/**
* Get contents.
* This method returns the contents of a file or directory in a repository.
* Files and symlinks support a custom media type for getting the raw content.
* Directories and submodules do not support custom media types.
* Note: This API supports files up to 1 megabyte in size.
* Here can be many outcomes. For details see "http://developer.github.com/v3/repos/contents/"
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ContentsPath>;
getReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ContentsPath>>;
getReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ContentsPath>>;
getReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ContentsPath | HttpResponse<models.ContentsPath> | HttpEvent<models.ContentsPath>> {
const path = `/repos/${args.owner}/${args.repo}/contents/${args.path}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('queryPath' in args) {
options.params = options.params.set('queryPath', String(args.queryPath));
}
if ('ref' in args) {
options.params = options.params.set('ref', String(args.ref));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.ContentsPath>(`${this.domain}${path}`, options);
}
/**
* Create a file.
* Response generated for [ 200 ] HTTP response code.
*/
putReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.CreateFile>;
putReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.CreateFile>>;
putReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.CreateFile>>;
putReposOwnerRepoContentsPath(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoContentsPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.CreateFile | HttpResponse<models.CreateFile> | HttpEvent<models.CreateFile>> {
const path = `/repos/${args.owner}/${args.repo}/contents/${args.path}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.put<models.CreateFile>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get list of contributors.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoContributors(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContributorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Contributors>;
getReposOwnerRepoContributors(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContributorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Contributors>>;
getReposOwnerRepoContributors(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContributorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Contributors>>;
getReposOwnerRepoContributors(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContributorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Contributors | HttpResponse<models.Contributors> | HttpEvent<models.Contributors>> {
const path = `/repos/${args.owner}/${args.repo}/contributors`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('anon' in args) {
options.params = options.params.set('anon', String(args.anon));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Contributors>(`${this.domain}${path}`, options);
}
/**
* Users with pull access can view deployments for a repository
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoDeployments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RepoDeployments>;
getReposOwnerRepoDeployments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RepoDeployments>>;
getReposOwnerRepoDeployments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RepoDeployments>>;
getReposOwnerRepoDeployments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RepoDeployments | HttpResponse<models.RepoDeployments> | HttpEvent<models.RepoDeployments>> {
const path = `/repos/${args.owner}/${args.repo}/deployments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.RepoDeployments>(`${this.domain}${path}`, options);
}
/**
* Users with push access can create a deployment for a given ref
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoDeployments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.DeploymentResp>;
postReposOwnerRepoDeployments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.DeploymentResp>>;
postReposOwnerRepoDeployments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.DeploymentResp>>;
postReposOwnerRepoDeployments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.DeploymentResp | HttpResponse<models.DeploymentResp> | HttpEvent<models.DeploymentResp>> {
const path = `/repos/${args.owner}/${args.repo}/deployments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.DeploymentResp>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Users with pull access can view deployment statuses for a deployment
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoDeploymentsIdStatuses(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsIdStatusesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.DeploymentStatuses>;
getReposOwnerRepoDeploymentsIdStatuses(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsIdStatusesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.DeploymentStatuses>>;
getReposOwnerRepoDeploymentsIdStatuses(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsIdStatusesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.DeploymentStatuses>>;
getReposOwnerRepoDeploymentsIdStatuses(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsIdStatusesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.DeploymentStatuses | HttpResponse<models.DeploymentStatuses> | HttpEvent<models.DeploymentStatuses>> {
const path = `/repos/${args.owner}/${args.repo}/deployments/${args.id}/statuses`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.DeploymentStatuses>(`${this.domain}${path}`, options);
}
/**
* Create a Deployment Status
* Users with push access can create deployment statuses for a given deployment:
*
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoDeploymentsIdStatuses(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsIdStatusesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
postReposOwnerRepoDeploymentsIdStatuses(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsIdStatusesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
postReposOwnerRepoDeploymentsIdStatuses(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsIdStatusesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
postReposOwnerRepoDeploymentsIdStatuses(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsIdStatusesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/deployments/${args.id}/statuses`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Deprecated. List downloads for a repository.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoDownloads(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Downloads>;
getReposOwnerRepoDownloads(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Downloads>>;
getReposOwnerRepoDownloads(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Downloads>>;
getReposOwnerRepoDownloads(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Downloads | HttpResponse<models.Downloads> | HttpEvent<models.Downloads>> {
const path = `/repos/${args.owner}/${args.repo}/downloads`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Downloads>(`${this.domain}${path}`, options);
}
/**
* Deprecated. Delete a download.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoDownloadsDownloadId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoDownloadsDownloadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoDownloadsDownloadId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoDownloadsDownloadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoDownloadsDownloadId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoDownloadsDownloadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoDownloadsDownloadId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoDownloadsDownloadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/downloads/${args.downloadId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Deprecated. Get a single download.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoDownloadsDownloadId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsDownloadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Downloads>;
getReposOwnerRepoDownloadsDownloadId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsDownloadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Downloads>>;
getReposOwnerRepoDownloadsDownloadId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsDownloadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Downloads>>;
getReposOwnerRepoDownloadsDownloadId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsDownloadIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Downloads | HttpResponse<models.Downloads> | HttpEvent<models.Downloads>> {
const path = `/repos/${args.owner}/${args.repo}/downloads/${args.downloadId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Downloads>(`${this.domain}${path}`, options);
}
/**
* Get list of repository events.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Events>;
getReposOwnerRepoEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Events>>;
getReposOwnerRepoEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Events>>;
getReposOwnerRepoEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Events | HttpResponse<models.Events> | HttpEvent<models.Events>> {
const path = `/repos/${args.owner}/${args.repo}/events`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Events>(`${this.domain}${path}`, options);
}
/**
* List forks.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoForks(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Forks>;
getReposOwnerRepoForks(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Forks>>;
getReposOwnerRepoForks(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Forks>>;
getReposOwnerRepoForks(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Forks | HttpResponse<models.Forks> | HttpEvent<models.Forks>> {
const path = `/repos/${args.owner}/${args.repo}/forks`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('sort' in args) {
options.params = options.params.set('sort', String(args.sort));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Forks>(`${this.domain}${path}`, options);
}
/**
* Create a fork.
* Forking a Repository happens asynchronously. Therefore, you may have to wai
* a short period before accessing the git objects. If this takes longer than 5
* minutes, be sure to contact Support.
*
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoForks(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Fork>;
postReposOwnerRepoForks(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Fork>>;
postReposOwnerRepoForks(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Fork>>;
postReposOwnerRepoForks(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Fork | HttpResponse<models.Fork> | HttpEvent<models.Fork>> {
const path = `/repos/${args.owner}/${args.repo}/forks`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Fork>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Create a Blob.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoGitBlobs(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Blobs>;
postReposOwnerRepoGitBlobs(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Blobs>>;
postReposOwnerRepoGitBlobs(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Blobs>>;
postReposOwnerRepoGitBlobs(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Blobs | HttpResponse<models.Blobs> | HttpEvent<models.Blobs>> {
const path = `/repos/${args.owner}/${args.repo}/git/blobs`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Blobs>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get a Blob.
* Since blobs can be any arbitrary binary data, the input and responses for
* the blob API takes an encoding parameter that can be either utf-8 or
* base64. If your data cannot be losslessly sent as a UTF-8 string, you can
* base64 encode it.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Blob>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Blob>>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Blob>>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Blob | HttpResponse<models.Blob> | HttpEvent<models.Blob>> {
const path = `/repos/${args.owner}/${args.repo}/git/blobs/${args.shaCode}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Blob>(`${this.domain}${path}`, options);
}
/**
* Create a Commit.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoGitCommits(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.GitCommit>;
postReposOwnerRepoGitCommits(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.GitCommit>>;
postReposOwnerRepoGitCommits(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.GitCommit>>;
postReposOwnerRepoGitCommits(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.GitCommit | HttpResponse<models.GitCommit> | HttpEvent<models.GitCommit>> {
const path = `/repos/${args.owner}/${args.repo}/git/commits`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.GitCommit>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get a Commit.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoGitCommitsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitCommitsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RepoCommit>;
getReposOwnerRepoGitCommitsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitCommitsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RepoCommit>>;
getReposOwnerRepoGitCommitsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitCommitsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RepoCommit>>;
getReposOwnerRepoGitCommitsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitCommitsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RepoCommit | HttpResponse<models.RepoCommit> | HttpEvent<models.RepoCommit>> {
const path = `/repos/${args.owner}/${args.repo}/git/commits/${args.shaCode}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.RepoCommit>(`${this.domain}${path}`, options);
}
/**
* Get all References
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoGitRefs(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Refs>;
getReposOwnerRepoGitRefs(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Refs>>;
getReposOwnerRepoGitRefs(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Refs>>;
getReposOwnerRepoGitRefs(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Refs | HttpResponse<models.Refs> | HttpEvent<models.Refs>> {
const path = `/repos/${args.owner}/${args.repo}/git/refs`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Refs>(`${this.domain}${path}`, options);
}
/**
* Create a Reference
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoGitRefs(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitRefsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.HeadBranch>;
postReposOwnerRepoGitRefs(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitRefsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.HeadBranch>>;
postReposOwnerRepoGitRefs(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitRefsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.HeadBranch>>;
postReposOwnerRepoGitRefs(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitRefsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.HeadBranch | HttpResponse<models.HeadBranch> | HttpEvent<models.HeadBranch>> {
const path = `/repos/${args.owner}/${args.repo}/git/refs`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.HeadBranch>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Delete a Reference
* Example: Deleting a branch: DELETE /repos/octocat/Hello-World/git/refs/heads/feature-a
* Example: Deleting a tag: DELETE /repos/octocat/Hello-World/git/refs/tags/v1.0
*
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/git/refs/${args.ref}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a Reference
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.HeadBranch>;
getReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.HeadBranch>>;
getReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.HeadBranch>>;
getReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.HeadBranch | HttpResponse<models.HeadBranch> | HttpEvent<models.HeadBranch>> {
const path = `/repos/${args.owner}/${args.repo}/git/refs/${args.ref}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.HeadBranch>(`${this.domain}${path}`, options);
}
/**
* Update a Reference
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.HeadBranch>;
patchReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.HeadBranch>>;
patchReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.HeadBranch>>;
patchReposOwnerRepoGitRefsRef(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoGitRefsRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.HeadBranch | HttpResponse<models.HeadBranch> | HttpEvent<models.HeadBranch>> {
const path = `/repos/${args.owner}/${args.repo}/git/refs/${args.ref}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.HeadBranch>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Create a Tag Object.
* Note that creating a tag object does not create the reference that makes a
* tag in Git. If you want to create an annotated tag in Git, you have to do
* this call to create the tag object, and then create the refs/tags/[tag]
* reference. If you want to create a lightweight tag, you only have to create
* the tag reference - this call would be unnecessary.
*
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoGitTags(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Tags>;
postReposOwnerRepoGitTags(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Tags>>;
postReposOwnerRepoGitTags(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Tags>>;
postReposOwnerRepoGitTags(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Tags | HttpResponse<models.Tags> | HttpEvent<models.Tags>> {
const path = `/repos/${args.owner}/${args.repo}/git/tags`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Tags>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get a Tag.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoGitTagsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTagsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Tag>;
getReposOwnerRepoGitTagsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTagsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Tag>>;
getReposOwnerRepoGitTagsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTagsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Tag>>;
getReposOwnerRepoGitTagsShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTagsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Tag | HttpResponse<models.Tag> | HttpEvent<models.Tag>> {
const path = `/repos/${args.owner}/${args.repo}/git/tags/${args.shaCode}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Tag>(`${this.domain}${path}`, options);
}
/**
* Create a Tree.
* The tree creation API will take nested entries as well. If both a tree and
* a nested path modifying that tree are specified, it will overwrite the
* contents of that tree with the new path contents and write a new tree out.
*
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoGitTrees(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTreesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Trees>;
postReposOwnerRepoGitTrees(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTreesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Trees>>;
postReposOwnerRepoGitTrees(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTreesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Trees>>;
postReposOwnerRepoGitTrees(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTreesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Trees | HttpResponse<models.Trees> | HttpEvent<models.Trees>> {
const path = `/repos/${args.owner}/${args.repo}/git/trees`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Trees>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get a Tree.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoGitTreesShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTreesShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Tree>;
getReposOwnerRepoGitTreesShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTreesShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Tree>>;
getReposOwnerRepoGitTreesShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTreesShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Tree>>;
getReposOwnerRepoGitTreesShaCode(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTreesShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Tree | HttpResponse<models.Tree> | HttpEvent<models.Tree>> {
const path = `/repos/${args.owner}/${args.repo}/git/trees/${args.shaCode}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('recursive' in args) {
options.params = options.params.set('recursive', String(args.recursive));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Tree>(`${this.domain}${path}`, options);
}
/**
* Get list of hooks.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoHooks(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Hook>;
getReposOwnerRepoHooks(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Hook>>;
getReposOwnerRepoHooks(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Hook>>;
getReposOwnerRepoHooks(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Hook | HttpResponse<models.Hook> | HttpEvent<models.Hook>> {
const path = `/repos/${args.owner}/${args.repo}/hooks`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Hook>(`${this.domain}${path}`, options);
}
/**
* Create a hook.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoHooks(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Hook>;
postReposOwnerRepoHooks(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Hook>>;
postReposOwnerRepoHooks(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Hook>>;
postReposOwnerRepoHooks(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Hook | HttpResponse<models.Hook> | HttpEvent<models.Hook>> {
const path = `/repos/${args.owner}/${args.repo}/hooks`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Hook>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Delete a hook.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/hooks/${args.hookId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get single hook.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Hook>;
getReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Hook>>;
getReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Hook>>;
getReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Hook | HttpResponse<models.Hook> | HttpEvent<models.Hook>> {
const path = `/repos/${args.owner}/${args.repo}/hooks/${args.hookId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Hook>(`${this.domain}${path}`, options);
}
/**
* Edit a hook.
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Hook>;
patchReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Hook>>;
patchReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Hook>>;
patchReposOwnerRepoHooksHookId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoHooksHookIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Hook | HttpResponse<models.Hook> | HttpEvent<models.Hook>> {
const path = `/repos/${args.owner}/${args.repo}/hooks/${args.hookId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.Hook>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Test a push hook.
* This will trigger the hook with the latest push to the current repository
* if the hook is subscribed to push events. If the hook is not subscribed
* to push events, the server will respond with 204 but no test POST will
* be generated.
* Note: Previously /repos/:owner/:repo/hooks/:id/tes
*
* Response generated for [ 204 ] HTTP response code.
*/
postReposOwnerRepoHooksHookIdTests(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksHookIdTestsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
postReposOwnerRepoHooksHookIdTests(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksHookIdTestsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
postReposOwnerRepoHooksHookIdTests(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksHookIdTestsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
postReposOwnerRepoHooksHookIdTests(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksHookIdTestsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/hooks/${args.hookId}/tests`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<void>(`${this.domain}${path}`, null, options);
}
/**
* List issues for a repository.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssues(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Issues>;
getReposOwnerRepoIssues(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Issues>>;
getReposOwnerRepoIssues(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Issues>>;
getReposOwnerRepoIssues(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Issues | HttpResponse<models.Issues> | HttpEvent<models.Issues>> {
const path = `/repos/${args.owner}/${args.repo}/issues`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('filter' in args) {
options.params = options.params.set('filter', String(args.filter));
}
if ('state' in args) {
options.params = options.params.set('state', String(args.state));
}
if ('labels' in args) {
options.params = options.params.set('labels', String(args.labels));
}
if ('sort' in args) {
options.params = options.params.set('sort', String(args.sort));
}
if ('direction' in args) {
options.params = options.params.set('direction', String(args.direction));
}
if ('since' in args) {
options.params = options.params.set('since', String(args.since));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Issues>(`${this.domain}${path}`, options);
}
/**
* Create an issue.
* Any user with pull access to a repository can create an issue.
*
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoIssues(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Issue>;
postReposOwnerRepoIssues(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Issue>>;
postReposOwnerRepoIssues(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Issue>>;
postReposOwnerRepoIssues(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Issue | HttpResponse<models.Issue> | HttpEvent<models.Issue>> {
const path = `/repos/${args.owner}/${args.repo}/issues`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Issue>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List comments in a repository.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssuesComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.IssuesComments>;
getReposOwnerRepoIssuesComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.IssuesComments>>;
getReposOwnerRepoIssuesComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.IssuesComments>>;
getReposOwnerRepoIssuesComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.IssuesComments | HttpResponse<models.IssuesComments> | HttpEvent<models.IssuesComments>> {
const path = `/repos/${args.owner}/${args.repo}/issues/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('direction' in args) {
options.params = options.params.set('direction', String(args.direction));
}
if ('sort' in args) {
options.params = options.params.set('sort', String(args.sort));
}
if ('since' in args) {
options.params = options.params.set('since', String(args.since));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.IssuesComments>(`${this.domain}${path}`, options);
}
/**
* Delete a comment.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/issues/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a single comment.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.IssuesComment>;
getReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.IssuesComment>>;
getReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.IssuesComment>>;
getReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.IssuesComment | HttpResponse<models.IssuesComment> | HttpEvent<models.IssuesComment>> {
const path = `/repos/${args.owner}/${args.repo}/issues/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.IssuesComment>(`${this.domain}${path}`, options);
}
/**
* Edit a comment.
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.IssuesComment>;
patchReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.IssuesComment>>;
patchReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.IssuesComment>>;
patchReposOwnerRepoIssuesCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.IssuesComment | HttpResponse<models.IssuesComment> | HttpEvent<models.IssuesComment>> {
const path = `/repos/${args.owner}/${args.repo}/issues/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.IssuesComment>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List issue events for a repository.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssuesEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Events>;
getReposOwnerRepoIssuesEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Events>>;
getReposOwnerRepoIssuesEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Events>>;
getReposOwnerRepoIssuesEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Events | HttpResponse<models.Events> | HttpEvent<models.Events>> {
const path = `/repos/${args.owner}/${args.repo}/issues/events`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Events>(`${this.domain}${path}`, options);
}
/**
* Get a single event.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssuesEventId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Event>;
getReposOwnerRepoIssuesEventId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Event>>;
getReposOwnerRepoIssuesEventId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Event>>;
getReposOwnerRepoIssuesEventId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Event | HttpResponse<models.Event> | HttpEvent<models.Event>> {
const path = `/repos/${args.owner}/${args.repo}/issues/events/${args.eventId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Event>(`${this.domain}${path}`, options);
}
/**
* Get a single issue
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssuesNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Issue>;
getReposOwnerRepoIssuesNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Issue>>;
getReposOwnerRepoIssuesNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Issue>>;
getReposOwnerRepoIssuesNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Issue | HttpResponse<models.Issue> | HttpEvent<models.Issue>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Issue>(`${this.domain}${path}`, options);
}
/**
* Edit an issue.
* Issue owners and users with push access can edit an issue.
*
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoIssuesNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Issue>;
patchReposOwnerRepoIssuesNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Issue>>;
patchReposOwnerRepoIssuesNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Issue>>;
patchReposOwnerRepoIssuesNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Issue | HttpResponse<models.Issue> | HttpEvent<models.Issue>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.Issue>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List comments on an issue.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssuesNumberComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.IssuesComments>;
getReposOwnerRepoIssuesNumberComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.IssuesComments>>;
getReposOwnerRepoIssuesNumberComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.IssuesComments>>;
getReposOwnerRepoIssuesNumberComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.IssuesComments | HttpResponse<models.IssuesComments> | HttpEvent<models.IssuesComments>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.IssuesComments>(`${this.domain}${path}`, options);
}
/**
* Create a comment.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoIssuesNumberComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.IssuesComment>;
postReposOwnerRepoIssuesNumberComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.IssuesComment>>;
postReposOwnerRepoIssuesNumberComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.IssuesComment>>;
postReposOwnerRepoIssuesNumberComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.IssuesComment | HttpResponse<models.IssuesComment> | HttpEvent<models.IssuesComment>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.IssuesComment>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List events for an issue.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssuesNumberEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Events>;
getReposOwnerRepoIssuesNumberEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Events>>;
getReposOwnerRepoIssuesNumberEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Events>>;
getReposOwnerRepoIssuesNumberEvents(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Events | HttpResponse<models.Events> | HttpEvent<models.Events>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}/events`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Events>(`${this.domain}${path}`, options);
}
/**
* Remove all labels from an issue.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}/labels`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* List labels on an issue.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Labels>;
getReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Labels>>;
getReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Labels>>;
getReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Labels | HttpResponse<models.Labels> | HttpEvent<models.Labels>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}/labels`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Labels>(`${this.domain}${path}`, options);
}
/**
* Add labels to an issue.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Label>;
postReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Label>>;
postReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Label>>;
postReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Label | HttpResponse<models.Label> | HttpEvent<models.Label>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}/labels`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Label>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Replace all labels for an issue.
* Sending an empty array ([]) will remove all Labels from the Issue.
*
* Response generated for [ 201 ] HTTP response code.
*/
putReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Label>;
putReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Label>>;
putReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Label>>;
putReposOwnerRepoIssuesNumberLabels(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoIssuesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Label | HttpResponse<models.Label> | HttpEvent<models.Label>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}/labels`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.put<models.Label>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Remove a label from an issue.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoIssuesNumberLabelsName(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoIssuesNumberLabelsName(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoIssuesNumberLabelsName(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoIssuesNumberLabelsName(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/issues/${args.number}/labels/${args.name}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get list of keys.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoKeys(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Keys>;
getReposOwnerRepoKeys(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Keys>>;
getReposOwnerRepoKeys(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Keys>>;
getReposOwnerRepoKeys(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Keys | HttpResponse<models.Keys> | HttpEvent<models.Keys>> {
const path = `/repos/${args.owner}/${args.repo}/keys`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Keys>(`${this.domain}${path}`, options);
}
/**
* Create a key.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoKeys(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserKeysKeyId>;
postReposOwnerRepoKeys(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserKeysKeyId>>;
postReposOwnerRepoKeys(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserKeysKeyId>>;
postReposOwnerRepoKeys(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserKeysKeyId | HttpResponse<models.UserKeysKeyId> | HttpEvent<models.UserKeysKeyId>> {
const path = `/repos/${args.owner}/${args.repo}/keys`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.UserKeysKeyId>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Delete a key.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoKeysKeyId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoKeysKeyId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoKeysKeyId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoKeysKeyId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/keys/${args.keyId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a key
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoKeysKeyId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserKeysKeyId>;
getReposOwnerRepoKeysKeyId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserKeysKeyId>>;
getReposOwnerRepoKeysKeyId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserKeysKeyId>>;
getReposOwnerRepoKeysKeyId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserKeysKeyId | HttpResponse<models.UserKeysKeyId> | HttpEvent<models.UserKeysKeyId>> {
const path = `/repos/${args.owner}/${args.repo}/keys/${args.keyId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.UserKeysKeyId>(`${this.domain}${path}`, options);
}
/**
* List all labels for this repository.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Labels>;
getReposOwnerRepoLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Labels>>;
getReposOwnerRepoLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Labels>>;
getReposOwnerRepoLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Labels | HttpResponse<models.Labels> | HttpEvent<models.Labels>> {
const path = `/repos/${args.owner}/${args.repo}/labels`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Labels>(`${this.domain}${path}`, options);
}
/**
* Create a label.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoLabels(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Label>;
postReposOwnerRepoLabels(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Label>>;
postReposOwnerRepoLabels(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Label>>;
postReposOwnerRepoLabels(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Label | HttpResponse<models.Label> | HttpEvent<models.Label>> {
const path = `/repos/${args.owner}/${args.repo}/labels`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Label>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Delete a label.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/labels/${args.name}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a single label.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Label>;
getReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Label>>;
getReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Label>>;
getReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Label | HttpResponse<models.Label> | HttpEvent<models.Label>> {
const path = `/repos/${args.owner}/${args.repo}/labels/${args.name}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Label>(`${this.domain}${path}`, options);
}
/**
* Update a label.
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Label>;
patchReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Label>>;
patchReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Label>>;
patchReposOwnerRepoLabelsName(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoLabelsNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Label | HttpResponse<models.Label> | HttpEvent<models.Label>> {
const path = `/repos/${args.owner}/${args.repo}/labels/${args.name}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.Label>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List languages.
* List languages for the specified repository. The value on the right of a
* language is the number of bytes of code written in that language.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoLanguages(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLanguagesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Languages>;
getReposOwnerRepoLanguages(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLanguagesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Languages>>;
getReposOwnerRepoLanguages(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLanguagesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Languages>>;
getReposOwnerRepoLanguages(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLanguagesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Languages | HttpResponse<models.Languages> | HttpEvent<models.Languages>> {
const path = `/repos/${args.owner}/${args.repo}/languages`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Languages>(`${this.domain}${path}`, options);
}
/**
* Perform a merge.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoMerges(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMergesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.MergesSuccessful>;
postReposOwnerRepoMerges(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMergesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.MergesSuccessful>>;
postReposOwnerRepoMerges(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMergesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.MergesSuccessful>>;
postReposOwnerRepoMerges(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMergesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.MergesSuccessful | HttpResponse<models.MergesSuccessful> | HttpEvent<models.MergesSuccessful>> {
const path = `/repos/${args.owner}/${args.repo}/merges`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.MergesSuccessful>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List milestones for a repository.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoMilestones(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Milestone>;
getReposOwnerRepoMilestones(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Milestone>>;
getReposOwnerRepoMilestones(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Milestone>>;
getReposOwnerRepoMilestones(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Milestone | HttpResponse<models.Milestone> | HttpEvent<models.Milestone>> {
const path = `/repos/${args.owner}/${args.repo}/milestones`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('state' in args) {
options.params = options.params.set('state', String(args.state));
}
if ('direction' in args) {
options.params = options.params.set('direction', String(args.direction));
}
if ('sort' in args) {
options.params = options.params.set('sort', String(args.sort));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Milestone>(`${this.domain}${path}`, options);
}
/**
* Create a milestone.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoMilestones(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMilestonesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Milestone>;
postReposOwnerRepoMilestones(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMilestonesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Milestone>>;
postReposOwnerRepoMilestones(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMilestonesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Milestone>>;
postReposOwnerRepoMilestones(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMilestonesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Milestone | HttpResponse<models.Milestone> | HttpEvent<models.Milestone>> {
const path = `/repos/${args.owner}/${args.repo}/milestones`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Milestone>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Delete a milestone.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/milestones/${args.number}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a single milestone.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Milestone>;
getReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Milestone>>;
getReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Milestone>>;
getReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Milestone | HttpResponse<models.Milestone> | HttpEvent<models.Milestone>> {
const path = `/repos/${args.owner}/${args.repo}/milestones/${args.number}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Milestone>(`${this.domain}${path}`, options);
}
/**
* Update a milestone.
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Milestone>;
patchReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Milestone>>;
patchReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Milestone>>;
patchReposOwnerRepoMilestonesNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoMilestonesNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Milestone | HttpResponse<models.Milestone> | HttpEvent<models.Milestone>> {
const path = `/repos/${args.owner}/${args.repo}/milestones/${args.number}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.Milestone>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get labels for every issue in a milestone.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoMilestonesNumberLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Labels>;
getReposOwnerRepoMilestonesNumberLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Labels>>;
getReposOwnerRepoMilestonesNumberLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Labels>>;
getReposOwnerRepoMilestonesNumberLabels(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberLabelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Labels | HttpResponse<models.Labels> | HttpEvent<models.Labels>> {
const path = `/repos/${args.owner}/${args.repo}/milestones/${args.number}/labels`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Labels>(`${this.domain}${path}`, options);
}
/**
* List your notifications in a repository
* List all notifications for the current user.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoNotifications(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Notifications>;
getReposOwnerRepoNotifications(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Notifications>>;
getReposOwnerRepoNotifications(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Notifications>>;
getReposOwnerRepoNotifications(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Notifications | HttpResponse<models.Notifications> | HttpEvent<models.Notifications>> {
const path = `/repos/${args.owner}/${args.repo}/notifications`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('all' in args) {
options.params = options.params.set('all', String(args.all));
}
if ('participating' in args) {
options.params = options.params.set('participating', String(args.participating));
}
if ('since' in args) {
options.params = options.params.set('since', String(args.since));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Notifications>(`${this.domain}${path}`, options);
}
/**
* Mark notifications as read in a repository.
* Marking all notifications in a repository as "read" removes them from the
* default view on GitHub.com.
*
* Response generated for [ 205 ] HTTP response code.
*/
putReposOwnerRepoNotifications(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
putReposOwnerRepoNotifications(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
putReposOwnerRepoNotifications(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
putReposOwnerRepoNotifications(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoNotificationsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/notifications`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.put<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List pull requests.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoPulls(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pulls>;
getReposOwnerRepoPulls(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pulls>>;
getReposOwnerRepoPulls(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pulls>>;
getReposOwnerRepoPulls(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pulls | HttpResponse<models.Pulls> | HttpEvent<models.Pulls>> {
const path = `/repos/${args.owner}/${args.repo}/pulls`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('state' in args) {
options.params = options.params.set('state', String(args.state));
}
if ('head' in args) {
options.params = options.params.set('head', String(args.head));
}
if ('base' in args) {
options.params = options.params.set('base', String(args.base));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Pulls>(`${this.domain}${path}`, options);
}
/**
* Create a pull request.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoPulls(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pulls>;
postReposOwnerRepoPulls(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pulls>>;
postReposOwnerRepoPulls(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pulls>>;
postReposOwnerRepoPulls(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pulls | HttpResponse<models.Pulls> | HttpEvent<models.Pulls>> {
const path = `/repos/${args.owner}/${args.repo}/pulls`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Pulls>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List comments in a repository.
* By default, Review Comments are ordered by ascending ID.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoPullsComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.IssuesComments>;
getReposOwnerRepoPullsComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.IssuesComments>>;
getReposOwnerRepoPullsComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.IssuesComments>>;
getReposOwnerRepoPullsComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.IssuesComments | HttpResponse<models.IssuesComments> | HttpEvent<models.IssuesComments>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('direction' in args) {
options.params = options.params.set('direction', String(args.direction));
}
if ('sort' in args) {
options.params = options.params.set('sort', String(args.sort));
}
if ('since' in args) {
options.params = options.params.set('since', String(args.since));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.IssuesComments>(`${this.domain}${path}`, options);
}
/**
* Delete a comment.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a single comment.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PullsComment>;
getReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PullsComment>>;
getReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PullsComment>>;
getReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PullsComment | HttpResponse<models.PullsComment> | HttpEvent<models.PullsComment>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.PullsComment>(`${this.domain}${path}`, options);
}
/**
* Edit a comment.
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PullsComment>;
patchReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PullsComment>>;
patchReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PullsComment>>;
patchReposOwnerRepoPullsCommentId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PullsComment | HttpResponse<models.PullsComment> | HttpEvent<models.PullsComment>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/comments/${args.commentId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.PullsComment>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get a single pull request.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoPullsNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PullRequest>;
getReposOwnerRepoPullsNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PullRequest>>;
getReposOwnerRepoPullsNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PullRequest>>;
getReposOwnerRepoPullsNumber(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PullRequest | HttpResponse<models.PullRequest> | HttpEvent<models.PullRequest>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/${args.number}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.PullRequest>(`${this.domain}${path}`, options);
}
/**
* Update a pull request.
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoPullsNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Repo>;
patchReposOwnerRepoPullsNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Repo>>;
patchReposOwnerRepoPullsNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Repo>>;
patchReposOwnerRepoPullsNumber(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsNumberParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Repo | HttpResponse<models.Repo> | HttpEvent<models.Repo>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/${args.number}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.Repo>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List comments on a pull request.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoPullsNumberComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PullsComment>;
getReposOwnerRepoPullsNumberComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PullsComment>>;
getReposOwnerRepoPullsNumberComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PullsComment>>;
getReposOwnerRepoPullsNumberComments(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PullsComment | HttpResponse<models.PullsComment> | HttpEvent<models.PullsComment>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/${args.number}/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.PullsComment>(`${this.domain}${path}`, options);
}
/**
* Create a comment.
*
* #TODO Alternative input
* ( http://developer.github.com/v3/pulls/comments/ )
*
* description: |
*
* Alternative Input.
*
* Instead of passing commit_id, path, and position you can reply to an
*
* existing Pull Request Comment like this:
*
*
*
* body
*
* Required string
*
* in_reply_to
*
* Required number - Comment id to reply to.
*
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoPullsNumberComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PullsComment>;
postReposOwnerRepoPullsNumberComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PullsComment>>;
postReposOwnerRepoPullsNumberComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PullsComment>>;
postReposOwnerRepoPullsNumberComments(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsNumberCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PullsComment | HttpResponse<models.PullsComment> | HttpEvent<models.PullsComment>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/${args.number}/comments`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.PullsComment>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List commits on a pull request.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoPullsNumberCommits(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Commits>;
getReposOwnerRepoPullsNumberCommits(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Commits>>;
getReposOwnerRepoPullsNumberCommits(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Commits>>;
getReposOwnerRepoPullsNumberCommits(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommitsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Commits | HttpResponse<models.Commits> | HttpEvent<models.Commits>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/${args.number}/commits`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Commits>(`${this.domain}${path}`, options);
}
/**
* List pull requests files.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoPullsNumberFiles(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberFilesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pulls>;
getReposOwnerRepoPullsNumberFiles(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberFilesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pulls>>;
getReposOwnerRepoPullsNumberFiles(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberFilesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pulls>>;
getReposOwnerRepoPullsNumberFiles(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberFilesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pulls | HttpResponse<models.Pulls> | HttpEvent<models.Pulls>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/${args.number}/files`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Pulls>(`${this.domain}${path}`, options);
}
/**
* Get if a pull request has been merged.
* Response generated for [ 204 ] HTTP response code.
*/
getReposOwnerRepoPullsNumberMerge(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberMergeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getReposOwnerRepoPullsNumberMerge(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberMergeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getReposOwnerRepoPullsNumberMerge(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberMergeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getReposOwnerRepoPullsNumberMerge(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberMergeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/${args.number}/merge`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<void>(`${this.domain}${path}`, options);
}
/**
* Merge a pull request (Merge Button's)
* Response generated for [ 200 ] HTTP response code.
*/
putReposOwnerRepoPullsNumberMerge(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoPullsNumberMergeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Merge>;
putReposOwnerRepoPullsNumberMerge(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoPullsNumberMergeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Merge>>;
putReposOwnerRepoPullsNumberMerge(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoPullsNumberMergeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Merge>>;
putReposOwnerRepoPullsNumberMerge(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoPullsNumberMergeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Merge | HttpResponse<models.Merge> | HttpEvent<models.Merge>> {
const path = `/repos/${args.owner}/${args.repo}/pulls/${args.number}/merge`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.put<models.Merge>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get the README.
* This method returns the preferred README for a repository.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoReadme(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReadmeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ContentsPath>;
getReposOwnerRepoReadme(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReadmeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ContentsPath>>;
getReposOwnerRepoReadme(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReadmeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ContentsPath>>;
getReposOwnerRepoReadme(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReadmeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ContentsPath | HttpResponse<models.ContentsPath> | HttpEvent<models.ContentsPath>> {
const path = `/repos/${args.owner}/${args.repo}/readme`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('ref' in args) {
options.params = options.params.set('ref', String(args.ref));
}
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.ContentsPath>(`${this.domain}${path}`, options);
}
/**
* Users with push access to the repository will receive all releases (i.e., published releases and draft releases). Users with pull access will receive published releases only
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoReleases(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Releases>;
getReposOwnerRepoReleases(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Releases>>;
getReposOwnerRepoReleases(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Releases>>;
getReposOwnerRepoReleases(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Releases | HttpResponse<models.Releases> | HttpEvent<models.Releases>> {
const path = `/repos/${args.owner}/${args.repo}/releases`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Releases>(`${this.domain}${path}`, options);
}
/**
* Create a release
* Users with push access to the repository can create a release.
*
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoReleases(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoReleasesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Release>;
postReposOwnerRepoReleases(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoReleasesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Release>>;
postReposOwnerRepoReleases(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoReleasesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Release>>;
postReposOwnerRepoReleases(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoReleasesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Release | HttpResponse<models.Release> | HttpEvent<models.Release>> {
const path = `/repos/${args.owner}/${args.repo}/releases`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Release>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Delete a release asset
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/releases/assets/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a single release asset
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Asset>;
getReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Asset>>;
getReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Asset>>;
getReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Asset | HttpResponse<models.Asset> | HttpEvent<models.Asset>> {
const path = `/repos/${args.owner}/${args.repo}/releases/assets/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Asset>(`${this.domain}${path}`, options);
}
/**
* Edit a release asset
* Users with push access to the repository can edit a release asset.
*
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Asset>;
patchReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Asset>>;
patchReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Asset>>;
patchReposOwnerRepoReleasesAssetsId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesAssetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Asset | HttpResponse<models.Asset> | HttpEvent<models.Asset>> {
const path = `/repos/${args.owner}/${args.repo}/releases/assets/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.Asset>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Users with push access to the repository can delete a release.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/releases/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a single release
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Release>;
getReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Release>>;
getReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Release>>;
getReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Release | HttpResponse<models.Release> | HttpEvent<models.Release>> {
const path = `/repos/${args.owner}/${args.repo}/releases/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Release>(`${this.domain}${path}`, options);
}
/**
* Users with push access to the repository can edit a release
* Response generated for [ 200 ] HTTP response code.
*/
patchReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Release>;
patchReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Release>>;
patchReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Release>>;
patchReposOwnerRepoReleasesId(
args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Release | HttpResponse<models.Release> | HttpEvent<models.Release>> {
const path = `/repos/${args.owner}/${args.repo}/releases/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.patch<models.Release>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List assets for a release
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoReleasesIdAssets(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdAssetsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Assets>;
getReposOwnerRepoReleasesIdAssets(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdAssetsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Assets>>;
getReposOwnerRepoReleasesIdAssets(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdAssetsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Assets>>;
getReposOwnerRepoReleasesIdAssets(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdAssetsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Assets | HttpResponse<models.Assets> | HttpEvent<models.Assets>> {
const path = `/repos/${args.owner}/${args.repo}/releases/${args.id}/assets`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Assets>(`${this.domain}${path}`, options);
}
/**
* List Stargazers.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoStargazers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStargazersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getReposOwnerRepoStargazers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStargazersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getReposOwnerRepoStargazers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStargazersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getReposOwnerRepoStargazers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStargazersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
const path = `/repos/${args.owner}/${args.repo}/stargazers`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Users>(`${this.domain}${path}`, options);
}
/**
* Get the number of additions and deletions per week.
* Returns a weekly aggregate of the number of additions and deletions pushed
* to a repository.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoStatsCodeFrequency(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCodeFrequencyParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.CodeFrequencyStats>;
getReposOwnerRepoStatsCodeFrequency(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCodeFrequencyParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.CodeFrequencyStats>>;
getReposOwnerRepoStatsCodeFrequency(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCodeFrequencyParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.CodeFrequencyStats>>;
getReposOwnerRepoStatsCodeFrequency(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCodeFrequencyParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.CodeFrequencyStats | HttpResponse<models.CodeFrequencyStats> | HttpEvent<models.CodeFrequencyStats>> {
const path = `/repos/${args.owner}/${args.repo}/stats/code_frequency`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.CodeFrequencyStats>(`${this.domain}${path}`, options);
}
/**
* Get the last year of commit activity data.
* Returns the last year of commit activity grouped by week. The days array
* is a group of commits per day, starting on Sunday.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoStatsCommitActivity(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCommitActivityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.CommitActivityStats>;
getReposOwnerRepoStatsCommitActivity(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCommitActivityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.CommitActivityStats>>;
getReposOwnerRepoStatsCommitActivity(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCommitActivityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.CommitActivityStats>>;
getReposOwnerRepoStatsCommitActivity(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCommitActivityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.CommitActivityStats | HttpResponse<models.CommitActivityStats> | HttpEvent<models.CommitActivityStats>> {
const path = `/repos/${args.owner}/${args.repo}/stats/commit_activity`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.CommitActivityStats>(`${this.domain}${path}`, options);
}
/**
* Get contributors list with additions, deletions, and commit counts.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoStatsContributors(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsContributorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ContributorsStats>;
getReposOwnerRepoStatsContributors(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsContributorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ContributorsStats>>;
getReposOwnerRepoStatsContributors(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsContributorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ContributorsStats>>;
getReposOwnerRepoStatsContributors(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsContributorsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ContributorsStats | HttpResponse<models.ContributorsStats> | HttpEvent<models.ContributorsStats>> {
const path = `/repos/${args.owner}/${args.repo}/stats/contributors`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.ContributorsStats>(`${this.domain}${path}`, options);
}
/**
* Get the weekly commit count for the repo owner and everyone else.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoStatsParticipation(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsParticipationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ParticipationStats>;
getReposOwnerRepoStatsParticipation(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsParticipationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ParticipationStats>>;
getReposOwnerRepoStatsParticipation(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsParticipationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ParticipationStats>>;
getReposOwnerRepoStatsParticipation(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsParticipationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ParticipationStats | HttpResponse<models.ParticipationStats> | HttpEvent<models.ParticipationStats>> {
const path = `/repos/${args.owner}/${args.repo}/stats/participation`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.ParticipationStats>(`${this.domain}${path}`, options);
}
/**
* Get the number of commits per hour in each day.
* Each array contains the day number, hour number, and number of commits
* 0-6 Sunday - Saturday
* 0-23 Hour of day
* Number of commits
*
*
* For example, [2, 14, 25] indicates that there were 25 total commits, during
* the 2.00pm hour on Tuesdays. All times are based on the time zone of
* individual commits.
*
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoStatsPunchCard(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsPunchCardParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.CodeFrequencyStats>;
getReposOwnerRepoStatsPunchCard(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsPunchCardParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.CodeFrequencyStats>>;
getReposOwnerRepoStatsPunchCard(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsPunchCardParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.CodeFrequencyStats>>;
getReposOwnerRepoStatsPunchCard(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsPunchCardParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.CodeFrequencyStats | HttpResponse<models.CodeFrequencyStats> | HttpEvent<models.CodeFrequencyStats>> {
const path = `/repos/${args.owner}/${args.repo}/stats/punch_card`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.CodeFrequencyStats>(`${this.domain}${path}`, options);
}
/**
* List Statuses for a specific Ref.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoStatusesRef(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatusesRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Ref>;
getReposOwnerRepoStatusesRef(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatusesRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Ref>>;
getReposOwnerRepoStatusesRef(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatusesRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Ref>>;
getReposOwnerRepoStatusesRef(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatusesRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Ref | HttpResponse<models.Ref> | HttpEvent<models.Ref>> {
const path = `/repos/${args.owner}/${args.repo}/statuses/${args.ref}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Ref>(`${this.domain}${path}`, options);
}
/**
* Create a Status.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoStatusesRef(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoStatusesRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Ref>;
postReposOwnerRepoStatusesRef(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoStatusesRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Ref>>;
postReposOwnerRepoStatusesRef(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoStatusesRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Ref>>;
postReposOwnerRepoStatusesRef(
args: Exclude<ReposAPIClientInterface['postReposOwnerRepoStatusesRefParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Ref | HttpResponse<models.Ref> | HttpEvent<models.Ref>> {
const path = `/repos/${args.owner}/${args.repo}/statuses/${args.ref}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.post<models.Ref>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* List watchers.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoSubscribers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscribersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getReposOwnerRepoSubscribers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscribersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getReposOwnerRepoSubscribers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscribersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getReposOwnerRepoSubscribers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscribersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
const path = `/repos/${args.owner}/${args.repo}/subscribers`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Users>(`${this.domain}${path}`, options);
}
/**
* Delete a Repository Subscription.
* Response generated for [ 204 ] HTTP response code.
*/
deleteReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/subscription`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Get a Repository Subscription.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Subscribition>;
getReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Subscribition>>;
getReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Subscribition>>;
getReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Subscribition | HttpResponse<models.Subscribition> | HttpEvent<models.Subscribition>> {
const path = `/repos/${args.owner}/${args.repo}/subscription`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Subscribition>(`${this.domain}${path}`, options);
}
/**
* Set a Repository Subscription
* Response generated for [ 200 ] HTTP response code.
*/
putReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Subscribition>;
putReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Subscribition>>;
putReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Subscribition>>;
putReposOwnerRepoSubscription(
args: Exclude<ReposAPIClientInterface['putReposOwnerRepoSubscriptionParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Subscribition | HttpResponse<models.Subscribition> | HttpEvent<models.Subscribition>> {
const path = `/repos/${args.owner}/${args.repo}/subscription`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.put<models.Subscribition>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get list of tags.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoTags(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Tags>;
getReposOwnerRepoTags(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Tags>>;
getReposOwnerRepoTags(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Tags>>;
getReposOwnerRepoTags(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Tags | HttpResponse<models.Tags> | HttpEvent<models.Tags>> {
const path = `/repos/${args.owner}/${args.repo}/tags`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Tags>(`${this.domain}${path}`, options);
}
/**
* Get list of teams
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoTeams(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTeamsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Teams>;
getReposOwnerRepoTeams(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTeamsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Teams>>;
getReposOwnerRepoTeams(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTeamsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Teams>>;
getReposOwnerRepoTeams(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTeamsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Teams | HttpResponse<models.Teams> | HttpEvent<models.Teams>> {
const path = `/repos/${args.owner}/${args.repo}/teams`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Teams>(`${this.domain}${path}`, options);
}
/**
* List Stargazers. New implementation.
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoWatchers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoWatchersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getReposOwnerRepoWatchers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoWatchersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getReposOwnerRepoWatchers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoWatchersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getReposOwnerRepoWatchers(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoWatchersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
const path = `/repos/${args.owner}/${args.repo}/watchers`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<models.Users>(`${this.domain}${path}`, options);
}
/**
* Get archive link.
* This method will return a 302 to a URL to download a tarball or zipball
* archive for a repository. Please make sure your HTTP framework is
* configured to follow redirects or you will need to use the Location header
* to make a second GET request.
* Note: For private repositories, these links are temporary and expire quickly.
*
* Response generated for [ default ] HTTP response code.
*/
getReposOwnerRepoArchiveFormatPath(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoArchiveFormatPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getReposOwnerRepoArchiveFormatPath(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoArchiveFormatPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getReposOwnerRepoArchiveFormatPath(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoArchiveFormatPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getReposOwnerRepoArchiveFormatPath(
args: Exclude<ReposAPIClientInterface['getReposOwnerRepoArchiveFormatPathParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/repos/${args.owner}/${args.repo}/${args.archiveFormat}/${args.path}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('xGitHubMediaType' in args) {
options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType));
}
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
if ('xRateLimit' in args) {
options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit));
}
if ('xRateLimitRemaining' in args) {
options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining));
}
if ('xRateLimitReset' in args) {
options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset));
}
if ('xGitHubRequestId' in args) {
options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId));
}
return this.http.get<void>(`${this.domain}${path}`, options);
}
} | the_stack |
import * as _ from 'lodash';
import {
Component,
ElementRef,
EventEmitter,
Injector,
Input,
OnDestroy,
OnInit,
Output,
ViewChild
} from '@angular/core';
import {StringUtil} from '@common/util/string.util';
import {AbstractPopupComponent} from '@common/component/abstract-popup.component';
import {PageResult} from '@domain/common/page';
import {Dataconnection} from '@domain/dataconnection/dataconnection';
import {ConnectionType, DatasourceInfo} from '@domain/datasource/datasource';
import {DataconnectionService} from '@common/service/dataconnection.service';
import {ConnectionComponent, ConnectionValid} from '../../../../component/connection/connection.component';
/**
* Creating datasource with Database - connection step
*/
@Component({
selector: 'db-data-connection',
templateUrl: './db-set-data-connection.component.html'
})
export class DbSetDataConnectionComponent extends AbstractPopupComponent implements OnInit, OnDestroy {
// connection component
@ViewChild(ConnectionComponent, {static: true})
private readonly _connectionComponent: ConnectionComponent;
// create source data
private _sourceData: DatasourceInfo;
// connection preset list
public connectionPresetList: any[] = [{
name: this.translateService.instant('msg.storage.ui.user.input'),
default: true
}];
// selected connection preset
public selectedConnectionPreset: any;
@Input('sourceData')
public set setSourceData(sourceData: DatasourceInfo) {
this._sourceData = sourceData;
}
@Input()
public step: string;
@Output()
public stepChange: EventEmitter<string> = new EventEmitter();
// ingestion type list
public ingestionTypeList: any[];
// selected ingestion type
public selectedIngestionType: any;
// constructor
constructor(private dataconnectionService: DataconnectionService,
protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
}
/**
* ngOnInit
*/
public ngOnInit() {
// Init
super.ngOnInit();
// ui 초기화
this._initView();
// if exist connectionData, load connectionData
if (this._sourceData.hasOwnProperty('connectionData')) {
this._loadData(_.cloneDeep(this._sourceData.connectionData));
} else {
// get connection preset list
this._getDataConnectionPresetList();
this._connectionComponent.init();
}
}
/**
* ngOnDestroy
*/
public ngOnDestroy() {
// Destory
super.ngOnDestroy();
}
/**
* Next click event
*/
public next(): void {
// set click flag
if (this._connectionComponent.isEmptyConnectionValidation()) {
this._connectionComponent.setRequireCheckConnection();
}
// next enable validation
if (this._isEnableConnection()) {
// if exist connectionData
if (this._sourceData.hasOwnProperty('connectionData')) {
// if changed connectionData, delete databaseData, schemaData, ingestionData
if (this._isChangeConnection(this._sourceData.connectionData)) {
delete this._sourceData.databaseData;
delete this._sourceData.schemaData;
delete this._sourceData.ingestionData;
}
// if change ingestion type
else if (this._sourceData.connectionData.selectedIngestionType.value !== this.selectedIngestionType.value) {
delete this._sourceData.ingestionData;
}
// delete connectionData
delete this._sourceData.connectionData;
}
// save connectionData
this._saveConnectionData(this._sourceData);
// move to next step
this.step = 'db-select-data';
this.stepChange.emit(this.step);
}
}
/**
* Get selectedConnectionPreset index in connectionPreset list
* @returns {number}
*/
public getConnectionDefaultIndex(): number {
// 커넥션 있을때만 작동
return this.selectedConnectionPreset && this.selectedConnectionPreset.id
? this.connectionPresetList.findIndex((item) => {
return item.id === this.selectedConnectionPreset.id;
})
: 0;
}
/**
* Change ingestion type click event
* @param type
*/
public onChangeIngestionType(type: any): void {
this.selectedIngestionType = type;
this._sourceData.connType = type.value;
}
/**
* Change connection preset click event
* @param preset
*/
public onSelectedConnectionPreset(preset): void {
// change selected connection preset
this.selectedConnectionPreset = preset;
// if exist preset id
if (!this.selectedConnectionPreset.default) {
// get connection data in preset
this._getConnectionPresetDetailData();
} else {
this._connectionComponent.properties = [];
}
}
/**
* Preset list scroll event
* @param pageNum
*/
public onScrollPage(pageNum): void {
// if remain next page
if (this._isMorePage()) {
// save pageResult
this.pageResult.number = pageNum;
// get more preset list
this._getDataConnectionPresetList();
}
}
/**
* Is more next page
* @returns {boolean}
* @private
*/
private _isMorePage(): boolean {
return (this.pageResult.number < this.pageResult.totalPages - 1);
}
/**
* Is change connection data
* @param data
* @returns {boolean}
* @private
*/
private _isChangeConnection(data: any): boolean {
const connection = this._connectionComponent.getConnectionParams();
// implementor type
if (data.connection.implementor !== connection.implementor) {
return true;
}
// if used url
if (StringUtil.isEmpty(data.connection.url) !== StringUtil.isEmpty(connection.url)) {
return true;
}
// hostname
if (data.connection.hostname !== connection.hostname) {
return true;
}
// port
if (data.connection.port !== connection.port) {
return true;
}
// url
if (data.connection.url !== connection.url) {
return true;
}
// database
if (data.connection.database !== connection.database) {
return true;
}
// catalog
if (data.connection.catalog !== connection.catalog) {
return true;
}
// sid
if (data.connection.sid !== connection.sid) {
return true;
}
// if change authentication type
if (data.connection.authenticationType !== connection.authenticationType) {
return true;
}
// if change username
if (data.connection.username !== connection.username) {
return true;
}
// if change password
if (data.connection.password !== connection.password) {
return true;
}
return false;
}
/**
* Is enable connection
* @return {boolean}
* @private
*/
private _isEnableConnection(): boolean {
// check valid connection
if (!this._connectionComponent.isEnableConnection()) {
// #1990 scroll into invalid input
this._connectionComponent.scrollIntoConnectionInvalidInput();
return false;
} else {
return true;
}
}
/**
* Get connection preset list
* @private
*/
private _getDataConnectionPresetList(): void {
// loading show
this.loadingShow();
// get connection preset list
this.dataconnectionService.getAllDataconnections(this._getConnectionPresetListParams(this.pageResult), 'forSimpleListView')
.then((result) => {
// if exist preset list
if (result['_embedded']) {
this.connectionPresetList = this.connectionPresetList.concat(result['_embedded'].connections);
}
// page
this.pageResult = result['page'];
// loading hide
this.loadingHide();
})
.catch(error => this.commonExceptionHandler(error));
}
/**
* Get connection data in preset
* @private
*/
private _getConnectionPresetDetailData(): void {
// loading show
this.loadingShow();
// get connection data in preset
this.dataconnectionService.getDataconnectionDetail(this.selectedConnectionPreset.id)
.then((connection: Dataconnection) => {
// loading hide
this.loadingHide();
this._connectionComponent.init(connection);
})
.catch(error => this.commonExceptionHandler(error));
}
/**
* Get parameter for connection preset list
* @param {PageResult} pageResult
* @returns {Object}
* @private
*/
private _getConnectionPresetListParams(pageResult: PageResult): object {
return {
size: pageResult.size,
page: pageResult.number,
type: 'jdbc'
};
}
/**
* 현재 페이지의 커넥션 데이터 저장
* @param {DatasourceInfo} sourceData
* @private
*/
private _saveConnectionData(sourceData: DatasourceInfo) {
sourceData['connectionData'] = {
connectionPresetList: this.connectionPresetList,
selectedConnectionPreset: this.selectedConnectionPreset,
selectedIngestionType: this.selectedIngestionType,
pageResult: this.pageResult,
// input
connection: this._connectionComponent.getConnectionParams(true),
};
}
/**
* ui init
* @private
*/
private _initView() {
// 선택한 프리셋
this.selectedConnectionPreset = this.connectionPresetList[0];
// ingestion 타입 목록
this.ingestionTypeList = [
{label: this.translateService.instant('msg.storage.ui.list.ingested.data'), value: ConnectionType.ENGINE},
{label: this.translateService.instant('msg.storage.ui.list.linked.data'), value: ConnectionType.LINK}
];
// 선택한 ingestion 타입 목록
this.selectedIngestionType = this.ingestionTypeList[0];
// page result
this.pageResult.number = 0;
this.pageResult.size = 20;
}
/**
* load connection data
* @param connectionData
* @private
*/
private _loadData(connectionData: any) {
this.connectionPresetList = connectionData.connectionPresetList;
this.selectedConnectionPreset = connectionData.selectedConnectionPreset;
this.selectedIngestionType = connectionData.selectedIngestionType;
this.pageResult = connectionData.pageResult;
// input init
this._connectionComponent.init(connectionData.connection);
this._connectionComponent.connectionValidation = ConnectionValid.ENABLE_CONNECTION;
}
} | the_stack |
export interface Format {
/**
* Whether or not this is a known format (ie.e. not automatically created)
*/
known: boolean
/**
* The lowercase name of the format e.g. `md`, `docx`, `dockerfile`
*/
name: string
/**
* Whether or not the format should be considered binary e.g. not to be displayed in a text / code editor
*/
binary: boolean
/**
* Whether HTML previews are normally supported for documents of this format. See also `Document.previewable` which indicates whether a HTML preview is supported for a particular document.
*/
preview: boolean
/**
* Any additional extensions (other than it's name) that this format should match against.
*/
extensions: string[]
}
export type Kernel =
| {
type: 'Default'
}
| {
type: 'Calc'
}
/**
* An in-memory representation of a document
*/
export interface Document {
/**
* The document identifier
*/
id: string
/**
* The absolute path of the document's file.
*/
path: string
/**
* The project directory for this document.
*
* Used to restrict file links (e.g. image paths) to within the project for both security and reproducibility reasons. For documents opened from within a project, this will be project directory. For "orphan" documents (opened by themselves) this will be the parent directory of the document. When the document is compiled, an error will be returned if a file link is outside of the root.
*/
project: string
/**
* Whether or not the document's file is in the temporary directory.
*/
temporary: boolean
/**
* The synchronization status of the document. This is orthogonal to `temporary` because a document's `content` can be synced or un-synced with the file system regardless of whether or not its `path` is temporary..
*/
status: 'synced' | 'unwritten' | 'unread' | 'deleted'
/**
* The name of the document
*
* Usually the filename from the `path` but "Untitled" for temporary documents.
*/
name: string
/**
* The format of the document.
*
* On initialization, this is inferred, if possible, from the file name extension of the document's `path`. However, it may change whilst the document is open in memory (e.g. if the `load` function sets a different format).
*/
format: Format
/**
* Whether a HTML preview of the document is supported
*
* This is determined by the type of the `root` node of the document. Will be `true` if the `root` is a type for which HTML previews are implemented e.g. `Article`, `ImageObject` and `false` if the `root` is `None`, or of some other type e.g. `Entity`.
*
* This flag is intended for dynamically determining whether to open a preview panel for a document by default. Regardless of its value, a user should be able to open a preview panel, in HTML or some other format, for any document.
*/
previewable: boolean
/**
* Addresses of nodes in `root` that have an `id`
*
* Used to fetch a particular node (and do something with it like `patch` or `execute` it) rather than walking the node tree looking for it. It is necessary to use [`Address`] here (rather than say raw pointers) because pointers or references will change as the document is patched. These addresses are shifted when the document is patched to account for this.
*/
addresses: Record<string, Address>
/**
* The set of relations between this document, or nodes in this document, and other resources.
*
* Relations may be external (e.g. this document links to another file) or internal (e.g. the second code chunk uses a variable defined in the first code chunk).
*/
relations?: Record<string, [Relation, Resource]>
/**
* Keeping track of client ids per topics allows for a some optimizations. For example, events will only be published on topics that have at least one subscriber.
*
* Valid subscription topics are the names of the `DocumentEvent` types:
*
* - `removed`: published when document file is deleted - `renamed`: published when document file is renamed - `modified`: published when document file is modified - `encoded:<format>` published when a document's content is changed internally or externally and conversions have been completed e.g. `encoded:html`
*/
subscriptions: {
[k: string]: string[]
}
/**
* The kernels in the document kernel space
*/
kernels: {
[k: string]: Kernel
}
/**
* The symbols in the document kernel space
*/
symbols: {
[k: string]: SymbolInfo
}
}
export interface SymbolInfo {
/**
* The type of the object that the symbol refers to (e.g `Number`, `Function`)
*
* Should be used as a hint only, to the underlying, native type of the symbol.
*/
kind: string
/**
* The home kernel of the symbol
*
* The home kernel of a symbol is the kernel that it was last assigned in. As such, a symbol's home kernel can change, although this is discouraged.
*/
home: string
/**
* The time that the symbol was last assigned in the home kernel
*
* A symbol is considered assigned when a `CodeChunk` with an `Assign` relation to the symbol is executed or the `kernel.set` method is called.
*/
assigned: string
/**
* A timestamp is recorded for each time that a symbol is mirrored to another kernel. This allows unnecessary mirroring to be avoided if the symbol has not been assigned since it was last mirrored to that kernel.
*/
mirrored: {
[k: string]: string
}
}
export interface DocumentEvent {
/**
* The type of event
*/
type: 'deleted' | 'renamed' | 'modified' | 'patched' | 'encoded'
/**
* The document associated with the event
*/
document: Document
/**
* The content associated with the event, only provided for, `modified` and `encoded` events.
*/
content?: string
/**
* The format of the document, only provided for `modified` (the format of the document) and `encoded` events (the format of the encoding).
*/
format?: Format
/**
* The `DomPatch` associated with a `Patched` event
*/
patch?: DomPatch
}
export type PatchesSchema =
| {
Slot: Slot
}
| {
Address: Address
}
| {
Patch: Patch
}
| {
Operation: Operation
}
| {
DomPatch: DomPatch
}
| {
DomOperation: DomOperation
}
/**
* A slot, used as part of an [`Address`], to locate a value within a `Node` tree.
*
* Slots can be used to identify a part of a larger object.
*
* The `Name` variant can be used to identify:
*
* - the property name of a `struct` - the key of a `HashMap<String, ...>`
*
* The `Integer` variant can be used to identify:
*
* - the index of a `Vec` - the index of a Unicode character in a `String`
*
* The `None` variant is used in places where a `Slot` is required but none applies to the particular type or use case.
*
* In contrast to JSON Patch, which uses a [JSON Pointer](http://tools.ietf.org/html/rfc6901) to describe the location of additions and removals, slots offer improved performance and type safety.
*/
export type Slot = number | string
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
export type Address = Slot[]
/**
* The operations that can be used in a patch to mutate one node into another.
*
* These are the same operations as described in [JSON Patch](http://jsonpatch.com/) (with the exception of `copy` and `test`). Note that `Replace` and `Move` could be represented by combinations of `Remove` and `Add`. They are included as a means of providing more semantically meaningful patches, and more space efficient serializations (e.g. it is not necessary to represent the value being moved or copied).
*
* In addition, there is a `Transform` operation which can be used describe the transformation of a node to another type, having a similar structure. Examples includes:
*
* - a `String` to an `Emphasis` - a `Paragraph` to a `QuoteBlock` - a `CodeChunk` to a `CodeBlock`
*
* The `length` field on `Add` and `Replace` is not necessary for applying operations, but is useful for generating them and for determining if there are conflicts between two patches without having to downcast the `value`.
*
* Note that for `String`s the integers in `address`, `items` and `length` all refer to Unicode characters not bytes.
*/
export type Operation = OperationAdd | OperationRemove | OperationReplace | OperationMove | OperationTransform
/**
* A DOM operation used to mutate the DOM.
*
* A `DomOperation` is the DOM version of an [`Operation`]. The same names for operation variants and their properties are used with the following exception:
*
* - the `value` property of `Add` and `Replace` is replaced by `html`, a HTML string representing the node (usually a HTML `Element` or `Text` node), and `json`, a JSON representation of the node (used for updating WebComponents).
*
* - the `length` property of `Add` and `Replace` is not included because it is not needed (for merge conflict resolution as it is in `Operation`).
*/
export type DomOperation =
| DomOperationAdd
| DomOperationRemove
| DomOperationReplace
| DomOperationMove
| DomOperationTransform
/**
* A set of [`Operation`]s
*/
export interface Patch {
/**
* The [`Operation`]s to apply
*/
ops: Operation[]
/**
* The id of the node to which to apply this patch
*/
target?: string
/**
* The id of the actor that generated this patch e.g. a web browser client, or file watcher
*/
actor?: string
}
/**
* Add a value
*/
export interface OperationAdd {
type: 'Add'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
address: Slot[]
/**
* The value to add
*/
value: any
/**
* The number of items added
*/
length: number
}
/**
* Remove one or more values
*/
export interface OperationRemove {
type: 'Remove'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
address: Slot[]
/**
* The number of items to remove
*/
items: number
}
/**
* Replace one or more values
*/
export interface OperationReplace {
type: 'Replace'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
address: Slot[]
/**
* The number of items to replace
*/
items: number
/**
* The replacement value
*/
value: any
/**
* The number of items added
*/
length: number
}
/**
* Move a value from one address to another
*/
export interface OperationMove {
type: 'Move'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
from: Slot[]
/**
* The number of items to move
*/
items: number
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
to: Slot[]
}
/**
* Transform a value from one type to another
*/
export interface OperationTransform {
type: 'Transform'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
address: Slot[]
/**
* The type of `Node` to transform from
*/
from: string
/**
* The type of `Node` to transform to
*/
to: string
}
/**
* A set of [`DomOperation`]s to be applied to some DOM element
*/
export interface DomPatch {
/**
* The [`DomOperation`]s to apply
*/
ops: DomOperation[]
/**
* The id of the node to which to apply this patch
*/
target?: string
/**
* The id of the actor that generated this patch e.g. a web browser client, or file watcher
*/
actor?: string
}
/**
* Add one or more DOM nodes
*/
export interface DomOperationAdd {
type: 'Add'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
address: Slot[]
/**
* The HTML to add
*/
html: string
/**
* The JSON value to add
*/
json: {
[k: string]: unknown
}
}
/**
* Remove one or more DOM nodes
*/
export interface DomOperationRemove {
type: 'Remove'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
address: Slot[]
/**
* The number of items to remove
*/
items: number
}
/**
* Replace one or more DOM nodes
*/
export interface DomOperationReplace {
type: 'Replace'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
address: Slot[]
/**
* The number of items to replace
*/
items: number
/**
* The replacement HTML
*/
html: string
/**
* The JSON value to replace
*/
json: {
[k: string]: unknown
}
}
/**
* Move a DOM node from one address to another
*/
export interface DomOperationMove {
type: 'Move'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
from: Slot[]
/**
* The number of items to move
*/
items: number
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
to: Slot[]
}
/**
* Transform a DOM node from one type to another
*/
export interface DomOperationTransform {
type: 'Transform'
/**
* The address, defined by a list of [`Slot`]s, of a value within `Node` tree.
*
* Implemented as a double-ended queue. Given that addresses usually have less than six slots it may be more performant to use a stack allocated `tinyvec` here instead.
*
* Note: This could instead have be called a "Path", but that name was avoided because of potential confusion with file system paths.
*/
address: Slot[]
/**
* The type of `Node` to transform from
*/
from: string
/**
* The type of `Node` to transform to
*/
to: string
}
/**
* An implementation, and extension, of schema.org [`Project`](https://schema.org/Project). Uses schema.org properties where possible but adds extension properties where needed (e.g. `theme`).
*/
export interface Project {
/**
* The name of the project
*/
name?: string
/**
* A description of the project
*/
description?: string
/**
* The path (within the project) of the project's image
*
* If not specified, will default to the most recently modified image in the project (if any).
*/
image?: string
/**
* The path (within the project) of the project's main file
*
* If not specified, will default to the first file matching the the regular expression in the configuration settings.
*/
main?: string
/**
* The default theme to use when viewing documents in this project
*
* If not specified, will default to the default theme in the configuration settings.
*/
theme?: string
/**
* A list of project sources and their destination within the project
*/
sources?: SourceDestination[]
/**
* A list of file conversions
*/
conversions?: Conversion[]
/**
* Glob patterns for paths to be excluded from file watching
*
* As a performance optimization, paths that match these patterns are excluded from file watching updates. If not specified, will default to the patterns in the configuration settings.
*/
watchExcludePatterns?: string[]
/**
* The filesystem path of the project folder
*/
path: string
/**
* The resolved path of the project's image file
*/
imagePath?: string
/**
* The resolved path of the project's main file
*/
mainPath?: string
/**
* The files in the project folder
*/
files: Record<string, File>
/**
* The project's dependency graph
*/
graph: Graph
}
/**
* The definition of a conversion between files within a project
*/
export interface Conversion {
/**
* The path of the input document
*/
input?: string
/**
* The path of the output document
*/
output?: string
/**
* The format of the input (defaults to being inferred from the file extension of the input)
*/
from?: string
/**
* The format of the output (defaults to being inferred from the file extension of the output)
*/
to?: string
/**
* Whether or not the conversion is active
*/
active?: boolean
}
export interface ProjectEvent {
/**
* The project associated with the event
*/
project: Project
/**
* The type of event
*/
type: 'updated'
}
/**
* A file or directory within a `Project`
*/
export interface File {
/**
* The absolute path of the file or directory
*/
path: string
/**
* The name of the file or directory
*/
name: string
/**
* Time that the file was last modified (Unix Epoch timestamp)
*/
modified?: number
/**
* Size of the file in bytes
*/
size?: number
/**
* Format of the file
*
* Usually this is the lower cased filename extension (if any) but may also be normalized. May be more convenient, and usually more available, than the `media_type` property.
*/
format: Format
/**
* The parent `File`, if any
*/
parent?: string
/**
* If a directory, a list of the canonical paths of the files within it. Otherwise, `None`.
*
* A `BTreeSet` rather than a `Vec` so that paths are ordered without having to be resorted after insertions. Another option is `BinaryHeap` but `BinaryHeap::retain` is only on nightly and so is awkward to use.
*/
children?: string[]
}
/**
* These events published under the `projects:<project-path>:files` topic.
*/
export interface FileEvent {
/**
* The path of the project (absolute)
*/
project: string
/**
* The path of the file (absolute)
*
* For `renamed` events this is the _old_ path.
*/
path: string
/**
* The type of event e.g. `Refreshed`, `Modified`, `Created`
*
* A `refreshed` event is emitted when the entire set of files is updated.
*/
type: 'refreshed' | 'created' | 'removed' | 'renamed' | 'modified'
/**
* The updated file
*
* Will be `None` for for `refreshed` and `removed` events, or if for some reason it was not possible to fetch metadata about the file.
*/
file?: File
/**
* The updated set of files in the project
*
* Represents the new state of the file tree after the event including updated `parent` and `children` properties of files affects by the event.
*/
files: Record<string, File>
}
/**
* A resource in a dependency graph (the nodes of the graph)
*/
export type Resource =
| {
type: 'Symbol'
/**
* The path of the file that the symbol is defined in
*/
path: string
/**
* The name/identifier of the symbol
*/
name: string
/**
* The type of the object that the symbol refers to (e.g `Number`, `Function`)
*
* Should be used as a hint only, and as such is excluded from equality and hash functions.
*/
kind: string
}
| {
type: 'Node'
/**
* The path of the file that the node is defined in
*/
path: string
/**
* The id of the node with the document
*/
id: string
/**
* The type of node e.g. `Parameter`, `CodeChunk`
*/
kind: string
}
| {
type: 'File'
/**
* The path of the file
*/
path: string
}
| {
type: 'Source'
/**
* The name of the project source
*/
name: string
}
| {
type: 'Module'
/**
* The programming language of the module
*/
language: string
/**
* The name of the module
*/
name: string
}
| {
type: 'Url'
/**
* The URL of the external resource
*/
url: string
}
/**
* The relation between two resources in a dependency graph (the edges of the graph)
*
* Some relations carry additional information such whether the relation is active (`Import` and `Convert`) or the range that they occur in code (`Assign`, `Use`, `Read`) etc
*/
export type Relation =
| {
type: 'Assign'
/**
* The range within code that the assignment is done
*/
range: [number, number, number, number]
}
| {
type: 'Convert'
/**
* Whether or not the conversion is automatically updated
*/
auto: boolean
}
| {
type: 'Embed'
[k: string]: unknown
}
| {
type: 'Import'
/**
* Whether or not the import is automatically updated
*/
auto: boolean
}
| {
type: 'Include'
[k: string]: unknown
}
| {
type: 'Link'
[k: string]: unknown
}
| {
type: 'Read'
/**
* The range within code that the read is declared
*/
range: [number, number, number, number]
}
| {
type: 'Use'
/**
* The range within code that the use is declared
*/
range: [number, number, number, number]
}
| {
type: 'Write'
/**
* The range within code that the write is declared
*/
range: [number, number, number, number]
}
/**
* A subject-relation-object triple
*/
export type Triple = [Resource, Relation, Resource]
/**
* A project dependency graph
*/
export interface Graph {
/**
* The resources in the graph
*/
nodes: Resource[]
/**
* The relations between resources in the graph
*/
edges: {
from: 'integer'
to: 'integer'
relation: Resource
}[]
}
export interface GraphEvent {
/**
* The path of the project (absolute)
*/
project: string
/**
* The type of event
*/
type: 'updated'
/**
* The graph at the time of the event
*/
graph: Graph
}
/**
* A session
*/
export interface Session {
/**
* The id of the session
*/
id: string
/**
* The id of the project that this session is for
*/
project: string
/**
* The id of the snapshot that this session is for
*/
snapshot: string
/**
* This is an optimization to avoid collecting session metrics and / or publishing events if there are no clients subscribed.
*/
subscriptions: {
[k: string]: string[]
}
/**
* The status of the session
*/
status: 'Pending' | 'Starting' | 'Started' | 'Stopping' | 'Stopped'
}
/**
* A session event
*/
export type SessionEvent =
| {
type: 'Updated'
session: Session
}
| {
type: 'Heartbeat'
session: Session
}
/**
* Each source by destination combination should be unique to a project. It is possible to have the same source being imported to multiple destinations within a project and for multiple sources to used the same destination (e.g. the root directory of the project).
*/
export interface SourceDestination {
/**
* The source from which files will be imported
*/
source?:
| {
type: 'Null'
}
| {
type: 'Elife'
/**
* Number of the article
*/
article: number
}
| {
type: 'GitHub'
/**
* Owner of the repository
*/
owner: string
/**
* Name of the repository
*/
name: string
/**
* Path within the repository
*/
path?: string
}
/**
* The destination path within the project
*/
destination?: string
/**
* Whether or not the source is active
*
* If the source is active an import job will be created for it each time the project is updated.
*/
active?: boolean
/**
* A list of file paths currently associated with the source, relative to the project root
*/
files?: string[]
}
/**
* As far as possible using existing properties defined in schema.org [`SoftwareApplication`](https://schema.org/SoftwareApplication) but extensions added where necessary.
*/
export interface Plugin {
/**
* The name of the plugin
*/
name: string
/**
* The version of the plugin
*/
softwareVersion: string
/**
* A description of the plugin
*/
description: string
/**
* URL of the image to be used when displaying the plugin
*/
image?: string
/**
* A list of URLS that the plugin can be installed from
*/
installUrl: string[]
/**
* A list of plugin "features" Each feature is a `JSONSchema` object describing a method (including its parameters).
*/
featureList: true[]
/**
* If the plugin is installed, the installation type
*/
installation?: 'docker' | 'binary' | 'javascript' | 'python' | 'r' | 'link'
/**
* The last time that the plugin manifest was updated. Used to determine if a refresh is necessary.
*/
refreshed?: string
/**
* The next version of the plugin, if any.
*
* If the plugin is installed and there is a newer version of the plugin then this property should be set at the time of refresh.
*/
next?: Plugin
/**
* The current alias for this plugin, if any
*/
alias?: string
}
/**
* Plugin installation method
*
* Which method to use to install a plugin.
*/
export type PluginInstallation = 'docker' | 'binary' | 'javascript' | 'python' | 'r' | 'link'
export interface Config {
/**
* Configuration settings for project defaults
*/
projects?: {
/**
* Patterns used to infer the main file of projects
*
* For projects that do not specify a main file, each file is tested against these case insensitive patterns in order. The first file (alphabetically) that matches is the project's main file.
*/
mainPatterns?: string[]
/**
* Default project theme
*
* Will be applied to all projects that do not specify a theme
*/
theme?: string
/**
* Default glob patterns for paths to be excluded from file watching
*
* Used for projects that do not specify their own watch exclude patterns. As a performance optimization, paths that match these patterns are excluded from file watching updates. The default list includes common directories that often have many files that are often updated.
*/
watchExcludePatterns?: string[]
}
/**
* Configuration settings for logging
*/
logging?: {
/**
* Configuration settings for log entries printed to stderr when using the CLI
*/
stderr?: {
/**
* The maximum log level to emit
*/
level?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'never'
/**
* The format for the logs entries
*/
format?: 'simple' | 'detail' | 'json'
}
/**
* Configuration settings for log entries shown to the user in the desktop
*/
desktop?: {
/**
* The maximum log level to emit
*/
level?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'never'
}
/**
* Configuration settings for logs entries written to file
*/
file?: {
/**
* The path of the log file
*/
path?: string
/**
* The maximum log level to emit
*/
level?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'never'
}
}
/**
* Configuration settings for telemetry
*/
telemetry?: {
/**
* Telemetry settings for Stencila CLI
*/
cli?: {
/**
* Whether to send error reports. Default is false.
*/
error_reports?: boolean
}
/**
* Telemetry settings for Stencila Desktop
*/
desktop?: {
/**
* Whether to send error reports. Default is false.
*/
error_reports?: boolean
}
}
/**
* Configuration settings for running as a server
*/
serve?: {
/**
* The URL to serve on (defaults to `ws://127.0.0.1:9000`)
*/
url?: string
/**
* Secret key to use for signing and verifying JSON Web Tokens
*/
key?: string
/**
* Do not require a JSON Web Token to access the server
*/
insecure?: boolean
}
/**
* Configuration settings for plugin installation and management
*/
plugins?: {
/**
* The order of preference of plugin installation method.
*/
installations?: PluginInstallation[]
/**
* The local plugin aliases that extends and/or override those in the global aliases at <https://github.com/stencila/stencila/blob/master/plugins.json>
*/
aliases?: {
[k: string]: string
}
}
/**
* Configuration settings for installation and management of third party binaries
*/
binaries?: {
/**
* Whether binaries should be automatically installed when they are required
*/
auto?: boolean
}
/**
* Configuration settings for document editors.
*/
editors?: {
/**
* Default format for new documents
*/
defaultFormat?: string
/**
* Show line numbers
*/
lineNumbers?: boolean
/**
* Enable wrapping of lines
*/
lineWrapping?: boolean
}
/**
* Configuration settings used when upgrading the application (and optionally plugins) automatically, in the background. These settings are NOT used as defaults when using the CLI `upgrade` command directly.
*/
upgrade?: {
/**
* Plugins should also be upgraded to latest version
*/
plugins?: boolean
/**
* Prompt to confirm an upgrade
*/
confirm?: boolean
/**
* Show information on the upgrade process
*/
verbose?: boolean
/**
* The interval between automatic upgrade checks (defaults to "1 day"). Only used when for configuration. Set to "off" for no automatic checks.
*/
auto?: string
}
}
/**
* An event associated with changes to the configuration
*/
export interface ConfigEvent {
/**
* The type of event
*/
type: 'set' | 'reset'
/**
* The configuration at the time of the event
*/
config: Config
}
/**
* An enumeration of custom errors returned by this library
*
* Where possible functions should return one of these errors to provide greater context to the user, in particular regarding actions that can be taken to resolve the error.
*/
export type Error =
| {
type: 'InvalidUUID'
family: string
id: string
message: string
}
| {
type: 'NotSame'
message: string
[k: string]: unknown
}
| {
type: 'NotEqual'
message: string
[k: string]: unknown
}
| {
type: 'UnpointableType'
address: Address
type_name: string
message: string
}
| {
type: 'InvalidAddress'
address: Address
type_name: string
message: string
}
| {
type: 'InvalidPatchOperation'
op: string
type_name: string
message: string
}
| {
type: 'InvalidPatchAddress'
address: string
type_name: string
message: string
}
| {
type: 'InvalidPatchValue'
type_name: string
message: string
}
| {
type: 'InvalidSlotVariant'
variant: string
type_name: string
message: string
}
| {
type: 'InvalidSlotName'
name: string
type_name: string
message: string
}
| {
type: 'InvalidSlotIndex'
index: number
type_name: string
message: string
}
| {
type: 'UnknownFormat'
format: string
message: string
}
| {
type: 'IncompatibleLanguage'
language: string
kernel_type: string
message: string
}
| {
type: 'UndelegatableMethod'
method: Method
message: string
}
| {
type: 'UndelegatableCall'
method: Method
params: {
[k: string]: unknown
}
message: string
}
| {
type: 'PluginNotInstalled'
plugin: string
message: string
}
| {
type: 'Unspecified'
message: string
}
/**
* An enumeration of all methods
*/
export type Method = 'import' | 'export' | 'decode' | 'encode' | 'coerce' | 'reshape' | 'compile' | 'build' | 'execute'
export const FORMATS: Record<string, Format> = {
"3gp": {
"known": true,
"name": "3gp",
"binary": true,
"preview": true,
"extensions": []
},
"dir": {
"known": true,
"name": "dir",
"binary": true,
"preview": false,
"extensions": []
},
"dockerfile": {
"known": true,
"name": "dockerfile",
"binary": false,
"preview": false,
"extensions": []
},
"docx": {
"known": true,
"name": "docx",
"binary": true,
"preview": true,
"extensions": []
},
"flac": {
"known": true,
"name": "flac",
"binary": true,
"preview": true,
"extensions": []
},
"gif": {
"known": true,
"name": "gif",
"binary": true,
"preview": true,
"extensions": []
},
"html": {
"known": true,
"name": "html",
"binary": false,
"preview": true,
"extensions": []
},
"ipynb": {
"known": true,
"name": "ipynb",
"binary": false,
"preview": true,
"extensions": []
},
"jpg": {
"known": true,
"name": "jpg",
"binary": true,
"preview": true,
"extensions": [
"jpeg"
]
},
"js": {
"known": true,
"name": "js",
"binary": false,
"preview": false,
"extensions": []
},
"json": {
"known": true,
"name": "json",
"binary": false,
"preview": true,
"extensions": []
},
"json5": {
"known": true,
"name": "json5",
"binary": false,
"preview": true,
"extensions": []
},
"latex": {
"known": true,
"name": "latex",
"binary": false,
"preview": true,
"extensions": [
"tex"
]
},
"makefile": {
"known": true,
"name": "makefile",
"binary": false,
"preview": false,
"extensions": []
},
"md": {
"known": true,
"name": "md",
"binary": false,
"preview": true,
"extensions": []
},
"mp3": {
"known": true,
"name": "mp3",
"binary": true,
"preview": true,
"extensions": []
},
"mp4": {
"known": true,
"name": "mp4",
"binary": true,
"preview": true,
"extensions": []
},
"odt": {
"known": true,
"name": "odt",
"binary": true,
"preview": true,
"extensions": []
},
"ogg": {
"known": true,
"name": "ogg",
"binary": true,
"preview": true,
"extensions": []
},
"ogv": {
"known": true,
"name": "ogv",
"binary": true,
"preview": true,
"extensions": []
},
"png": {
"known": true,
"name": "png",
"binary": true,
"preview": true,
"extensions": []
},
"py": {
"known": true,
"name": "py",
"binary": false,
"preview": false,
"extensions": []
},
"r": {
"known": true,
"name": "r",
"binary": false,
"preview": false,
"extensions": []
},
"rmd": {
"known": true,
"name": "rmd",
"binary": false,
"preview": true,
"extensions": []
},
"rpng": {
"known": true,
"name": "rpng",
"binary": true,
"preview": true,
"extensions": []
},
"sh": {
"known": true,
"name": "sh",
"binary": false,
"preview": false,
"extensions": []
},
"toml": {
"known": true,
"name": "toml",
"binary": false,
"preview": true,
"extensions": []
},
"ts": {
"known": true,
"name": "ts",
"binary": false,
"preview": false,
"extensions": []
},
"txt": {
"known": true,
"name": "txt",
"binary": false,
"preview": false,
"extensions": []
},
"webm": {
"known": true,
"name": "webm",
"binary": true,
"preview": true,
"extensions": []
},
"xml": {
"known": true,
"name": "xml",
"binary": false,
"preview": true,
"extensions": []
},
"yaml": {
"known": true,
"name": "yaml",
"binary": false,
"preview": true,
"extensions": []
}
} | the_stack |
import test, { ExecutionContext } from 'ava';
import {
buildAdClick,
buildAdConversion,
buildAddToCart,
buildAdImpression,
buildConsentGranted,
buildConsentWithdrawn,
buildEcommerceTransaction,
buildEcommerceTransactionItem,
buildFormFocusOrChange,
buildFormSubmission,
buildLinkClick,
buildPagePing,
buildPageView,
buildRemoveFromCart,
buildScreenView,
buildSelfDescribingEvent,
buildSiteSearch,
buildSocialInteraction,
buildStructEvent,
trackerCore,
} from '../src/core';
import { Payload } from '../src/payload';
const selfDescribingEventSchema = 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0';
let beforeCount = 0,
afterCount = 0;
const tracker = trackerCore({
base64: false,
corePlugins: [{ beforeTrack: () => (beforeCount += 1), afterTrack: () => (afterCount += 1) }],
});
function compare(result: Payload, expected: Payload, t: ExecutionContext) {
t.truthy(result['eid'], 'A UUID should be attached to all events');
delete result['eid'];
t.truthy(result['dtm'], 'A timestamp should be attached to all events');
delete result['dtm'];
t.deepEqual(result, expected);
}
test('should track a page view', (t) => {
const pageUrl = 'http://www.example.com';
const pageTitle = 'title page';
const referrer = 'https://www.google.com';
const expected = {
e: 'pv',
url: pageUrl,
page: pageTitle,
refr: referrer,
};
compare(tracker.track(buildPageView({ pageUrl, pageTitle, referrer })), expected, t);
});
test('should track a page ping', (t) => {
const pageUrl = 'http://www.example.com';
const pageTitle = 'title page';
const referrer = 'http://www.google.com';
const expected = {
e: 'pp',
page: pageTitle,
url: pageUrl,
refr: referrer,
pp_mix: '1',
pp_max: '2',
pp_miy: '3',
pp_may: '4',
};
compare(
tracker.track(
buildPagePing({ pageUrl, pageTitle, referrer, minXOffset: 1, maxXOffset: 2, minYOffset: 3, maxYOffset: 4 })
),
expected,
t
);
});
test('should track a structured event', (t) => {
const expected = {
e: 'se',
se_ca: 'cat',
se_ac: 'act',
se_la: 'lab',
se_pr: 'prop',
se_va: '1',
};
compare(
tracker.track(buildStructEvent({ category: 'cat', action: 'act', label: 'lab', property: 'prop', value: 1 })),
expected,
t
);
});
test('should track an ecommerce transaction event', (t) => {
const orderId = 'ak0008';
const affiliation = '1234';
const total = 50;
const tax = 6;
const shipping = 0;
const city = 'Phoenix';
const state = 'Arizona';
const country = 'USA';
const currency = 'USD';
const expected = {
e: 'tr',
tr_af: affiliation,
tr_id: orderId,
tr_tt: total,
tr_tx: tax,
tr_sh: shipping,
tr_ci: city,
tr_st: state,
tr_co: country,
tr_cu: currency,
};
compare(
tracker.track(
buildEcommerceTransaction({
orderId,
total,
affiliation,
tax,
shipping,
city,
state,
country,
currency,
})
),
expected,
t
);
});
test('should track an ecommerce transaction item event', (t) => {
const orderId = 'ak0008';
const sku = '4q345';
const price = 17.0;
const quantity = 2;
const name = 'red shoes';
const category = 'clothing';
const currency = 'USD';
const expected = {
e: 'ti',
ti_id: orderId,
ti_sk: sku,
ti_nm: name,
ti_ca: category,
ti_pr: price,
ti_qu: quantity,
ti_cu: currency,
};
compare(
tracker.track(buildEcommerceTransactionItem({ orderId, sku, name, category, price, quantity, currency })),
expected,
t
);
});
test('should track a self-describing event', (t) => {
const inputJson = {
schema: 'iglu:com.acme/user/jsonschema/1-0-1',
data: {
name: 'Eric',
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(tracker.track(buildSelfDescribingEvent({ event: inputJson })), expected, t);
});
test('should track a link click', (t) => {
const targetUrl = 'http://www.example.com';
const elementId = 'first header';
const elementClasses = ['header'];
const elementContent = 'link';
const elementTarget = 'target';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1',
data: {
targetUrl: targetUrl,
elementId: elementId,
elementClasses: elementClasses,
elementTarget: elementTarget,
elementContent: elementContent,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(
tracker.track(buildLinkClick({ targetUrl, elementId, elementClasses, elementTarget, elementContent })),
expected,
t
);
});
test('should track a screen view', (t) => {
const name = 'intro';
const id = '7398-4352-5345-1950';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/screen_view/jsonschema/1-0-0',
data: {
name: name,
id: id,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(tracker.track(buildScreenView({ name, id })), expected, t);
});
test('should track an ad impression', (t) => {
const impressionId = 'a0e8f8780ab3';
const costModel = 'cpc';
const cost = 0.5;
const targetUrl = 'http://adsite.com';
const bannerId = '123';
const zoneId = 'zone-14';
const advertiserId = 'ad-company';
const campaignId = 'campaign-7592';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_impression/jsonschema/1-0-0',
data: {
impressionId: impressionId,
costModel: costModel,
cost: cost,
targetUrl: targetUrl,
bannerId: bannerId,
zoneId: zoneId,
advertiserId: advertiserId,
campaignId: campaignId,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(
tracker.track(
buildAdImpression({ impressionId, costModel, cost, targetUrl, bannerId, zoneId, advertiserId, campaignId })
),
expected,
t
);
});
test('should track an ad click', (t) => {
const targetUrl = 'http://adsite.com';
const clickId = 'click-321';
const costModel = 'cpc';
const cost = 0.5;
const bannerId = '123';
const zoneId = 'zone-14';
const impressionId = 'a0e8f8780ab3';
const advertiserId = 'ad-company';
const campaignId = 'campaign-7592';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_click/jsonschema/1-0-0',
data: {
targetUrl: targetUrl,
clickId: clickId,
costModel: costModel,
cost: cost,
bannerId: bannerId,
zoneId: zoneId,
impressionId: impressionId,
advertiserId: advertiserId,
campaignId: campaignId,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(
tracker.track(
buildAdClick({ targetUrl, clickId, costModel, cost, bannerId, zoneId, impressionId, advertiserId, campaignId })
),
expected,
t
);
});
test('should track an ad conversion', (t) => {
const conversionId = 'conversion-59';
const costModel = 'cpc';
const cost = 0.5;
const category = 'cat';
const action = 'act';
const property = 'prop';
const initialValue = 7;
const advertiserId = 'ad-company';
const campaignId = 'campaign-7592';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_conversion/jsonschema/1-0-0',
data: {
conversionId: conversionId,
costModel: costModel,
cost: cost,
category: category,
action: action,
property: property,
initialValue: initialValue,
advertiserId: advertiserId,
campaignId: campaignId,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(
tracker.track(
buildAdConversion({
conversionId,
costModel,
cost,
category,
action,
property,
initialValue,
advertiserId,
campaignId,
})
),
expected,
t
);
});
test('should track a social interaction', (t) => {
const action = 'like';
const network = 'facebook';
const target = 'status-0000345345';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/social_interaction/jsonschema/1-0-0',
data: {
action: action,
network: network,
target: target,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(tracker.track(buildSocialInteraction({ action, network, target })), expected, t);
});
test('should track an add-to-cart event', (t) => {
const sku = '4q345';
const unitPrice = 17.0;
const quantity = 2;
const name = 'red shoes';
const category = 'clothing';
const currency = 'USD';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/add_to_cart/jsonschema/1-0-0',
data: {
sku: sku,
quantity: quantity,
name: name,
category: category,
unitPrice: unitPrice,
currency: currency,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(tracker.track(buildAddToCart({ sku, name, category, unitPrice, quantity, currency })), expected, t);
});
test('should track a remove-from-cart event', (t) => {
const sku = '4q345';
const unitPrice = 17.0;
const quantity = 2;
const name = 'red shoes';
const category = 'clothing';
const currency = 'USD';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/remove_from_cart/jsonschema/1-0-0',
data: {
sku: sku,
quantity: quantity,
name: name,
category: category,
unitPrice: unitPrice,
currency: currency,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(tracker.track(buildRemoveFromCart({ sku, name, category, unitPrice, quantity, currency })), expected, t);
});
test('should track a form focus event', (t) => {
const formId = 'parent';
const elementId = 'child';
const nodeName = 'INPUT';
const type = 'text';
const elementClasses = ['important'];
const value = 'male';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/focus_form/jsonschema/1-0-0',
data: {
formId: formId,
elementId: elementId,
nodeName: nodeName,
elementClasses: elementClasses,
value: value,
elementType: type,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(
tracker.track(
buildFormFocusOrChange({ schema: 'focus_form', formId, elementId, nodeName, type, elementClasses, value })
),
expected,
t
);
});
test('should track a form change event', (t) => {
const formId = 'parent';
const elementId = 'child';
const nodeName = 'INPUT';
const type = 'text';
const elementClasses = ['important'];
const value = 'male';
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/change_form/jsonschema/1-0-0',
data: {
formId: formId,
elementId: elementId,
nodeName: nodeName,
elementClasses: elementClasses,
value: value,
type: type,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(
tracker.track(
buildFormFocusOrChange({ schema: 'change_form', formId, elementId, nodeName, type, elementClasses, value })
),
expected,
t
);
});
test('should track a form submission event', (t) => {
const formId = 'parent';
const formClasses = ['formclass'];
const elements = [
{
name: 'gender',
value: 'male',
nodeName: 'INPUT',
type: 'text',
},
];
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/submit_form/jsonschema/1-0-0',
data: {
formId: formId,
formClasses: formClasses,
elements: elements,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(tracker.track(buildFormSubmission({ formId, formClasses, elements })), expected, t);
});
test('should track a site seach event', (t) => {
const terms = ['javascript', 'development'];
const filters = {
safeSearch: true,
category: 'books',
};
const totalResults = 35;
const pageResults = 10;
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/site_search/jsonschema/1-0-0',
data: {
terms: terms,
filters: filters,
totalResults: totalResults,
pageResults: pageResults,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
};
compare(tracker.track(buildSiteSearch({ terms, filters, totalResults, pageResults })), expected, t);
});
test('should track a consent withdrawn event', (t) => {
const all = false;
const id = '1234';
const version = '2';
const name = 'consent_form';
const description = 'user withdraws consent for form';
const timestamp = 1000000000000;
const inputContext = [
{
schema: 'iglu:com.snowplowanalytics.snowplow/consent_document/jsonschema/1-0-0',
data: {
id: id,
version: version,
name: name,
description: description,
},
},
];
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/consent_withdrawn/jsonschema/1-0-0',
data: {
all: all,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
co: JSON.stringify({
schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0',
data: inputContext,
}),
};
const consentEvent = buildConsentWithdrawn({ all, id, version, name, description });
compare(tracker.track(consentEvent.event, consentEvent.context, timestamp), expected, t);
});
test('should track a consent granted event', (t) => {
const id = '1234';
const version = '2';
const name = 'consent_form';
const description = 'user grants consent for form';
const timestamp = 1000000000000;
const expiry = '01 January, 1970 00:00:00 Universal Time (UTC)';
const inputContext = [
{
schema: 'iglu:com.snowplowanalytics.snowplow/consent_document/jsonschema/1-0-0',
data: {
id: id,
version: version,
name: name,
description: description,
},
},
];
const inputJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/consent_granted/jsonschema/1-0-0',
data: {
expiry: expiry,
},
};
const expected = {
e: 'ue',
ue_pr: JSON.stringify({
schema: selfDescribingEventSchema,
data: inputJson,
}),
co: JSON.stringify({
schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0',
data: inputContext,
}),
};
const consentEvent = buildConsentGranted({ id, version, name, description, expiry });
compare(tracker.track(consentEvent.event, consentEvent.context, timestamp), expected, t);
});
test('should track a page view with custom context', (t) => {
const pageUrl = 'http://www.example.com';
const pageTitle = 'title page';
const referrer = 'https://www.google.com';
const inputContext = [
{
schema: 'iglu:com.acme/user/jsonschema/1-0-0',
data: {
userType: 'tester',
userName: 'Jon',
},
},
];
const expected = {
e: 'pv',
url: pageUrl,
page: pageTitle,
refr: referrer,
co: JSON.stringify({
schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0',
data: inputContext,
}),
};
compare(tracker.track(buildPageView({ pageUrl, pageTitle, referrer }), inputContext), expected, t);
});
test('should track a page view with a timestamp', (t) => {
const timestamp = 1000000000000;
t.is(
tracker.track(
buildPageView({ pageUrl: 'http://www.example.com', pageTitle: 'title', referrer: 'ref' }),
[],
timestamp
)['dtm'],
'1000000000000'
);
});
test('should add individual name-value pairs to the payload', (t) => {
const tracker = trackerCore({ base64: false });
const pageUrl = 'http://www.example.com';
const pageTitle = 'title';
const referrer = 'https://www.google.com';
const expected = {
e: 'pv',
url: pageUrl,
tna: 'sp',
tv: 'js-2.0.0',
page: pageTitle,
refr: referrer,
};
tracker.addPayloadPair('tna', 'sp');
tracker.addPayloadPair('tv', 'js-2.0.0');
compare(tracker.track(buildPageView({ pageUrl, pageTitle, referrer })), expected, t);
});
test('should add a dictionary of name-value pairs to the payload', (t) => {
const tracker = trackerCore({ base64: false });
const pageUrl = 'http://www.example.com';
const pageTitle = 'title';
const referrer = 'https://www.google.com';
const expected = {
e: 'pv',
url: pageUrl,
tv: 'js-2.0.0',
tna: 'sp',
aid: 'sp325',
page: pageTitle,
refr: referrer,
};
tracker.addPayloadPair('tv', 'js-2.0.0');
tracker.addPayloadDict({
tna: 'sp',
aid: 'sp325',
});
compare(tracker.track(buildPageView({ pageUrl, pageTitle, referrer })), expected, t);
});
test('should reset payload name-value pairs', (t) => {
const tracker = trackerCore({ base64: false });
const pageUrl = 'http://www.example.com';
const pageTitle = 'title';
const referrer = 'https://www.google.com';
const expected = {
e: 'pv',
url: pageUrl,
tna: 'sp',
page: pageTitle,
refr: referrer,
};
tracker.addPayloadPair('tna', 'mistake');
tracker.resetPayloadPairs({ tna: 'sp' });
compare(tracker.track(buildPageView({ pageUrl, pageTitle, referrer })), expected, t);
});
test('should execute a callback', (t) => {
const tracker = trackerCore({
base64: false,
corePlugins: [],
callback: function (payload) {
const callbackTarget = payload;
compare(callbackTarget.build(), expected, t);
},
});
const pageUrl = 'http://www.example.com';
const pageTitle = 'title';
const referrer = 'https://www.google.com';
const expected = {
e: 'pv',
url: pageUrl,
page: pageTitle,
refr: referrer,
};
tracker.track(buildPageView({ pageUrl, pageTitle, referrer }));
});
test('should use setter methods', (t) => {
const tracker = trackerCore({ base64: false });
tracker.setTrackerVersion('js-3.0.0');
tracker.setTrackerNamespace('sp1');
tracker.setAppId('my-app');
tracker.setPlatform('web');
tracker.setUserId('jacob');
tracker.setScreenResolution('400', '200');
tracker.setViewport('500', '800');
tracker.setColorDepth('24');
tracker.setTimezone('Europe London');
tracker.setIpAddress('37.151.33.154');
tracker.setUseragent('SnowplowJavascript/0.0.1');
const pageUrl = 'http://www.example.com';
const pageTitle = 'title page';
const referrer = 'https://www.google.com';
const expected = {
e: 'pv',
url: pageUrl,
page: pageTitle,
tna: 'sp1',
tv: 'js-3.0.0',
aid: 'my-app',
p: 'web',
uid: 'jacob',
res: '400x200',
vp: '500x800',
cd: '24',
tz: 'Europe London',
ip: '37.151.33.154',
ua: 'SnowplowJavascript/0.0.1',
refr: referrer,
};
compare(tracker.track(buildPageView({ pageUrl, pageTitle, referrer })), expected, t);
});
test('should set true timestamp', (t) => {
const pageUrl = 'http://www.example.com';
const pageTitle = 'title page';
const referrer = 'https://www.google.com';
const result = tracker.track(buildPageView({ pageUrl, pageTitle, referrer }), undefined, {
type: 'ttm',
value: 1477403862,
});
t.true('ttm' in result);
t.is(result['ttm'], '1477403862');
t.false('dtm' in result);
});
test('should set device timestamp as ADT', (t) => {
const inputJson = {
schema: 'iglu:com.acme/user/jsonschema/1-0-1',
data: {
name: 'Eric',
},
};
const result = tracker.track(buildSelfDescribingEvent({ event: inputJson }), [inputJson], {
type: 'dtm',
value: 1477403869,
});
t.true('dtm' in result);
t.is(result['dtm'], '1477403869');
t.false('ttm' in result);
});
test('should run plugin before and after track callbacks on each track event', (t) => {
const url = 'http://www.example.com';
const str = 'cccccckevjfiddbdjeikkdbkvvkdjcehggiutbkhnrfe';
const num = 1;
const arr = [str];
const filters = {
safeSearch: true,
category: str,
};
const inputJson = {
schema: 'iglu:com.acme/user/jsonschema/1-0-1',
data: {
name: str,
},
};
(beforeCount = 0), (afterCount = 0);
const fs = [
tracker.track(
buildPagePing({
pageUrl: url,
pageTitle: str,
referrer: url,
maxXOffset: num,
maxYOffset: num,
minXOffset: num,
minYOffset: num,
})
),
tracker.track(buildPageView({ pageUrl: url, pageTitle: str, referrer: url })),
tracker.track(buildAddToCart({ category: str, name: str, quantity: num, sku: str, unitPrice: num })),
tracker.track(buildScreenView({ id: str, name: str })),
tracker.track(buildSiteSearch({ filters, pageResults: num, terms: arr, totalResults: num })),
tracker.track(buildStructEvent({ category: str, action: str })),
tracker.track(
buildAdConversion({
conversionId: str,
costModel: 'cpm',
cost: num,
category: str,
action: str,
property: str,
initialValue: num,
advertiserId: str,
campaignId: str,
})
),
tracker.track(
buildAdImpression({
impressionId: str,
costModel: 'cpm',
cost: num,
targetUrl: str,
bannerId: str,
zoneId: str,
advertiserId: str,
campaignId: str,
})
),
tracker.track(buildFormSubmission({ elements: [], formClasses: [], formId: str })),
tracker.track(buildRemoveFromCart({ category: str, name: str, quantity: num, sku: str, unitPrice: num })),
tracker.track(buildConsentGranted({ id: str, version: str }).event),
tracker.track(buildConsentWithdrawn({ all: true }).event),
tracker.track(
buildFormFocusOrChange({
schema: 'focus_form',
formId: str,
elementId: str,
nodeName: str,
type: str,
elementClasses: arr,
value: str,
})
),
tracker.track(buildSocialInteraction({ action: str, network: str, target: str })),
tracker.track(buildSelfDescribingEvent({ event: inputJson })),
tracker.track(buildEcommerceTransaction({ orderId: str, total: num })),
tracker.track(
buildEcommerceTransactionItem({ orderId: str, sku: str, name: str, category: str, price: num, quantity: num })
),
tracker.track(buildLinkClick({ targetUrl: url })),
tracker.track(
buildAdClick({
targetUrl: str,
clickId: str,
costModel: 'cpm',
cost: num,
bannerId: str,
zoneId: str,
impressionId: str,
advertiserId: str,
campaignId: str,
})
),
];
t.is(beforeCount, fs.length);
t.is(afterCount, fs.length);
}); | the_stack |
import * as napa from "../lib/index";
import * as assert from "assert";
import * as path from "path";
type Zone = napa.zone.Zone;
describe('napajs/module', function () {
let napaZone = napa.zone.create('module-tests-zone', { workers: 1 });
describe('load', function () {
it('javascript module', () => {
return napaZone.execute(() => {
var assert = require("assert");
var jsmodule = require('./module/jsmodule');
assert.notEqual(jsmodule, undefined);
assert.equal(jsmodule.wasLoaded, true);
});
});
it('javascript module from string', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require('path');
var jsmodule = (<any>require)(
'./module/jsmodule-from-string',
"module.exports = function() { return __filename;}");
assert.notEqual(jsmodule, undefined);
assert.equal(jsmodule(), path.resolve(__dirname, 'module/jsmodule-from-string'));
});
});
it('json module', () => {
return napaZone.execute(() => {
var assert = require("assert");
var jsonModule = require('./module/test.json');
assert.notEqual(jsonModule, undefined);
assert.equal(jsonModule.prop1, "val1");
assert.equal(jsonModule.prop2, "val2");
});
});
it('napa module', () => {
return napaZone.execute(() => {
var assert = require("assert");
var napaModule = require('../bin/simple-addon.napa');
assert.notEqual(napaModule, undefined);
assert.equal(napaModule.getModuleName(), "simple-napa-addon");
});
});
it('object wrap module', () => {
return napaZone.execute(() => {
var assert = require("assert");
var napaModule = require('../bin/simple-addon.napa');
var obj = napaModule.createSimpleObjectWrap();
assert.notEqual(obj, undefined);
obj.setValue(3);
assert.equal(obj.getValue(), 3);
}, [__dirname]);
});
it('circular dependencies', () => {
return napaZone.execute(() => {
var assert = require("assert");
var cycle_a = require('./module/cycle-a.js');
var cycle_b = require('./module/cycle-b.js');
assert(cycle_a.done);
assert(cycle_b.done);
}, [__dirname]);
});
it('module that does not exist', () => {
return napaZone.execute(() => {
try {
var jsmodule = require('./module/module-does-not-exist');
assert.fail("require on module that does not exist shall throw");
}
catch (e) {
}
});
});
});
describe('resolve', function () {
// TODO: support correct __dirname in anonymous function and move tests from 'resolution-tests.js' here.
it('require.resolve', () => {
return napaZone.execute("./module/resolution-tests.js", "run");
});
});
describe('core-modules', function () {
describe('process', function () {
it.skip('argv', () => {
return napaZone.execute(() => {
var assert = require("assert");
assert(process.argv.length > 0);
assert(process.argv[0].includes('node'));
});
});
it('execPath', () => {
return napaZone.execute(() => {
var assert = require("assert");
assert(process.execPath.includes('node'));
});
});
it('env', () => {
return napaZone.execute(() => {
var assert = require("assert");
process.env.test = "napa-test";
assert.equal(process.env.test, "napa-test");
});
});
it('platform', () => {
return napaZone.execute(() => {
var assert = require("assert");
assert(process.platform == 'win32' ||
process.platform == 'darwin' ||
process.platform == 'linux' ||
process.platform == 'freebsd');
});
});
it('umask', () => {
return napaZone.execute(() => {
var assert = require("assert");
var old = process.umask(0);
assert.equal(process.umask(old), 0);
});
});
it('chdir', () => {
return napaZone.execute(() => {
var assert = require("assert");
var cwd = process.cwd();
process.chdir('..');
assert.notEqual(cwd, process.cwd());
assert(cwd.includes(process.cwd()));
process.chdir(cwd);
assert.equal(cwd, process.cwd());
});
});
it('pid', () => {
return napaZone.execute(() => {
var assert = require("assert");
assert.notEqual(typeof process.pid, undefined);
assert(!isNaN(process.pid));
});
});
});
describe('fs', function () {
it('existsSync', () => {
return napaZone.execute(() => {
var assert = require("assert");
var fs = require('fs');
assert(fs.existsSync(__dirname + '/module/jsmodule.js'));
assert(!fs.existsSync(__dirname + '/non-existing-file.txt'));
});
});
it('readFileSync', () => {
return napaZone.execute(() => {
var assert = require("assert");
var fs = require('fs');
var content = JSON.parse(fs.readFileSync(__dirname + '/module/test.json'));
assert.equal(content.prop1, 'val1');
assert.equal(content.prop2, 'val2');
});
});
it('mkdirSync', () => {
return napaZone.execute(() => {
var assert = require("assert");
var fs = require('fs');
fs.mkdirSync(__dirname + '/module/test-dir');
assert(fs.existsSync(__dirname + '/module/test-dir'));
}).then(()=> {
// Cleanup
var fs = require('fs');
if (fs.existsSync('./module/test-dir')) {
fs.rmdir('./module/test-dir');
}
})
});
it('writeFileSync', () => {
return napaZone.execute(() => {
var assert = require("assert");
var fs = require('fs');
fs.writeFileSync(__dirname + '/module/test-file', 'test');
assert.equal(fs.readFileSync(__dirname + '/module/test-file'), 'test');
}, [__dirname]).then(()=> {
// Cleanup
var fs = require('fs');
if (fs.existsSync('./module/test-file')) {
fs.unlinkSync('./module/test-file');
}
})
});
it('readFileSync', () => {
return napaZone.execute(() => {
var assert = require("assert");
var fs = require('fs');
var testDir = __dirname + '/module/test-dir';
fs.mkdirSync(testDir);
fs.writeFileSync(testDir + '/1', 'test');
fs.writeFileSync(testDir + '/2', 'test');
assert.deepEqual(fs.readdirSync(testDir).sort(), ['1', '2']);
}).then(()=> {
// Cleanup
var fs = require('fs');
if (fs.existsSync('./module/test-dir')) {
fs.unlinkSync('./module/test-dir/1');
fs.unlinkSync('./module/test-dir/2');
fs.rmdir('./module/test-dir');
}
})
});
});
describe('path', function () {
it('normalize', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.normalize('a\\b\\..\\c/./d/././.'), "a\\c\\d");
} else {
assert.equal(path.normalize('a\\b\\..\\c/./d/././.'), "a/c/d");
}
});
});
it('resolve', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.resolve('c:\\foo/bar', "a.txt"), "c:\\foo\\bar\\a.txt");
assert.equal(path.resolve("abc.txt"), process.cwd() + "\\abc.txt");
assert.equal(path.resolve("abc", "efg", "../hij", "./xyz.txt"), process.cwd() + "\\abc\\hij\\xyz.txt");
assert.equal(path.resolve("abc", "d:/a.txt"), "d:\\a.txt");
} else {
assert.equal(path.resolve('/foo/bar', "a.txt"), "/foo/bar/a.txt");
assert.equal(path.resolve("abc.txt"), process.cwd() + "/abc.txt");
assert.equal(path.resolve("abc", "efg", "../hij", "./xyz.txt"), process.cwd() + "/abc/hij/xyz.txt");
assert.equal(path.resolve("abc", "/a.txt"), "/a.txt");
}
});
});
it('join', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.join("/foo", "bar", "baz/asdf", "quux", ".."), "\\foo\\bar\\baz\\asdf");
} else {
assert.equal(path.join("/foo", "bar", "baz/asdf", "quux", ".."), "/foo/bar/baz/asdf");
}
});
});
// TODO: fix bugs
// 1. Error: the string "AssertionError: '.' == 'c:'" was thrown, throw an Error :)
// 2. Error: the string "AssertionError: 'c:' == 'c:\\\\'" was thrown, throw an Error :)
it.skip('dirname', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.dirname("c:"), "c:");
assert.equal(path.dirname("c:\\windows"), "c:\\");
assert.equal(path.dirname("c:\\windows\\abc.txt"), "c:\\windows");
} else {
assert.equal(path.dirname("/"), "/");
assert.equal(path.dirname("/etc"), "/");
assert.equal(path.dirname("/etc/passwd"), "/etc");
}
});
});
it('basename', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.basename("c:\\windows\\abc.txt"), "abc.txt");
assert.equal(path.basename("c:\\windows\\a"), "a");
assert.equal(path.basename("c:\\windows\\abc.txt", ".txt"), "abc");
assert.equal(path.basename("c:\\windows\\abc.txt", ".Txt"), "abc.txt");
} else {
assert.equal(path.basename("/test//abc.txt"), "abc.txt");
assert.equal(path.basename("/test//a"), "a");
assert.equal(path.basename("/test/abc.txt", ".txt"), "abc");
assert.equal(path.basename("/windows/abc.txt", ".Txt"), "abc.txt");
}
});
});
// TODO: fix bugs
// 1. Error: the string "AssertionError: '' == '.'" was thrown, throw an Error :)
it.skip('extname', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.extname("c:\\windows\\abc.txt"), ".txt");
assert.equal(path.extname("c:\\windows\\a.json.txt"), ".txt");
assert.equal(path.extname("c:\\windows\\a."), ".");
} else {
assert.equal(path.extname("/test/abc.txt"), ".txt");
assert.equal(path.extname("/test/a.json.txt"), ".txt");
assert.equal(path.extname("/test/a."), ".");
}
});
});
it('isAbsolute', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.isAbsolute("c:\\windows\\a."), true);
assert.equal(path.isAbsolute("c:/windows/.."), true);
assert.equal(path.isAbsolute("../abc"), false);
assert.equal(path.isAbsolute("./abc"), false);
assert.equal(path.isAbsolute("abc"), false);
} else {
assert.equal(path.isAbsolute("/test/a."), true);
assert.equal(path.isAbsolute("/test/.."), true);
assert.equal(path.isAbsolute("../abc"), false);
assert.equal(path.isAbsolute("./abc"), false);
assert.equal(path.isAbsolute("abc"), false);
}
});
});
it('relative', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.relative("c:\\a\\..\\b", "c:\\b"), "");
assert.equal(path.relative("c:/a", "d:/b/../c"), "d:\\c");
assert.equal(path.relative("z:/a", "a.txt"), process.cwd() + "\\a.txt");
assert.equal(path.relative("c:/a", "c:/"), "..");
} else {
assert.equal(path.relative("/test/a/../b", "/test/b"), "");
assert.equal(path.relative("/test/a", "/test1/b/../c"), "../../test1/c");
assert.equal(path.relative("/test/a", "a.txt"), "../.." + process.cwd() + "/a.txt");
assert.equal(path.relative("/test/a", "/test/"), "..");
}
});
});
it('sep', () => {
return napaZone.execute(() => {
var assert = require("assert");
var path = require("path");
if (process.platform == 'win32') {
assert.equal(path.sep, "\\");
} else {
assert.equal(path.sep, "/");
}
});
});
});
describe('os', function () {
it('type', () => {
return napaZone.execute(() => {
var assert = require("assert");
var os = require("os");
assert(os.type() == "Windows_NT" || os.type() == "Darwin" || os.type() == "Linux");
});
});
});
});
describe('async', function () {
it('post async work', () => {
return napaZone.execute(() => {
var assert = require("assert");
var napaModule = require('../bin/simple-addon.napa');
var obj = napaModule.createSimpleObjectWrap();
obj.setValue(3);
var promise = new Promise((resolve) => {
obj.postIncrementWork((newValue: number) => {
resolve(newValue);
});
});
// The value shouldn't have changed yet.
assert.equal(obj.getValue(), 3);
return promise;
}).then((result: napa.zone.Result) => {
assert.equal(result.value, 4);
});
});
it('do async work', () => {
return napaZone.execute(() => {
var assert = require("assert");
var napaModule = require('../bin/simple-addon.napa');
var obj = napaModule.createSimpleObjectWrap();
obj.setValue(8);
var promise = new Promise((resolve) => {
obj.doIncrementWork((newValue: number) => {
resolve(newValue);
});
});
// The actual increment happened in the same thread.
assert.equal(obj.getValue(), 9);
return promise;
}).then((result: napa.zone.Result) => {
assert.equal(result.value, 9);
});
});
});
}); | the_stack |
import firebase from "firebase/app";
import {isSameStringArray, TRASH_TAG} from "./Utils";
import * as base64js from "base64-js";
import {sha1} from "./Sha1";
import {TagSet} from "./TagSet";
import DocumentData = firebase.firestore.DocumentData;
import DocumentSnapshot = firebase.firestore.DocumentSnapshot;
import {BasicProgram, Cassette, decodeTrs80File, setBasicName} from "trs80-base";
type UpdateData = firebase.firestore.UpdateData;
// What's considered a "new" file.
const NEW_TIME_MS = 60*60*24*7*1000;
// Prefix for version of hash. Increment this number when the hash algorithm changes.
const HASH_PREFIX = "1:";
/**
* Return whether the test string starts with the filter prefix.
*/
function prefixMatches(testString: string, filterPrefix: string): boolean {
return testString.substr(0, filterPrefix.length).localeCompare(filterPrefix, undefined, {
usage: "search",
sensitivity: "base",
}) === 0;
}
/**
* Return whether any word in the test string starts with the filter prefix.
*/
function prefixMatchesAnyWord(testString: string, filterPrefix: string): boolean {
return testString.split(/\W+/).some(word => prefixMatches(word, filterPrefix));
}
/**
* Represents a file that the user owns.
*/
export class File {
public readonly id: string;
public readonly uid: string;
public readonly name: string;
public readonly filename: string;
public readonly note: string;
public readonly author: string;
public readonly releaseYear: string;
public readonly shared: boolean;
public readonly tags: string[]; // Don't modify this, treat as immutable. Always sorted alphabetically.
public readonly hash: string;
public readonly isDeleted: boolean;
public readonly screenshots: string[]; // Don't modify this, treat as immutable.
public readonly binary: Uint8Array;
public readonly addedAt: Date;
public readonly modifiedAt: Date;
constructor(id: string, uid: string, name: string, filename: string, note: string,
author: string, releaseYear: string, shared: boolean, tags: string[], hash: string,
screenshots: string[], binary: Uint8Array, addedAt: Date, modifiedAt: Date) {
this.id = id;
this.uid = uid;
this.name = name;
this.filename = filename;
this.note = note;
this.author = author;
this.releaseYear = releaseYear;
this.shared = shared;
this.tags = [...tags].sort(); // Guarantee it's sorted.
this.isDeleted = this.tags.indexOf(TRASH_TAG) >= 0;
this.hash = hash;
this.screenshots = screenshots;
this.binary = binary;
this.addedAt = addedAt;
this.modifiedAt = modifiedAt;
}
/**
* Return the file as an object that can be converted to JSON and exported.
*/
public asMap(): {[key: string]: any} {
return {
id: this.id,
uid: this.uid,
name: this.name,
filename: this.filename,
note: this.note,
author: this.author,
releaseYear: this.releaseYear,
shared: this.shared,
tags: this.tags,
hash: this.hash,
screenshots: this.screenshots,
binary: base64js.fromByteArray(this.binary),
addedAt: this.addedAt.getTime(),
modifiedAt: this.modifiedAt.getTime(),
};
}
public builder(): FileBuilder {
const builder = new FileBuilder();
builder.id = this.id;
builder.uid = this.uid;
builder.name = this.name;
builder.filename = this.filename;
builder.note = this.note;
builder.author = this.author;
builder.releaseYear = this.releaseYear;
builder.shared = this.shared;
builder.tags = this.tags;
builder.hash = this.hash;
builder.screenshots = this.screenshots;
builder.binary = this.binary;
builder.addedAt = this.addedAt;
builder.modifiedAt = this.modifiedAt;
return builder;
}
/**
* Returns a Firestore update object to convert oldFile to this.
*/
public getUpdateDataComparedTo(oldFile: File): UpdateData {
const updateData: UpdateData = {};
if (this.name !== oldFile.name) {
updateData.name = this.name;
}
if (this.filename !== oldFile.filename) {
updateData.filename = this.filename;
}
if (this.note !== oldFile.note) {
updateData.note = this.note;
}
if (this.author !== oldFile.author) {
updateData.author = this.author;
}
if (this.releaseYear !== oldFile.releaseYear) {
updateData.releaseYear = this.releaseYear;
}
if (this.shared !== oldFile.shared) {
updateData.shared = this.shared;
}
if (!isSameStringArray(this.tags, oldFile.tags)) {
updateData.tags = this.tags;
}
if (this.hash !== oldFile.hash) {
updateData.hash = this.hash;
}
if (!isSameStringArray(this.screenshots, oldFile.screenshots)) {
updateData.screenshots = this.screenshots;
}
if (this.modifiedAt.getTime() !== oldFile.modifiedAt.getTime()) {
updateData.modifiedAt = this.modifiedAt;
}
return updateData;
}
/**
* Get all tags, both stored in the file and the automatically created ones.
* TODO could cache this, assume the auto ones don't change over time. The "new" would
* change but not much.
*/
public getAllTags(): TagSet {
const allTags = new TagSet();
if (this.shared) {
allTags.add("Shared");
}
const now = Date.now();
if (now - this.addedAt.getTime() < NEW_TIME_MS) {
allTags.add("New");
}
// TODO better extension algorithm.
const i = this.filename.lastIndexOf(".");
if (i > 0) {
allTags.add(this.filename.substr(i + 1).toUpperCase());
}
if (this.note === "") {
allTags.add("Missing note");
}
if (this.screenshots.length === 0) {
allTags.add("Missing screenshot");
}
allTags.add(...this.tags);
return allTags;
}
/**
* Whether this file would match the specified filter prefix.
*/
public matchesFilterPrefix(filterPrefix: string): boolean {
// Always match empty string.
if (filterPrefix === "") {
return true;
}
// Check various fields.
if (prefixMatchesAnyWord(this.name, filterPrefix)) {
return true;
}
if (prefixMatches(this.filename, filterPrefix)) {
return true;
}
if (prefixMatchesAnyWord(this.note, filterPrefix)) {
return true;
}
if (prefixMatchesAnyWord(this.author, filterPrefix)) {
return true;
}
return false;
}
/**
* Whether the hash was computed with an outdated algorithm.
*/
public isOldHash(): boolean {
return !this.hash.startsWith(HASH_PREFIX);
}
/**
* Compare two files for sorting.
*/
public static compare(a: File, b: File): number {
// Primary sort by name.
let cmp = a.name.localeCompare(b.name, undefined, {
usage: "sort",
sensitivity: "base",
ignorePunctuation: true,
numeric: true,
});
if (cmp !== 0) {
return cmp;
}
// Secondary sort is filename.
cmp = a.filename.localeCompare(b.filename, undefined, {
usage: "sort",
numeric: true,
});
if (cmp !== 0) {
return cmp;
}
// Break ties with ID so the sort is stable.
return a.id.localeCompare(b.id);
}
}
/**
* Builder to help construct File objects.
*/
export class FileBuilder {
public id = "";
public uid = "";
public name = "";
public filename = "";
public note = "";
public author = "";
public releaseYear = "";
public shared = false;
public tags: string[] = [];
public hash = "";
public screenshots: string[] = [];
public binary = new Uint8Array(0);
public addedAt = new Date();
public modifiedAt = new Date();
public static fromDoc(doc: DocumentSnapshot<DocumentData>): FileBuilder {
const builder = new FileBuilder();
builder.id = doc.id;
// Assume data() is valid, either because it's a query or because we checked "exists".
const data = doc.data() as DocumentData;
builder.uid = data.uid;
builder.name = data.name;
builder.filename = data.filename;
builder.note = data.note;
builder.author = data.author ?? "";
builder.releaseYear = data.releaseYear ?? "";
builder.shared = data.shared ?? false;
builder.tags = data.tags ?? [];
builder.hash = data.hash;
builder.screenshots = data.screenshots ?? [];
builder.binary = (data.binary as firebase.firestore.Blob).toUint8Array();
builder.addedAt = (data.addedAt as firebase.firestore.Timestamp).toDate();
builder.modifiedAt = (data.modifiedAt as firebase.firestore.Timestamp).toDate();
return builder;
}
public withId(id: string): this {
this.id = id;
return this;
}
public withUid(uid: string): this {
this.uid = uid;
return this;
}
public withName(name: string): this {
this.name = name;
return this;
}
public withFilename(filename: string): this {
this.filename = filename;
return this;
}
public withNote(note: string): this {
this.note = note;
return this;
}
public withAuthor(author: string): this {
this.author = author;
return this;
}
public withReleaseYear(releaseYear: string): this {
this.releaseYear = releaseYear;
return this;
}
public withShared(shared: boolean): this {
this.shared = shared;
return this;
}
public withTags(tags: string[]): this {
this.tags = tags;
return this;
}
public withScreenshots(screenshots: string[]): this {
this.screenshots = screenshots;
return this;
}
public withBinary(binary: Uint8Array): this {
this.binary = binary;
// We used to do the raw binary, but that doesn't catch some irrelevant changes, like differences
// in CAS header or the Basic name. So decode the binary and see if we can zero out the differences.
// This might create an unfortunate preference for setting the filename first.
let trs80File = decodeTrs80File(binary, this.filename);
// Pull the program out of the cassette.
if (trs80File.className === "Cassette") {
if (trs80File.files.length > 0) {
trs80File = trs80File.files[0].file;
binary = trs80File.binary;
}
}
// Clear out the Basic name.
if (trs80File.className === "BasicProgram") {
binary = setBasicName(binary, "A");
}
// Prefix with version number.
this.hash = HASH_PREFIX + sha1(binary);
return this;
}
public withModifiedAt(modifiedAt: Date): this {
this.modifiedAt = modifiedAt;
return this;
}
public build(): File {
return new File(this.id, this.uid, this.name, this.filename, this.note,
this.author, this.releaseYear, this.shared, this.tags, this.hash,
this.screenshots, this.binary, this.addedAt, this.modifiedAt);
}
} | the_stack |
import {IModel, Model} from 'mobx-collection-store';
import IDictionary from './interfaces/IDictionary';
import IRequestOptions from './interfaces/IRequestOptions';
import * as JsonApi from './interfaces/JsonApi';
import {buildUrl, create, fetchLink, handleResponse, remove, update} from './NetworkUtils';
import {Response} from './Response';
import {Store} from './Store';
import {getValue, mapItems, objectForEach} from './utils';
interface IInternal {
relationships?: IDictionary<JsonApi.IRelationship>;
meta?: object;
links?: IDictionary<JsonApi.ILink>;
persisted?: boolean;
id: number|string;
type: string;
}
export class Record extends Model implements IModel {
/**
* Type property of the record class
*
* @static
*
* @memberOf Record
*/
public static typeAttribute = ['__internal', 'type'];
/**
* ID property of the record class
*
* @static
*
* @memberOf Record
*/
public static idAttribute = ['__internal', 'id'];
/**
* Should the autogenerated ID be sent to the server when creating a record
*
* @static
* @type {boolean}
* @memberOf Record
*/
public static useAutogeneratedIds: boolean = false;
/**
* Endpoint for API requests if there is no self link
*
* @static
* @type {string|() => string}
* @memberOf Record
*/
public static endpoint: string|(() => string);
public 'static': typeof Record;
/**
* Internal metadata
*
* @private
* @type {IInternal}
* @memberOf Record
*/
private __internal: IInternal;
/**
* Cache link fetch requests
*
* @private
* @type {IDictionary<Promise<Response>>}
* @memberOf Record
*/
private __relationshipLinkCache: IDictionary<IDictionary<Promise<Response>>> = {};
/**
* Cache link fetch requests
*
* @private
* @type {IDictionary<Promise<Response>>}
* @memberOf Record
*/
private __linkCache: IDictionary<Promise<Response>> = {};
/**
* Get record relationship links
*
* @returns {IDictionary<JsonApi.IRelationship>} Record relationship links
*
* @memberOf Record
*/
public getRelationshipLinks(): IDictionary<JsonApi.IRelationship> {
return this.__internal && this.__internal.relationships;
}
/**
* Fetch a relationship link
*
* @param {string} relationship Name of the relationship
* @param {string} name Name of the link
* @param {IRequestOptions} [options] Server options
* @param {boolean} [force=false] Ignore the existing cache
* @returns {Promise<Response>} Response promise
*
* @memberOf Record
*/
public fetchRelationshipLink(
relationship: string,
name: string,
options?: IRequestOptions,
force: boolean = false,
): Promise<Response> {
this.__relationshipLinkCache[relationship] = this.__relationshipLinkCache[relationship] || {};
/* istanbul ignore else */
if (!(name in this.__relationshipLinkCache) || force) {
const link: JsonApi.ILink = (
'relationships' in this.__internal &&
relationship in this.__internal.relationships &&
name in this.__internal.relationships[relationship]
) ? this.__internal.relationships[relationship][name] : null;
const headers: IDictionary<string> = options && options.headers;
this.__relationshipLinkCache[relationship][name] = fetchLink(link, this.__collection as Store, headers, options);
}
return this.__relationshipLinkCache[relationship][name];
}
/**
* Get record metadata
*
* @returns {object} Record metadata
*
* @memberOf Record
*/
public getMeta(): object {
return this.__internal && this.__internal.meta;
}
/**
* Get record links
*
* @returns {IDictionary<JsonApi.ILink>} Record links
*
* @memberOf Record
*/
public getLinks(): IDictionary<JsonApi.ILink> {
return this.__internal && this.__internal.links;
}
/**
* Fetch a record link
*
* @param {string} name Name of the link
* @param {IRequestOptions} [options] Server options
* @param {boolean} [force=false] Ignore the existing cache
* @returns {Promise<Response>} Response promise
*
* @memberOf Record
*/
public fetchLink(name: string, options?: IRequestOptions, force: boolean = false): Promise<Response> {
if (!(name in this.__linkCache) || force) {
const link: JsonApi.ILink = ('links' in this.__internal && name in this.__internal.links) ?
this.__internal.links[name] : null;
this.__linkCache[name] = fetchLink(link, this.__collection as Store, options && options.headers, options);
}
let request: Promise<Response> = this.__linkCache[name];
if (this['__queue__']) {
request = this.__linkCache[name].then((response) => {
const related: Record = this['__related__'];
const prop: string = this['__prop__'];
const record: Record = response.data as Record;
if (record &&
record.getRecordType() !== this.getRecordType() &&
record.getRecordType() === related.getRecordType()
) {
/* istanbul ignore if */
if (prop) {
related[prop] = record;
return response;
}
related.__persisted = true;
return response.replaceData(related);
}
return response;
});
}
return request;
}
/**
* Get the persisted state
*
* @readonly
* @private
* @type {boolean}
* @memberOf Record
*/
private get __persisted(): boolean {
return (this.__internal && this.__internal.persisted) || false;
}
/**
* Set the persisted state
*
* @private
*
* @memberOf Record
*/
private set __persisted(state: boolean) {
this.__internal.persisted = state;
}
/**
* Serialize the record into JSON API format
*
* @returns {JsonApi.IRecord} JSON API formated record
*
* @memberOf Record
*/
public toJsonApi(): JsonApi.IRecord {
const attributes: IDictionary<any> = this.toJS();
const useAutogenerated: boolean = this.static['useAutogeneratedIds'];
const data: JsonApi.IRecord = {
attributes,
id: (this.__persisted || useAutogenerated) ? this.getRecordId() : undefined,
type: this.getRecordType() as string,
};
const refs: IDictionary<string> = this['__refs'];
objectForEach(refs, (key: string) => {
data.relationships = data.relationships || {};
const rel = mapItems(this[`${key}Id`], (id: number|string) => {
if (!id && id !== 0) {
return null;
}
return {id, type: refs[key]};
});
data.relationships[key] = {data: rel} as JsonApi.IRelationship;
delete data.attributes[key];
delete data.attributes[`${key}Id`];
delete data.attributes[`${key}Meta`];
});
delete data.attributes.__internal;
delete data.attributes.__type__;
return data;
}
/**
* Saves (creates or updates) the record to the server
*
* @param {IRequestOptions} [options] Server options
* @param {boolean} [ignoreSelf=false] Should the self link be ignored if it exists
* @returns {Promise<Record>} Returns the record is successful or rejects with an error
*
* @memberOf Record
*/
public save(options?: IRequestOptions, ignoreSelf: boolean = false): Promise<Record> {
const store: Store = this.__collection as Store;
const data: JsonApi.IRecord = this.toJsonApi();
const requestMethod: Function = this.__persisted ? update : create;
return requestMethod(store, this.__getUrl(options, ignoreSelf), {data}, options && options.headers)
.then(handleResponse(this));
}
public saveRelationship(relationship: string, options?: IRequestOptions): Promise<Record> {
const link: JsonApi.ILink = (
'relationships' in this.__internal &&
relationship in this.__internal.relationships &&
'self' in this.__internal.relationships[relationship]
) ? this.__internal.relationships[relationship]['self'] : null;
/* istanbul ignore if */
if (!link) {
throw new Error('The relationship doesn\'t have a defined link');
}
const store: Store = this.__collection as Store;
/* istanbul ignore next */
const href: string = typeof link === 'object' ? link.href : link;
const type: string = this['__refs'][relationship];
type ID = JsonApi.IIdentifier|Array<JsonApi.IIdentifier>;
const data: ID = mapItems(this[`${relationship}Id`], (id) => ({id, type})) as ID;
return update(store, href, {data}, options && options.headers)
.then(handleResponse(this, relationship));
}
/**
* Remove the records from the server and store
*
* @param {IRequestOptions} [options] Server options
* @param {boolean} [ignoreSelf=false] Should the self link be ignored if it exists
* @returns {Promise<boolean>} Resolves true if successfull or rejects if there was an error
*
* @memberOf Record
*/
public remove(options?: IRequestOptions, ignoreSelf: boolean = false): Promise<boolean> {
const store: Store = this.__collection as Store;
if (!this.__persisted) {
this.__collection.remove(this.getRecordType(), this.getRecordId());
return Promise.resolve(true);
}
return remove(store, this.__getUrl(options, ignoreSelf), options && options.headers)
.then((response: Response) => {
/* istanbul ignore if */
if (response.error) {
throw response.error;
}
this.__persisted = false;
if (this.__collection) {
this.__collection.remove(this.getRecordType(), this.getRecordId());
}
return true;
});
}
/**
* Set the persisted status of the record
*
* @param {boolean} state Is the record persisted on the server
*
* @memberOf Record
*/
public setPersisted(state: boolean): void {
this.__persisted = state;
}
/**
* Get the persisted status of the record
*
* @memberOf Record
*/
public getPersisted(): boolean {
return this.__persisted;
}
/**
* Get the URL that should be used for the API calls
*
* @private
* @returns {string} API URL
*
* @memberOf Record
*/
private __getUrl(options?: IRequestOptions, ignoreSelf?: boolean): string {
const links: IDictionary<JsonApi.ILink> = this.getLinks();
if (!ignoreSelf && links && links.self) {
const self: JsonApi.ILink = links.self;
/* istanbul ignore next */
return typeof self === 'string' ? self : self.href;
}
/* istanbul ignore next */
const type = getValue<string>(this.static.endpoint) || this.getRecordType() || this.static.type;
return buildUrl(type, this.__persisted ? this.getRecordId() : null, null, options);
}
} | the_stack |
import {DialogButton} from "../../../scripts/clipperUI/panels/dialogPanel";
import {RatingsPanel} from "../../../scripts/clipperUI/panels/ratingsPanel";
import {Clipper} from "../../../scripts/clipperUI/frontEndGlobals";
import {RatingsHelper, RatingsPromptStage} from "../../../scripts/clipperUI/ratingsHelper";
import {SmartValue} from "../../../scripts/communicator/smartValue";
import {StubSessionLogger} from "../../../scripts/logging/stubSessionLogger";
import {ClipperStorageKeys} from "../../../scripts/storage/clipperStorageKeys";
import {Constants} from "../../../scripts/constants";
import {ObjectUtils} from "../../../scripts/objectUtils";
import {Settings} from "../../../scripts/settings";
import {MithrilUtils} from "../../mithrilUtils";
import {MockProps} from "../../mockProps";
import {TestModule} from "../../testModule";
module TestConstants {
export module LogCategories {
export var oneNoteClipperUsage = "OneNoteClipperUsage";
}
export module Urls {
export var clipperFeedbackUrl = "https://www.onenote.com/feedback";
}
}
export class RatingsPanelTests extends TestModule {
protected module() {
return "ratingsPanel";
}
protected beforeEach() {
Settings.setSettingsJsonForTesting({});
RatingsHelper.preCacheNeededValues();
}
protected tests() {
test("'Positive' click at RatingsPromptStage.Init goes to RatingsPromptStage.Rate when rate url exists", (assert: QUnitAssert) => {
let done = assert.async();
Settings.setSettingsJsonForTesting({
"ChromeExtension_RatingUrl": {
"Value": "https://chrome.google.com/webstore/detail/onenote-web-clipper/reviews"
}
});
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
let initPositive = document.getElementById(Constants.Ids.ratingsButtonInitYes);
MithrilUtils.simulateAction(() => {
initPositive.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.Rate]);
Clipper.getStoredValue(ClipperStorageKeys.doNotPromptRatings, (doNotPromptRatingsAsStr: string) => {
strictEqual(doNotPromptRatingsAsStr, "true");
done();
});
});
test("'Positive' click at RatingsPromptStage.Init goes to RatingsPromptStage.End when rate url does not exist", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
let initPositive = document.getElementById(Constants.Ids.ratingsButtonInitYes);
MithrilUtils.simulateAction(() => {
initPositive.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.End]);
Clipper.getStoredValue(ClipperStorageKeys.doNotPromptRatings, (doNotPromptRatingsAsStr: string) => {
strictEqual(doNotPromptRatingsAsStr, "true");
done();
});
});
test("'Negative' click at RatingsPromptStage.Init without a prior bad rating goes to RatingsPromptStage.Feedback when feedback url exists (and doNotPromptRatings === undefined)", (assert: QUnitAssert) => {
let done = assert.async();
Settings.setSettingsJsonForTesting({
"LogCategory_RatingsPrompt": {
"Value": TestConstants.LogCategories.oneNoteClipperUsage
}
});
Clipper.storeValue(ClipperStorageKeys.lastSeenVersion, "3.1.0");
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
let initNegative = document.getElementById(Constants.Ids.ratingsButtonInitNo);
MithrilUtils.simulateAction(() => {
initNegative.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.Feedback]);
Clipper.getStoredValue(ClipperStorageKeys.doNotPromptRatings, (doNotPromptRatingsAsStr: string) => {
strictEqual(doNotPromptRatingsAsStr, undefined, "doNotPromptRatings should be undefined");
done();
});
});
test("'Negative' click at RatingsPromptStage.Init without a prior bad rating goes to RatingsPromptStage.End when feedback url does not exist (and doNotPromptRatings === undefined)", (assert: QUnitAssert) => {
let done = assert.async();
Clipper.storeValue(ClipperStorageKeys.lastSeenVersion, "3.1.0");
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
let initNegative = document.getElementById(Constants.Ids.ratingsButtonInitNo);
MithrilUtils.simulateAction(() => {
initNegative.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.End]);
Clipper.getStoredValue(ClipperStorageKeys.doNotPromptRatings, (doNotPromptRatingsAsStr: string) => {
strictEqual(doNotPromptRatingsAsStr, undefined, "doNotPromptRatings should be undefined");
done();
});
});
test("'Negative' click at RatingsPromptStage.Init with a prior bad rating sets doNotPromptRatings to 'true' (feedback url exists)", (assert: QUnitAssert) => {
let done = assert.async();
Settings.setSettingsJsonForTesting({
"LogCategory_RatingsPrompt": {
"Value": TestConstants.LogCategories.oneNoteClipperUsage
}
});
Clipper.storeValue(ClipperStorageKeys.lastBadRatingDate, (Date.now() - Constants.Settings.minTimeBetweenBadRatings).toString());
Clipper.storeValue(ClipperStorageKeys.lastSeenVersion, "3.1.0");
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
let initNegative = document.getElementById(Constants.Ids.ratingsButtonInitNo);
MithrilUtils.simulateAction(() => {
initNegative.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.Feedback]);
Clipper.getStoredValue(ClipperStorageKeys.doNotPromptRatings, (doNotPromptRatingsAsStr: string) => {
strictEqual(doNotPromptRatingsAsStr, "true");
done();
});
});
test("'Negative' click at RatingsPromptStage.Init with a prior bad rating sets doNotPromptRatings to 'true' (feedback url does not exist)", (assert: QUnitAssert) => {
let done = assert.async();
Clipper.storeValue(ClipperStorageKeys.lastBadRatingDate, (Date.now() - Constants.Settings.minTimeBetweenBadRatings).toString());
Clipper.storeValue(ClipperStorageKeys.lastSeenVersion, "3.1.0");
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
let initNegative = document.getElementById(Constants.Ids.ratingsButtonInitNo);
MithrilUtils.simulateAction(() => {
initNegative.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.End]);
Clipper.getStoredValue(ClipperStorageKeys.doNotPromptRatings, (doNotPromptRatingsAsStr: string) => {
strictEqual(doNotPromptRatingsAsStr, "true");
done();
});
});
test("'Rate' click at RatingsPromptStage.Rate goes to RatingsPromptStage.End when rate url exists", () => {
Settings.setSettingsJsonForTesting({
"ChromeExtension_RatingUrl": {
"Value": "https://chrome.google.com/webstore/detail/onenote-web-clipper/reviews"
}
});
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
// skip to RATE panel
controllerInstance.setState({ currentRatingsPromptStage: RatingsPromptStage.Rate });
m.redraw(true);
let ratePositive = document.getElementById(Constants.Ids.ratingsButtonRateYes);
MithrilUtils.simulateAction(() => {
ratePositive.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.End]);
});
test("'Rate' click at RatingsPromptStage.Rate not available when rate url does not exist (unexpected scenario)", () => {
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
// skip to RATE panel
controllerInstance.setState({ currentRatingsPromptStage: RatingsPromptStage.Rate });
m.redraw(true);
let ratePositive = document.getElementById(Constants.Ids.ratingsButtonRateYes);
ok(ObjectUtils.isNullOrUndefined(ratePositive), "'Rate' button should not exist");
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.None]);
});
test("'No Thanks' click at RatingsPromptStage.Rate goes to RatingsPromptStage.None when rate url exists", () => {
Settings.setSettingsJsonForTesting({
"ChromeExtension_RatingUrl": {
"Value": "https://chrome.google.com/webstore/detail/onenote-web-clipper/reviews"
}
});
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
// skip to RATE panel
controllerInstance.setState({ currentRatingsPromptStage: RatingsPromptStage.Rate });
m.redraw(true);
let rateNegative = document.getElementById(Constants.Ids.ratingsButtonRateNo);
MithrilUtils.simulateAction(() => {
rateNegative.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.None]);
});
test("'No Thanks' click at RatingsPromptStage.Rate not available when rate url does not exist (unexpected scenario)", () => {
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
// skip to RATE panel
controllerInstance.setState({ currentRatingsPromptStage: RatingsPromptStage.Rate });
m.redraw(true);
let rateNegative = document.getElementById(Constants.Ids.ratingsButtonRateNo);
ok(ObjectUtils.isNullOrUndefined(rateNegative), "'No Thanks' button should not exist");
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.None]);
});
test("'Feedback' click at RatingsPromptStage.Feedback goes to RatingsPromptStage.End when feedback url exists", () => {
Settings.setSettingsJsonForTesting({
"LogCategory_RatingsPrompt": {
"Value": TestConstants.LogCategories.oneNoteClipperUsage
}
});
Clipper.storeValue(ClipperStorageKeys.lastSeenVersion, "3.1.0");
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
// skip to FEEDBACK panel
controllerInstance.setState({ currentRatingsPromptStage: RatingsPromptStage.Feedback });
m.redraw(true);
let feedbackPositive = document.getElementById(Constants.Ids.ratingsButtonFeedbackYes);
MithrilUtils.simulateAction(() => {
feedbackPositive.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.End]);
});
test("'Feedback' click at RatingsPromptStage.Feedback not available when feedback url does not exist (unexpected scenario)", () => {
Clipper.storeValue(ClipperStorageKeys.lastSeenVersion, "3.1.0");
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
// skip to FEEDBACK panel
controllerInstance.setState({ currentRatingsPromptStage: RatingsPromptStage.Feedback });
m.redraw(true);
let feedbackPositive = document.getElementById(Constants.Ids.ratingsButtonFeedbackYes);
ok(ObjectUtils.isNullOrUndefined(feedbackPositive), "'Feedback' button should not exist");
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.None]);
});
test("'No Thanks' click at RatingsPromptStage.Feedback goes to RatingsPromptStage.None when feedback url exists", () => {
Settings.setSettingsJsonForTesting({
"LogCategory_RatingsPrompt": {
"Value": TestConstants.LogCategories.oneNoteClipperUsage
}
});
Clipper.storeValue(ClipperStorageKeys.lastSeenVersion, "3.1.0");
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
// skip to FEEDBACK panel
controllerInstance.setState({ currentRatingsPromptStage: RatingsPromptStage.Feedback });
m.redraw(true);
let feedbackNegative = document.getElementById(Constants.Ids.ratingsButtonFeedbackNo);
MithrilUtils.simulateAction(() => {
feedbackNegative.click();
});
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.None]);
});
test("'No Thanks' click at RatingsPromptStage.Feedback not available when feedback url does not exist (unexpected scenario)", () => {
Clipper.storeValue(ClipperStorageKeys.lastSeenVersion, "3.1.0");
let clipperState = MockProps.getMockClipperState();
clipperState.showRatingsPrompt = true;
let ratingsPanel = <RatingsPanel clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(ratingsPanel);
// skip to FEEDBACK panel
controllerInstance.setState({ currentRatingsPromptStage: RatingsPromptStage.Feedback });
m.redraw(true);
let feedbackNegative = document.getElementById(Constants.Ids.ratingsButtonFeedbackNo);
ok(ObjectUtils.isNullOrUndefined(feedbackNegative), "'No Thanks' button should not exist");
strictEqual(RatingsPromptStage[controllerInstance.state.userSelectedRatingsPromptStage], RatingsPromptStage[RatingsPromptStage.None]);
});
}
}
(new RatingsPanelTests()).runTests(); | the_stack |
import '../../shared/gr-icons/gr-icons';
import '../gr-change-list/gr-change-list';
import '../gr-repo-header/gr-repo-header';
import '../gr-user-header/gr-user-header';
import {page} from '../../../utils/page-wrapper-utils';
import {GerritNav} from '../../core/gr-navigation/gr-navigation';
import {AppElementParams} from '../../gr-app-types';
import {
AccountDetailInfo,
AccountId,
ChangeInfo,
EmailAddress,
PreferencesInput,
RepoName,
} from '../../../types/common';
import {ChangeStarToggleStarDetail} from '../../shared/gr-change-star/gr-change-star';
import {ChangeListViewState} from '../../../types/types';
import {fire, fireTitleChange} from '../../../utils/event-util';
import {getAppContext} from '../../../services/app-context';
import {GerritView} from '../../../services/router/router-model';
import {RELOAD_DASHBOARD_INTERVAL_MS} from '../../../constants/constants';
import {sharedStyles} from '../../../styles/shared-styles';
import {LitElement, PropertyValues, html, css} from 'lit';
import {customElement, property, state, query} from 'lit/decorators';
import {ValueChangedEvent} from '../../../types/events';
const LOOKUP_QUERY_PATTERNS: RegExp[] = [
/^\s*i?[0-9a-f]{7,40}\s*$/i, // CHANGE_ID
/^\s*[1-9][0-9]*\s*$/g, // CHANGE_NUM
/[0-9a-f]{40}/, // COMMIT
];
const USER_QUERY_PATTERN = /^owner:\s?("[^"]+"|[^ ]+)$/;
const REPO_QUERY_PATTERN =
/^project:\s?("[^"]+"|[^ ]+)(\sstatus\s?:(open|"open"))?$/;
const LIMIT_OPERATOR_PATTERN = /\blimit:(\d+)/i;
@customElement('gr-change-list-view')
export class GrChangeListView extends LitElement {
/**
* Fired when the title of the page should change.
*
* @event title-change
*/
@query('#prevArrow') protected prevArrow?: HTMLAnchorElement;
@query('#nextArrow') protected nextArrow?: HTMLAnchorElement;
@property({type: Object})
params?: AppElementParams;
@property({type: Object})
account: AccountDetailInfo | null = null;
@property({type: Object})
viewState: ChangeListViewState = {};
@property({type: Object})
preferences?: PreferencesInput;
// private but used in test
@state() changesPerPage?: number;
// private but used in test
@state() query = '';
// private but used in test
@state() offset?: number;
// private but used in test
@state() changes?: ChangeInfo[];
// private but used in test
@state() loading = true;
// private but used in test
@state() userId: AccountId | EmailAddress | null = null;
// private but used in test
@state() repo: RepoName | null = null;
private readonly restApiService = getAppContext().restApiService;
private reporting = getAppContext().reportingService;
private lastVisibleTimestampMs = 0;
constructor() {
super();
this.addEventListener('next-page', () => this.handleNextPage());
this.addEventListener('previous-page', () => this.handlePreviousPage());
this.addEventListener('reload', () => this.reload());
// We are not currently verifying if the view is actually visible. We rely
// on gr-app-element to restamp the component if view changes
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
if (
Date.now() - this.lastVisibleTimestampMs >
RELOAD_DASHBOARD_INTERVAL_MS
)
this.reload();
} else {
this.lastVisibleTimestampMs = Date.now();
}
});
}
override connectedCallback() {
super.connectedCallback();
this.loadPreferences();
}
static override get styles() {
return [
sharedStyles,
css`
:host {
display: block;
}
.loading {
color: var(--deemphasized-text-color);
padding: var(--spacing-l);
}
gr-change-list {
width: 100%;
}
gr-user-header,
gr-repo-header {
border-bottom: 1px solid var(--border-color);
}
nav {
align-items: center;
display: flex;
height: 3rem;
justify-content: flex-end;
margin-right: 20px;
}
nav,
iron-icon {
color: var(--deemphasized-text-color);
}
iron-icon {
height: 1.85rem;
margin-left: 16px;
width: 1.85rem;
}
.hide {
display: none;
}
@media only screen and (max-width: 50em) {
.loading,
.error {
padding: 0 var(--spacing-l);
}
}
`,
];
}
override render() {
if (this.loading) return html`<div class="loading">Loading...</div>`;
const loggedIn = !!(this.account && Object.keys(this.account).length > 0);
return html`
<div>
${this.renderRepoHeader()} ${this.renderUserHeader(loggedIn)}
<gr-change-list
.account=${this.account}
.changes=${this.changes}
.preferences=${this.preferences}
.selectedIndex=${this.viewState.selectedChangeIndex}
.showStar=${loggedIn}
@selected-index-changed=${(e: ValueChangedEvent<number>) => {
this.handleSelectedIndexChanged(e);
}}
@toggle-star=${(e: CustomEvent<ChangeStarToggleStarDetail>) => {
this.handleToggleStar(e);
}}
></gr-change-list>
${this.renderChangeListViewNav()}
</div>
`;
}
private renderRepoHeader() {
if (!this.repo) return;
return html` <gr-repo-header .repo=${this.repo}></gr-repo-header> `;
}
private renderUserHeader(loggedIn: boolean) {
if (!this.userId) return;
return html`
<gr-user-header
.userId=${this.userId}
showDashboardLink
.loggedIn=${loggedIn}
></gr-user-header>
`;
}
private renderChangeListViewNav() {
if (this.loading || !this.changes || !this.changes.length) return;
return html`
<nav>
Page ${this.computePage()} ${this.renderPrevArrow()}
${this.renderNextArrow()}
</nav>
`;
}
private renderPrevArrow() {
if (this.offset === 0) return;
return html`
<a id="prevArrow" href="${this.computeNavLink(-1)}">
<iron-icon icon="gr-icons:chevron-left" aria-label="Older"> </iron-icon>
</a>
`;
}
private renderNextArrow() {
if (
!(
this.changes?.length &&
this.changes[this.changes.length - 1]._more_changes
)
)
return;
return html`
<a id="nextArrow" href="${this.computeNavLink(1)}">
<iron-icon icon="gr-icons:chevron-right" aria-label="Newer">
</iron-icon>
</a>
`;
}
override willUpdate(changedProperties: PropertyValues) {
if (changedProperties.has('params')) {
this.paramsChanged();
}
if (changedProperties.has('changes')) {
this.changesChanged();
}
}
reload() {
if (this.loading) return;
this.loading = true;
this.getChanges().then(changes => {
this.changes = changes || [];
this.loading = false;
});
}
private paramsChanged() {
const value = this.params;
if (!value || value.view !== GerritView.SEARCH) return;
this.loading = true;
this.query = value.query;
const offset = Number(value.offset);
this.offset = isNaN(offset) ? 0 : offset;
if (
this.viewState.query !== this.query ||
this.viewState.offset !== this.offset
) {
this.viewState.selectedChangeIndex = 0;
this.viewState.query = this.query;
this.viewState.offset = this.offset;
fire(this, 'view-state-changed', {value: this.viewState});
}
// NOTE: This method may be called before attachment. Fire title-change
// in an async so that attachment to the DOM can take place first.
setTimeout(() => fireTitleChange(this, this.query));
this.restApiService
.getPreferences()
.then(prefs => {
if (!prefs) {
throw new Error('getPreferences returned undefined');
}
this.changesPerPage = prefs.changes_per_page;
return this.getChanges();
})
.then(changes => {
changes = changes || [];
if (this.query && changes.length === 1) {
for (const queryPattern of LOOKUP_QUERY_PATTERNS) {
if (this.query.match(queryPattern)) {
// "Back"/"Forward" buttons work correctly only with
// opt_redirect options
GerritNav.navigateToChange(changes[0], {
redirect: true,
});
return;
}
}
}
this.changes = changes;
this.loading = false;
});
}
private loadPreferences() {
return this.restApiService.getLoggedIn().then(loggedIn => {
if (loggedIn) {
this.restApiService.getPreferences().then(preferences => {
this.preferences = preferences;
});
} else {
this.preferences = {};
}
});
}
// private but used in test
getChanges() {
return this.restApiService.getChanges(
this.changesPerPage,
this.query,
this.offset
);
}
// private but used in test
limitFor(query: string, defaultLimit?: number) {
if (defaultLimit === undefined) return 0;
const match = query.match(LIMIT_OPERATOR_PATTERN);
if (!match) {
return defaultLimit;
}
return Number(match[1]);
}
// private but used in test
computeNavLink(direction: number) {
const offset = this.offset ?? 0;
const limit = this.limitFor(this.query, this.changesPerPage);
const newOffset = Math.max(0, offset + limit * direction);
return GerritNav.getUrlForSearchQuery(this.query, newOffset);
}
// private but used in test
handleNextPage() {
if (!this.nextArrow || !this.changesPerPage) return;
page.show(this.computeNavLink(1));
}
// private but used in test
handlePreviousPage() {
if (!this.prevArrow || !this.changesPerPage) return;
page.show(this.computeNavLink(-1));
}
private changesChanged() {
this.userId = null;
this.repo = null;
const changes = this.changes;
if (!changes || !changes.length) {
return;
}
if (USER_QUERY_PATTERN.test(this.query)) {
const owner = changes[0].owner;
const userId = owner._account_id ? owner._account_id : owner.email;
if (userId) {
this.userId = userId;
return;
}
}
if (REPO_QUERY_PATTERN.test(this.query)) {
this.repo = changes[0].project;
}
}
// private but used in test
computePage() {
if (this.offset === undefined || this.changesPerPage === undefined) return;
return this.offset / this.changesPerPage + 1;
}
private handleToggleStar(e: CustomEvent<ChangeStarToggleStarDetail>) {
if (e.detail.starred) {
this.reporting.reportInteraction('change-starred-from-change-list');
}
this.restApiService.saveChangeStarred(
e.detail.change._number,
e.detail.starred
);
}
private handleSelectedIndexChanged(e: ValueChangedEvent<number>) {
if (!this.viewState) return;
this.viewState.selectedChangeIndex = e.detail.value;
fire(this, 'view-state-changed', {value: this.viewState});
}
}
declare global {
interface HTMLElementEventMap {
'view-state-changed': ValueChangedEvent<ChangeListViewState>;
}
interface HTMLElementTagNameMap {
'gr-change-list-view': GrChangeListView;
}
} | the_stack |
var objectCreate = Object.create || objectCreatePolyfill;
var objectKeys = Object.keys || objectKeysPolyfill;
var bind = Function.prototype.bind || functionBindPolyfill;
// By default Dispatchers will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
let defaultMaxListeners = 10;
export default class EventEmitter {
static listenerCount(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
}
static defaultMaxListeners: number;
_maxListeners?: number;
_eventsCount: number;
_events: any;
constructor() {
if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
this._events = objectCreate(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
}
// // Obviously not all Emitters should be limited to 10. This function allows
// // that to be increased. Set to zero for unlimited.
// setMaxListeners(n) {
// if (typeof n !== 'number' || n < 0 || isNaN(n))
// throw new TypeError('"n" argument must be a positive number');
// this._maxListeners = n;
// return this;
// }
//
// getMaxListeners() {
// return $getMaxListeners(this);
// }
emit(type: string, ...rest) {
var er, handler, len, args, i, events;
var doError = type === 'error';
events = this._events;
if (events) doError = doError && events.error == null;
else if (!doError) return false;
// If there is no 'error' event listener then throw.
if (doError) {
if (arguments.length > 1) er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Unhandled "error" event. (' + er + ')');
err['context'] = er;
throw err;
}
}
handler = events[type];
if (!handler) return false;
var isFn = typeof handler === 'function';
len = arguments.length;
switch (len) {
// fast cases
case 1:
emitNone(handler, isFn, this);
break;
case 2:
emitOne(handler, isFn, this, arguments[1]);
break;
case 3:
emitTwo(handler, isFn, this, arguments[1], arguments[2]);
break;
case 4:
emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
break;
// slower
default:
args = new Array(len - 1);
for (i = 1; i < len; i++) args[i - 1] = arguments[i];
emitMany(handler, isFn, this, args);
}
return true;
}
on(type: string, listener: Function) {
return _addListener(this, type, listener);
}
once(type, listener) {
if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
this.on(type, _onceWrap(this, type, listener));
return this;
}
off(type, listener) {
return _removeListener.call(this, type, listener);
}
removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (!events) return this;
// not listening for off, no need to emit
if (!events.off) {
if (arguments.length === 0) {
this._events = objectCreate(null);
this._eventsCount = 0;
} else if (events[type]) {
if (--this._eventsCount === 0) this._events = objectCreate(null);
else delete events[type];
}
return this;
}
// emit off for all listeners on all events
if (arguments.length === 0) {
var keys = objectKeys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'off') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('off');
this._events = objectCreate(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.off(type, listeners);
} else if (listeners) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.off(type, listeners[i]);
}
}
return this;
}
listeners(type) {
return _listeners(this, type, true);
}
rawListeners(type) {
return _listeners(this, type, false);
}
listenerCount() {
return EventEmitter.listenerCount.apply(this, arguments);
}
}
let hasDefineProperty;
try {
var o = {};
if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
hasDefineProperty = o['x'] === 0;
} catch (err) {
hasDefineProperty = false;
}
if (hasDefineProperty) {
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function () {
return defaultMaxListeners;
},
set: function (arg) {
// check whether the input is a positive number (whose value is zero or
// greater and not a NaN).
if (typeof arg !== 'number' || arg < 0 || arg !== arg)
throw new TypeError('"defaultMaxListeners" must be a positive number');
defaultMaxListeners = arg;
}
});
} else {
EventEmitter.defaultMaxListeners = defaultMaxListeners;
}
function $getMaxListeners(that) {
if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
// These standalone emit* functions are used to optimize calling of event
// handlers for fast cases because emit() itself often has a variable number of
// arguments and can be deoptimized because of that. These functions always have
// the same number of arguments and thus do not get deoptimized, so the code
// inside them can execute faster.
function emitNone(handler, isFn, self) {
if (isFn) handler.call(self);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
try {
listeners[i].call(self);
} catch (e) {
console.error(e);
}
}
}
}
function emitOne(handler, isFn, self, arg1) {
if (isFn) handler.call(self, arg1);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
try {
listeners[i].call(self, arg1);
} catch (e) {
console.error(e);
}
}
}
}
function emitTwo(handler, isFn, self, arg1, arg2) {
if (isFn) handler.call(self, arg1, arg2);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
try {
listeners[i].call(self, arg1, arg2);
} catch (e) {
console.error(e);
}
}
}
}
function emitThree(handler, isFn, self, arg1, arg2, arg3) {
if (isFn) handler.call(self, arg1, arg2, arg3);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
try {
listeners[i].call(self, arg1, arg2, arg3);
} catch (e) {
console.error(e);
}
}
}
}
function emitMany(handler, isFn, self, args) {
if (isFn) handler.apply(self, args);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
try {
listeners[i].apply(self, args);
} catch (e) {
console.error(e);
}
}
}
}
function _addListener(target: EventEmitter, type, listener: Function) {
var m;
var events;
var existing;
if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
events = target._events;
if (!events) {
events = target._events = objectCreate(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener) {
target.emit('newListener', type, listener['listener'] ? listener['listener'] : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (!existing) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] = [existing, listener];
} else {
existing.push(listener);
}
// Check for listener leak
if (!existing.warned) {
m = $getMaxListeners(target);
if (m && m > 0 && existing.length > m) {
existing.warned = true;
class CustomError extends Error {
emitter: any;
type: string;
count: number;
}
let w: CustomError = new CustomError(
'Possible Dispatcher memory leak detected. ' +
existing.length +
' "' +
String(type) +
'" listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit.'
);
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
if (typeof console === 'object' && console.warn) {
console.warn('%s: %s', w.name, w.message);
}
}
}
}
return target;
}
function _removeListener(type, listener) {
var list, events, position, i, originalListener;
if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
events = this._events;
if (!events) return this;
list = events[type];
if (!list) return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0) this._events = objectCreate(null);
else {
delete events[type];
if (events.off) this.emit('off', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0) return this;
if (position === 0) list.shift();
else spliceOne(list, position);
if (list.length === 1) events[type] = list[0];
if (events.off) this.emit('off', type, originalListener || listener);
}
return this;
}
function onceWrapper() {
if (!this.fired) {
this.target.off(this.type, this.wrapFn);
this.fired = true;
switch (arguments.length) {
case 0:
return this.listener.call(this.target);
case 1:
return this.listener.call(this.target, arguments[0]);
case 2:
return this.listener.call(this.target, arguments[0], arguments[1]);
case 3:
return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]);
default:
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) args[i] = arguments[i];
this.listener.apply(this.target, args);
}
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = bind.call(onceWrapper, state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
function _listeners(target, type, unwrap) {
var events = target._events;
if (!events) return [];
var evlistener = events[type];
if (!evlistener) return [];
if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
function listenerCount(type) {
var events = this._events;
if (events) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener) {
return evlistener.length;
}
}
return 0;
}
// About 1.5x faster than the two-arg version of Array#splice().
function spliceOne(list, index) {
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k];
list.pop();
}
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i) copy[i] = arr[i];
return copy;
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function objectCreatePolyfill(proto) {
var F = function () {};
F.prototype = proto;
return new F();
}
function objectKeysPolyfill(obj) {
var keys = [];
for (var k in obj)
if (Object.prototype.hasOwnProperty.call(obj, k)) {
keys.push(k);
}
return k;
}
function functionBindPolyfill(context) {
var fn = this;
return function () {
return fn.apply(context, arguments);
};
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [apigateway-v2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonapigatewaymanagementv2.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class ApigatewayV2 extends PolicyStatement {
public servicePrefix = 'apigateway';
/**
* Statement provider for service [apigateway-v2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonapigatewaymanagementv2.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 delete a particular resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/API_DELETE.html
*/
public toDELETE() {
return this.to('DELETE');
}
/**
* Grants permission to read a particular resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/API_GET.html
*/
public toGET() {
return this.to('GET');
}
/**
* Grants permission to update a particular resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/API_PATCH.html
*/
public toPATCH() {
return this.to('PATCH');
}
/**
* Grants permission to create a particular resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/API_POST.html
*/
public toPOST() {
return this.to('POST');
}
/**
* Grants permission to update a particular resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/API_PUT.html
*/
public toPUT() {
return this.to('PUT');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"DELETE",
"PATCH",
"POST",
"PUT"
],
"Read": [
"GET"
]
};
/**
* Adds a resource of type AccessLogSettings to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param stageName - Identifier for the stageName.
* @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 onAccessLogSettings(apiId: string, stageName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}/accesslogsettings';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${StageName}', stageName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Api to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @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:
* - .ifRequestApiKeyRequired()
* - .ifRequestApiName()
* - .ifRequestAuthorizerType()
* - .ifRequestAuthorizerUri()
* - .ifRequestDisableExecuteApiEndpoint()
* - .ifRequestEndpointType()
* - .ifRequestRouteAuthorizationType()
* - .ifResourceApiKeyRequired()
* - .ifResourceApiName()
* - .ifResourceAuthorizerType()
* - .ifResourceAuthorizerUri()
* - .ifResourceDisableExecuteApiEndpoint()
* - .ifResourceEndpointType()
* - .ifResourceRouteAuthorizationType()
* - .ifAwsResourceTag()
*/
public onApi(apiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Apis to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @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:
* - .ifRequestApiKeyRequired()
* - .ifRequestApiName()
* - .ifRequestAuthorizerType()
* - .ifRequestAuthorizerUri()
* - .ifRequestDisableExecuteApiEndpoint()
* - .ifRequestEndpointType()
* - .ifRequestRouteAuthorizationType()
* - .ifAwsResourceTag()
*/
public onApis(region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis';
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ApiMapping to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param domainName - Identifier for the domainName.
* @param apiMappingId - Identifier for the apiMappingId.
* @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()
*/
public onApiMapping(domainName: string, apiMappingId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/apimappings/${ApiMappingId}';
arn = arn.replace('${DomainName}', domainName);
arn = arn.replace('${ApiMappingId}', apiMappingId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ApiMappings to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param domainName - Identifier for the domainName.
* @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()
*/
public onApiMappings(domainName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/apimappings';
arn = arn.replace('${DomainName}', domainName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Authorizer to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param authorizerId - Identifier for the authorizerId.
* @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:
* - .ifRequestAuthorizerType()
* - .ifRequestAuthorizerUri()
* - .ifResourceAuthorizerType()
* - .ifResourceAuthorizerUri()
* - .ifAwsResourceTag()
*/
public onAuthorizer(apiId: string, authorizerId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/authorizers/${AuthorizerId}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${AuthorizerId}', authorizerId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Authorizers to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @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:
* - .ifRequestAuthorizerType()
* - .ifRequestAuthorizerUri()
* - .ifAwsResourceTag()
*/
public onAuthorizers(apiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/authorizers';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type AuthorizersCache to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param stageName - Identifier for the stageName.
* @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 onAuthorizersCache(apiId: string, stageName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}/cache/authorizers';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${StageName}', stageName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Cors to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @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 onCors(apiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/cors';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Deployment to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param deploymentId - Identifier for the deploymentId.
* @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()
*/
public onDeployment(apiId: string, deploymentId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/deployments/${DeploymentId}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${DeploymentId}', deploymentId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Deployments to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @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:
* - .ifRequestStageName()
* - .ifAwsResourceTag()
*/
public onDeployments(apiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/deployments';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ExportedAPI to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param specification - Identifier for the specification.
* @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 onExportedAPI(apiId: string, specification: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/exports/${Specification}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Specification}', specification);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Integration to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param integrationId - Identifier for the integrationId.
* @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()
*/
public onIntegration(apiId: string, integrationId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${IntegrationId}', integrationId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Integrations to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @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()
*/
public onIntegrations(apiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type IntegrationResponse to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param integrationId - Identifier for the integrationId.
* @param integrationResponseId - Identifier for the integrationResponseId.
* @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 onIntegrationResponse(apiId: string, integrationId: string, integrationResponseId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}/integrationresponses/${IntegrationResponseId}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${IntegrationId}', integrationId);
arn = arn.replace('${IntegrationResponseId}', integrationResponseId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type IntegrationResponses to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param integrationId - Identifier for the integrationId.
* @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 onIntegrationResponses(apiId: string, integrationId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}/integrationresponses';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${IntegrationId}', integrationId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Model to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param modelId - Identifier for the modelId.
* @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()
*/
public onModel(apiId: string, modelId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models/${ModelId}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${ModelId}', modelId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Models to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @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()
*/
public onModels(apiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ModelTemplate to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param modelId - Identifier for the modelId.
* @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 onModelTemplate(apiId: string, modelId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models/${ModelId}/template';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${ModelId}', modelId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Route to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param routeId - Identifier for the routeId.
* @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:
* - .ifRequestApiKeyRequired()
* - .ifRequestRouteAuthorizationType()
* - .ifResourceApiKeyRequired()
* - .ifResourceRouteAuthorizationType()
* - .ifAwsResourceTag()
*/
public onRoute(apiId: string, routeId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes/${RouteId}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${RouteId}', routeId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Routes to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @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:
* - .ifRequestApiKeyRequired()
* - .ifRequestRouteAuthorizationType()
* - .ifAwsResourceTag()
*/
public onRoutes(apiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type RouteResponse to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param routeId - Identifier for the routeId.
* @param routeResponseId - Identifier for the routeResponseId.
* @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 onRouteResponse(apiId: string, routeId: string, routeResponseId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes/${RouteId}/routeresponses/${RouteResponseId}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${RouteId}', routeId);
arn = arn.replace('${RouteResponseId}', routeResponseId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type RouteResponses to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param routeId - Identifier for the routeId.
* @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 onRouteResponses(apiId: string, routeId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes/${RouteId}/routeresponses';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${RouteId}', routeId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type RouteRequestParameter to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param routeId - Identifier for the routeId.
* @param requestParameterKey - Identifier for the requestParameterKey.
* @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 onRouteRequestParameter(apiId: string, routeId: string, requestParameterKey: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes/${RouteId}/requestparameters/${RequestParameterKey}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${RouteId}', routeId);
arn = arn.replace('${RequestParameterKey}', requestParameterKey);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type RouteSettings to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param stageName - Identifier for the stageName.
* @param routeKey - Identifier for the routeKey.
* @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 onRouteSettings(apiId: string, stageName: string, routeKey: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}/routesettings/${RouteKey}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${StageName}', stageName);
arn = arn.replace('${RouteKey}', routeKey);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Stage to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @param stageName - Identifier for the stageName.
* @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:
* - .ifRequestAccessLoggingDestination()
* - .ifRequestAccessLoggingFormat()
* - .ifResourceAccessLoggingDestination()
* - .ifResourceAccessLoggingFormat()
* - .ifAwsResourceTag()
*/
public onStage(apiId: string, stageName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${StageName}', stageName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Stages to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiId - Identifier for the apiId.
* @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:
* - .ifRequestAccessLoggingDestination()
* - .ifRequestAccessLoggingFormat()
* - .ifAwsResourceTag()
*/
public onStages(apiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages';
arn = arn.replace('${ApiId}', apiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access by access log destination. Available during the CreateStage and UpdateStage operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Stage
* - Stages
*
* @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 ifRequestAccessLoggingDestination(value: string | string[], operator?: Operator | string) {
return this.if(`Request/AccessLoggingDestination`, value, operator || 'StringLike');
}
/**
* Filters access by access log format. Available during the CreateStage and UpdateStage operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Stage
* - Stages
*
* @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 ifRequestAccessLoggingFormat(value: string | string[], operator?: Operator | string) {
return this.if(`Request/AccessLoggingFormat`, value, operator || 'StringLike');
}
/**
* Filters access based on whether an API key is required or not. Available during the CreateRoute and UpdateRoute operations. Also available as a collection during import and reimport
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Apis
* - Route
* - Routes
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifRequestApiKeyRequired(value?: boolean) {
return this.if(`Request/ApiKeyRequired`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by API name. Available during the CreateApi and UpdateApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Apis
*
* @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 ifRequestApiName(value: string | string[], operator?: Operator | string) {
return this.if(`Request/ApiName`, value, operator || 'StringLike');
}
/**
* Filters access by type of authorizer in the request, for example REQUEST or JWT. Available during CreateAuthorizer and UpdateAuthorizer. Also available during import and reimport as an ArrayOfString
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Apis
* - Authorizer
* - Authorizers
*
* @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 ifRequestAuthorizerType(value: string | string[], operator?: Operator | string) {
return this.if(`Request/AuthorizerType`, value, operator || 'StringLike');
}
/**
* Filters access by URI of a Lambda authorizer function. Available during CreateAuthorizer and UpdateAuthorizer. Also available during import and reimport as an ArrayOfString
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Apis
* - Authorizer
* - Authorizers
*
* @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 ifRequestAuthorizerUri(value: string | string[], operator?: Operator | string) {
return this.if(`Request/AuthorizerUri`, value, operator || 'StringLike');
}
/**
* Filters access by status of the default execute-api endpoint. Available during the CreateApi and UpdateApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Apis
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifRequestDisableExecuteApiEndpoint(value?: boolean) {
return this.if(`Request/DisableExecuteApiEndpoint`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by endpoint type. Available during the CreateDomainName, UpdateDomainName, CreateApi, and UpdateApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Apis
*
* @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 ifRequestEndpointType(value: string | string[], operator?: Operator | string) {
return this.if(`Request/EndpointType`, value, operator || 'StringLike');
}
/**
* Filters access by URI of the truststore used for mutual TLS authentication. Available during the CreateDomainName and UpdateDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @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 ifRequestMtlsTrustStoreUri(value: string | string[], operator?: Operator | string) {
return this.if(`Request/MtlsTrustStoreUri`, value, operator || 'StringLike');
}
/**
* Filters access by version of the truststore used for mutual TLS authentication. Available during the CreateDomainName and UpdateDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @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 ifRequestMtlsTrustStoreVersion(value: string | string[], operator?: Operator | string) {
return this.if(`Request/MtlsTrustStoreVersion`, value, operator || 'StringLike');
}
/**
* Filters access by authorization type, for example NONE, AWS_IAM, CUSTOM, JWT. Available during the CreateRoute and UpdateRoute operations. Also available as a collection during import
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Apis
* - Route
* - Routes
*
* @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 ifRequestRouteAuthorizationType(value: string | string[], operator?: Operator | string) {
return this.if(`Request/RouteAuthorizationType`, value, operator || 'StringLike');
}
/**
* Filters access by TLS version. Available during the CreateDomain and UpdateDomain operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @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 ifRequestSecurityPolicy(value: string | string[], operator?: Operator | string) {
return this.if(`Request/SecurityPolicy`, value, operator || 'StringLike');
}
/**
* Filters access by stage name of the deployment that you attempt to create. Available during the CreateDeployment operation
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Deployments
*
* @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 ifRequestStageName(value: string | string[], operator?: Operator | string) {
return this.if(`Request/StageName`, value, operator || 'StringLike');
}
/**
* Filters access by access log destination of the current Stage resource. Available during the UpdateStage and DeleteStage operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Stage
*
* @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 ifResourceAccessLoggingDestination(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/AccessLoggingDestination`, value, operator || 'StringLike');
}
/**
* Filters access by access log format of the current Stage resource. Available during the UpdateStage and DeleteStage operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Stage
*
* @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 ifResourceAccessLoggingFormat(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/AccessLoggingFormat`, value, operator || 'StringLike');
}
/**
* Filters access based on whether an API key is required or not for the existing Route resource. Available during the UpdateRoute and DeleteRoute operations. Also available as a collection during reimport
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Route
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifResourceApiKeyRequired(value?: boolean) {
return this.if(`Resource/ApiKeyRequired`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by API name. Available during the UpdateApi and DeleteApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
*
* @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 ifResourceApiName(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/ApiName`, value, operator || 'StringLike');
}
/**
* Filters access by the current type of authorizer, for example REQUEST or JWT. Available during UpdateAuthorizer and DeleteAuthorizer operations. Also available during import and reimport as an ArrayOfString
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Authorizer
*
* @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 ifResourceAuthorizerType(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/AuthorizerType`, value, operator || 'StringLike');
}
/**
* Filters access by the URI of the current Lambda authorizer associated with the current API. Available during UpdateAuthorizer and DeleteAuthorizer. Also available as a collection during reimport
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Authorizer
*
* @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 ifResourceAuthorizerUri(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/AuthorizerUri`, value, operator || 'StringLike');
}
/**
* Filters access by status of the default execute-api endpoint. Available during the UpdateApi and DeleteApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifResourceDisableExecuteApiEndpoint(value?: boolean) {
return this.if(`Resource/DisableExecuteApiEndpoint`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by endpoint type. Available during the UpdateDomainName, DeleteDomainName, UpdateApi, and DeleteApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
*
* @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 ifResourceEndpointType(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/EndpointType`, value, operator || 'StringLike');
}
/**
* Filters access by URI of the truststore used for mutual TLS authentication. Available during the UpdateDomainName and DeleteDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @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 ifResourceMtlsTrustStoreUri(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/MtlsTrustStoreUri`, value, operator || 'StringLike');
}
/**
* Filters access by version of the truststore used for mutual TLS authentication. Available during the UpdateDomainName and DeleteDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @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 ifResourceMtlsTrustStoreVersion(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/MtlsTrustStoreVersion`, value, operator || 'StringLike');
}
/**
* ilters access by authorization type of the existing Route resource, for example NONE, AWS_IAM, CUSTOM. Available during the UpdateRoute and DeleteRoute operations. Also available as a collection during reimport
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Api
* - Route
*
* @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 ifResourceRouteAuthorizationType(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/RouteAuthorizationType`, value, operator || 'StringLike');
}
/**
* Filters access by TLS version. Available during the UpdateDomainName and DeleteDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @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 ifResourceSecurityPolicy(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/SecurityPolicy`, value, operator || 'StringLike');
}
} | the_stack |
import {ExtraGlamorousProps} from './glamorous-component'
import {
CSSPropertiesCompleteSingle,
CSSPropertiesPseudo,
} from './css-properties'
import {SVGPropertiesCompleteSingle} from './svg-properties'
// The file `./named-built-in-glamorous-components.d.ts` is based off this file
// and should get any updates this file does.
/*
* FIXME:
* Since TypeScript doesn't have
* HTMLDetailsElement, HTMLDialogElement,
* HTMLKeygenElement, HTMLMenuItemElement
* Those components currently has wrong type.
* After TypeScript add those types, plz fix this.
* Reference: https://github.com/Microsoft/TypeScript/issues/17828
*/
export interface HTMLComponent {
A: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Abbr: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Address: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Area: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Article: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Aside: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Audio: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
B: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Base: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Bdi: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Bdo: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Big: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Blockquote: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Body: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Br: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Button: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Canvas: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Caption: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Cite: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Code: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Col: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Colgroup: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Data: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Datalist: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Dd: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Del: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
// TypeScript doesn't have HTMLDetailsElement
Details: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Dfn: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
// TypeScript doesn't have HTMLDialogElement
Dialog: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Div: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Dl: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Dt: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Em: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Embed: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Fieldset: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Figcaption: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Figure: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Footer: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Form: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
H1: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
H2: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
H3: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
H4: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
H5: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
H6: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Head: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Header: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Hgroup: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Hr: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Html: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
I: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Iframe: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Img: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Input: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Ins: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Kbd: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
// TypeScript doesn't have HTMLKeygenElement
Keygen: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Label: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Legend: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Li: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Link: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Main: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Map: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Mark: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Menu: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
// TypeScript doesn't have HTMLMenuItemElement
Menuitem: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Meta: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Meter: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Nav: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Noscript: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Object: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Ol: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Optgroup: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Option: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Output: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
P: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Param: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Picture: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Pre: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Progress: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Q: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Rp: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Rt: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Ruby: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
S: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Samp: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Script: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Section: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Select: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Small: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Source: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Span: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Strong: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Style: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Sub: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Summary: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Sup: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Table: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Tbody: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Td: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Textarea: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Tfoot: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Th: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Thead: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Time: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Title: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Tr: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Track: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
U: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Ul: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Var: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Video: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
Wbr: preact.FunctionalComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
JSX.HTMLAttributes
>
}
export interface SVGComponent {
Circle: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
ClipPath: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Defs: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Ellipse: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
G: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Image: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Line: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
LinearGradient: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Mask: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Path: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Pattern: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Polygon: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Polyline: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
RadialGradient: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Rect: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Stop: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Svg: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Text: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
Tspan: preact.FunctionalComponent<
SVGPropertiesCompleteSingle & ExtraGlamorousProps & JSX.SVGAttributes
>
} | the_stack |
import { ColorPaletteDirective } from './color-palette.directive';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClient, HttpHandler } from '@angular/common/http';
import { ViewContainerRef, Component, DebugElement, ElementRef } from '@angular/core';
import { By } from '@angular/platform-browser';
// Simple test component that will not in the actual app
@Component({
selector: 'testColor',
template: `
<input type="text" amexioColorPalette>
`
})
class colorTestComponent {
}
describe('Directive: Color', () => {
let comp: colorTestComponent;
let fixture: ComponentFixture<colorTestComponent>;
let inputEl: DebugElement;
let dirIn: any;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ColorPaletteDirective, colorTestComponent],
providers: [HttpClient, HttpHandler, ViewContainerRef],
});
fixture = TestBed.createComponent(colorTestComponent);
comp = fixture.componentInstance;
const directiveEl = fixture.debugElement.query(By.directive(ColorPaletteDirective));
expect(directiveEl).not.toBeNull();
dirIn = directiveEl.injector.get(ColorPaletteDirective);
inputEl = fixture.debugElement.query(By.css('input'));
dirIn.gradient = true;
dirIn.themejson = [
{
themeName: 'amexio-primary-darker-color',
},
{
themeName: 'amexio-theme-color1',
},
{
themeName: 'amexio-theme-color2',
},
{
themeName: 'amexio-theme-color3',
},
{
themeName: 'amexio-theme-color4',
},
{
themeName: 'amexio-theme-color5',
},
{
themeName: 'amexio-theme-color6',
}];
dirIn.gradientThemeJson = [
{
themeName: 'amexio-primary-darker-color-Gradient',
},
{
themeName: 'amexio-theme-color1-Gradient',
},
{
themeName: 'amexio-theme-color2-Gradient',
},
{
themeName: 'amexio-theme-color3-Gradient',
},
{
themeName: 'amexio-theme-color4-Gradient',
},
{
themeName: 'amexio-theme-color5-Gradient',
},
{
themeName: 'amexio-theme-color6-Gradient',
},
];
});
it('should create component', () => {
const debugEl: HTMLElement = fixture.debugElement.nativeElement;
const p: HTMLElement = debugEl.querySelector('p');
});
it('vibrantThemeCall method', () => {
dirIn.gradient = true;
dirIn.vibrantThemeCall();
expect(dirIn.gradient).toEqual(true);
setTimeout(() => {
dirIn.getBGColorStyles(dirIn.hostComponent);
}, 1000);
dirIn.gradient = false;
dirIn.vibrantThemeCall();
expect(dirIn.gradient).toEqual(false);
setTimeout(() => {
dirIn.getGradientStyles(dirIn.hostComponent);
}, 1000);
});
it('getBGColorStyles()case1', () => {
let obj = { amexioComponentId: 'amexio-card', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-card';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
// navbar = 'amexio-navbar';
// static accordion = 'amexio-accordion';
// static panel = 'amexio-panel';
// static window = 'amexio-window';
// static dialogue = 'amexio-dialogue';
// static grid = 'amexio-grid';
// static box = 'amexio-box';
// static tab = 'amexio-tab';
// static banner = 'amexio-banner';
// static floatingpanel = 'amexio-floating-panel';
dirIn.ColorPaletteConstants = { card: c, cardce: c, }
expect(dirIn.ColorPaletteConstants.card).toBeUndefined();
expect(dirIn.ColorPaletteConstants.cardce).toBeUndefined();
dirIn.ColorPaletteConstants = { card: 'amexio-card', cardce: 'amexio-card-ce' };
dirIn.ColorPaletteConstants.card = 'amexio-card'
dirIn.ColorPaletteConstants.cardce = 'amexio-card-ce'
expect(dirIn.ColorPaletteConstants.card).toBeDefined();
expect(dirIn.ColorPaletteConstants.cardce).toBeDefined();
});
it('getBGColorStyles()case2', () => {
let obj = { amexioComponentId: 'amexio-banner', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-banner';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { banner: c };
expect(dirIn.ColorPaletteConstants.banner).toBeUndefined();
dirIn.ColorPaletteConstants = { banner: 'amexio-banner' };
dirIn.ColorPaletteConstants.banner = 'amexio-banner'
expect(dirIn.ColorPaletteConstants.banner).toBeDefined();
});
it('getBGColorStyles()case3', () => {
let obj = { amexioComponentId: 'amexio-navbar', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-navbar';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { navbar: c };
expect(dirIn.ColorPaletteConstants.banner).toBeUndefined();
dirIn.ColorPaletteConstants = { navbar: 'amexio-navbar' };
dirIn.ColorPaletteConstants.navbar = 'amexio-navbar'
expect(dirIn.ColorPaletteConstants.navbar).toBeDefined();
});
it('getBGColorStyles()case4', () => {
let obj = { amexioComponentId: 'amexio-accordion', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-accordion';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { accordion: c };
expect(dirIn.ColorPaletteConstants.accordion).toBeUndefined();
dirIn.ColorPaletteConstants = { accordion: 'amexio-accordion' };
dirIn.ColorPaletteConstants.accordion = 'amexio-accordion'
expect(dirIn.ColorPaletteConstants.accordion).toBeDefined();
});
it('getBGColorStyles()case5', () => {
let obj = { amexioComponentId: 'amexio-panel', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-panel';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { panel: c };
expect(dirIn.ColorPaletteConstants.panel).toBeUndefined();
dirIn.ColorPaletteConstants = { panel: 'amexio-panel' };
dirIn.ColorPaletteConstants.panel = 'amexio-panel'
expect(dirIn.ColorPaletteConstants.panel).toBeDefined();
});
it('getBGColorStyles()case6', () => {
let obj = { amexioComponentId: 'amexio-floating-panel', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-floating-panel';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { floatingpanel: c };
expect(dirIn.ColorPaletteConstants.floatingpanel).toBeUndefined();
dirIn.ColorPaletteConstants = { floatingpanel: 'amexio-floating-panel' };
dirIn.ColorPaletteConstants.floatingpanel = 'amexio-floating-panel'
expect(dirIn.ColorPaletteConstants.floatingpanel).toBeDefined();
});
it('getBGColorStyles()case7', () => {
let obj = { amexioComponentId: 'amexio-window', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-window';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { window: c };
expect(dirIn.ColorPaletteConstants.window).toBeUndefined();
dirIn.ColorPaletteConstants = { window: 'amexio-window' };
dirIn.ColorPaletteConstants.window = 'amexio-window'
expect(dirIn.ColorPaletteConstants.window).toBeDefined();
});
it('getBGColorStyles()case8', () => {
let obj = { amexioComponentId: 'amexio-dialogue', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-dialogue';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { dialogue: c };
expect(dirIn.ColorPaletteConstants.dialogue).toBeUndefined();
dirIn.ColorPaletteConstants = { dialogue: 'amexio-dialogue' };
dirIn.ColorPaletteConstants.dialogue = 'amexio-dialogue'
expect(dirIn.ColorPaletteConstants.dialogue).toBeDefined();
});
it('getBGColorStyles()case9', () => {
let obj = { amexioComponentId: 'amexio-box', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-box';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { box: c };
expect(dirIn.ColorPaletteConstants.box).toBeUndefined();
dirIn.ColorPaletteConstants = { box: 'amexio-box' };
dirIn.ColorPaletteConstants.box = 'amexio-box'
expect(dirIn.ColorPaletteConstants.box).toBeDefined();
});
it('getBGColorStyles()case10', () => {
let obj = { amexioComponentId: 'amexio-grid', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-grid';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { grid: c };
expect(dirIn.ColorPaletteConstants.grid).toBeUndefined();
dirIn.ColorPaletteConstants = { grid: 'amexio-grid' };
dirIn.ColorPaletteConstants.grid = 'amexio-grid'
expect(dirIn.ColorPaletteConstants.grid).toBeDefined();
});
it('getBGColorStyles()case11', () => {
let obj = { amexioComponentId: 'amexio-tab', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-tab';
dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { tab: c };
expect(dirIn.ColorPaletteConstants.tab).toBeUndefined();
dirIn.ColorPaletteConstants = { tab: 'amexio-tab' };
dirIn.ColorPaletteConstants.tab = 'amexio-tab'
expect(dirIn.ColorPaletteConstants.tab).toBeDefined();
});
// ###########################################
it('getGradientStyles()case2', () => {
let obj = { amexioComponentId: 'amexio-banner', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-banner';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { banner: c };
expect(dirIn.ColorPaletteConstants.banner).toBeUndefined();
dirIn.ColorPaletteConstants = { banner: 'amexio-banner' };
dirIn.ColorPaletteConstants.banner = 'amexio-banner'
expect(dirIn.ColorPaletteConstants.banner).toBeDefined();
});
it('getGradientStyles()case3', () => {
let obj = { amexioComponentId: 'amexio-navbar', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-navbar';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { navbar: c };
expect(dirIn.ColorPaletteConstants.banner).toBeUndefined();
dirIn.ColorPaletteConstants = { navbar: 'amexio-navbar' };
dirIn.ColorPaletteConstants.navbar = 'amexio-navbar'
expect(dirIn.ColorPaletteConstants.navbar).toBeDefined();
});
it('getGradientStyles()case4', () => {
let obj = { amexioComponentId: 'amexio-accordion', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-accordion';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { accordion: c };
expect(dirIn.ColorPaletteConstants.accordion).toBeUndefined();
dirIn.ColorPaletteConstants = { accordion: 'amexio-accordion' };
dirIn.ColorPaletteConstants.accordion = 'amexio-accordion'
expect(dirIn.ColorPaletteConstants.accordion).toBeDefined();
});
it('getGradientStyles()case5', () => {
let obj = { amexioComponentId: 'amexio-panel', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-panel';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { panel: c };
expect(dirIn.ColorPaletteConstants.panel).toBeUndefined();
dirIn.ColorPaletteConstants = { panel: 'amexio-panel' };
dirIn.ColorPaletteConstants.panel = 'amexio-panel'
expect(dirIn.ColorPaletteConstants.panel).toBeDefined();
});
it('getGradientStyles()case6', () => {
let obj = { amexioComponentId: 'amexio-floating-panel', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-floating-panel';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { floatingpanel: c };
expect(dirIn.ColorPaletteConstants.floatingpanel).toBeUndefined();
dirIn.ColorPaletteConstants = { floatingpanel: 'amexio-floating-panel' };
dirIn.ColorPaletteConstants.floatingpanel = 'amexio-floating-panel'
expect(dirIn.ColorPaletteConstants.floatingpanel).toBeDefined();
});
it('getGradientStyles()case7', () => {
let obj = { amexioComponentId: 'amexio-window', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-window';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { window: c };
expect(dirIn.ColorPaletteConstants.window).toBeUndefined();
dirIn.ColorPaletteConstants = { window: 'amexio-window' };
dirIn.ColorPaletteConstants.window = 'amexio-window'
expect(dirIn.ColorPaletteConstants.window).toBeDefined();
});
it('getGradientStyles()case8', () => {
let obj = { amexioComponentId: 'amexio-dialogue', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-dialogue';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { dialogue: c };
expect(dirIn.ColorPaletteConstants.dialogue).toBeUndefined();
dirIn.ColorPaletteConstants = { dialogue: 'amexio-dialogue' };
dirIn.ColorPaletteConstants.dialogue = 'amexio-dialogue'
expect(dirIn.ColorPaletteConstants.dialogue).toBeDefined();
});
it('getGradientStyles()case9', () => {
let obj = { amexioComponentId: 'amexio-box', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-box';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { box: c };
expect(dirIn.ColorPaletteConstants.box).toBeUndefined();
dirIn.ColorPaletteConstants = { box: 'amexio-box' };
dirIn.ColorPaletteConstants.box = 'amexio-box'
expect(dirIn.ColorPaletteConstants.box).toBeDefined();
});
it('getGradientStyles()case10', () => {
let obj = { amexioComponentId: 'amexio-grid', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-grid';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { grid: c };
expect(dirIn.ColorPaletteConstants.grid).toBeUndefined();
dirIn.ColorPaletteConstants = { grid: 'amexio-grid' };
dirIn.ColorPaletteConstants.grid = 'amexio-grid'
expect(dirIn.ColorPaletteConstants.grid).toBeDefined();
});
it('getGradientStyles()case11', () => {
let obj = { amexioComponentId: 'amexio-tab', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-tab';
dirIn.getGradientStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { tab: c };
expect(dirIn.ColorPaletteConstants.tab).toBeUndefined();
dirIn.ColorPaletteConstants = { tab: 'amexio-tab' };
dirIn.ColorPaletteConstants.tab = 'amexio-tab'
expect(dirIn.ColorPaletteConstants.tab).toBeDefined();
});
it('getGradientStyles()', () => {
let obj = { amexioComponentId: 'amexio-card', setColorPalette: () => { } }
dirIn.hostComponent = obj
dirIn.hostComponent.amexioComponentId = 'amexio-card';
// dirIn.getBGColorStyles(dirIn.hostComponent);
let c;
dirIn.ColorPaletteConstants = { card: c, cardce: c }
dirIn.getGradientStyles(dirIn.hostComponent);
// case (ColorPaletteConstants.card || ColorPaletteConstants.cardce): {
expect(dirIn.ColorPaletteConstants.card).toBeUndefined();
expect(dirIn.ColorPaletteConstants.cardce).toBeUndefined();
dirIn.ColorPaletteConstants = { card: 'amexio-card', cardce: 'amexio-card-ce' };
dirIn.ColorPaletteConstants.card = 'amexio-card'
dirIn.ColorPaletteConstants.cardce = 'amexio-card-ce'
expect(dirIn.ColorPaletteConstants.card).toBeDefined();
expect(dirIn.ColorPaletteConstants.cardce).toBeDefined();
});
it('randomFloat method call', () => {
dirIn.randomFloat();
const int = window.crypto.getRandomValues(new Uint32Array(1))[0];
return int / 2 ** 32;
});
it('randomInt method call', () => {
let max = 10;
let min = 5;
dirIn.randomInt(min, max);
const range = max - min;
return Math.floor(dirIn.randomFloat() * range + min);
});
it('getRandomNumber method call', () => {
let length = 19;
let max = 10;
let min = 5;
dirIn.getRandomNumber(length, min, max);
const arr = (new Array(length).fill(0).map(() => dirIn.randomInt(min, max)));
return arr[0];
});
it('randomFloat method call', () => {
dirIn.randomFloat();
const int = window.crypto.getRandomValues(new Uint32Array(1))[0];
return int / 2 ** 32;
});
it('randomInt method call', () => {
let max =10;
let min = 5;
dirIn.randomInt(min,max);
const range = max - min;
return Math.floor(dirIn.randomFloat() * range + min);
});
it('getRandomNumber method call', () => {
let length = 19;
let max =10;
let min = 5;
dirIn.getRandomNumber(length,min,max);
const arr = (new Array(length).fill(0).map(() => dirIn.randomInt(min, max)));
return arr[0];
});
// it('randomThemeCall method else call', () => {
// dirIn.randomThemeCall();
// dirIn.gradient = false;
// expect(dirIn.gradient).toEqual(false);
// const randomIndex = dirIn.getRandomNumber(1, 0, dirIn.themejson.length);
// });
// it('randomThemeCall method call', () => {
// dirIn.randomThemeCall();
// dirIn.gradient = true;
// expect(dirIn.gradient).toEqual(true);
// const randomIndex = dirIn.getRandomNumber(1, 0, dirIn.gradientThemeJson.length);
// });
}); | the_stack |
import { CalendarWrapper } from '../lib/wrappers/CalendarWrapper'
import { DayGridViewWrapper } from '../lib/wrappers/DayGridViewWrapper'
import { TimeGridViewWrapper } from '../lib/wrappers/TimeGridViewWrapper'
import '../lib/dom-misc'
['height', 'contentHeight'].forEach((heightProp) => {
describe(heightProp, () => {
let $calendarEl
let heightEl // HTMLElement
let asAMethod
let heightPropDescriptions: { description: string, height: string | number, heightWrapper?: boolean }[] = [
{ description: 'as a number', height: 600 },
]
if (heightProp === 'height') {
heightPropDescriptions.push({ description: 'as "100%"', height: '100%', heightWrapper: true })
}
pushOptions({
initialDate: '2014-08-01',
})
beforeEach(() => {
$calendarEl = $('<div />').appendTo('body').width(900)
})
afterEach(() => {
$calendarEl.remove()
})
// relies on asAMethod (boolean)
// otherOptions: other calendar options to dynamically set (assumes asAMethod)
function init(heightVal) {
let calendar
if (asAMethod) {
calendar = initCalendar({}, $calendarEl[0])
let calendarWrapper = new CalendarWrapper(calendar)
let dateEl = calendarWrapper.getFirstDateEl()
calendar.setOption(heightProp, heightVal)
expect(calendarWrapper.getFirstDateEl()).toBe(dateEl)
} else {
calendar = initCalendar({ [heightProp]: heightVal }, $calendarEl[0])
}
if (heightProp === 'height') {
heightEl = calendar.el
} else {
heightEl = new CalendarWrapper(calendar).getViewEl()
}
return calendar
}
function expectHeight(heightVal) {
let diff = Math.abs(heightEl.offsetHeight - heightVal)
expect(diff).toBeLessThan(2) // off-by-one or exactly the same. for zoom, and firefox
}
$.each({
'as an init option': false,
'as a method': true,
}, (desc, bool) => {
describe(desc, () => {
beforeEach(() => {
asAMethod = bool
})
describe('for ' + heightProp, () => {
describe('when in month view', () => {
pushOptions({
initialView: 'dayGridMonth',
})
heightPropDescriptions.forEach((testInfo) => {
describe(testInfo.description, () => {
if (testInfo.heightWrapper) {
beforeEach(() => {
$calendarEl.wrap('<div id="calendar-container" style="height: 600px;" />')
})
afterEach(() => {
$('#calendar-container').remove()
})
}
describe('when there are no events', () => {
it('should be the specified height, with no scrollbars', () => {
let calendar = init(testInfo.height)
let viewWrapper = new DayGridViewWrapper(calendar)
let diff = Math.abs(heightEl.offsetHeight - 600)
expect(diff).toBeLessThan(2)
expect(viewWrapper.getScrollerEl()).not.toHaveScrollbars()
})
})
describe('when there is one tall row of events', () => {
pushOptions({
events: repeatClone({ title: 'event', start: '2014-08-04' }, 9),
})
it('should take away height from other rows, but not do scrollbars', () => {
let calendar = init(testInfo.height)
let viewWrapper = new DayGridViewWrapper(calendar)
let $rows = $(viewWrapper.dayGrid.getRowEls())
let $tallRow = $rows.eq(1)
let $shortRows = $rows.not($tallRow) // 0, 2, 3, 4, 5
let shortHeight = $shortRows.eq(0).outerHeight()
expectHeight(600)
$shortRows.each((i, node) => {
let rowHeight = $(node).outerHeight()
let diff = Math.abs(rowHeight - shortHeight)
expect(diff).toBeLessThan(10) // all roughly the same
})
expect($tallRow.outerHeight()).toBeGreaterThan(shortHeight * 2) // much taller
expect(viewWrapper.getScrollerEl()).not.toHaveScrollbars()
})
})
describe('when there are many tall rows of events', () => {
pushOptions({
events: [].concat(
repeatClone({ title: 'event0', start: '2014-07-28' }, 9),
repeatClone({ title: 'event1', start: '2014-08-04' }, 9),
repeatClone({ title: 'event2', start: '2014-08-11' }, 9),
repeatClone({ title: 'event3', start: '2014-08-18' }, 9),
repeatClone({ title: 'event4', start: '2014-08-25' }, 9),
repeatClone({ title: 'event5', start: '2014-09-01' }, 9),
),
})
it('height is correct and scrollbars show up', () => {
let calendar = init(testInfo.height)
let viewWrapper = new DayGridViewWrapper(calendar)
expectHeight(600)
expect(viewWrapper.getScrollerEl()).toHaveScrollbars()
})
})
})
})
describe('as "auto", when there are many tall rows of events', () => {
pushOptions({
events: [].concat(
repeatClone({ title: 'event0', start: '2014-07-28' }, 9),
repeatClone({ title: 'event1', start: '2014-08-04' }, 9),
repeatClone({ title: 'event2', start: '2014-08-11' }, 9),
repeatClone({ title: 'event3', start: '2014-08-18' }, 9),
repeatClone({ title: 'event4', start: '2014-08-25' }, 9),
repeatClone({ title: 'event5', start: '2014-09-01' }, 9),
),
})
it('height is really tall and there are no scrollbars', () => {
let calendar = init('auto')
let viewWrapper = new DayGridViewWrapper(calendar)
expect(heightEl.offsetHeight).toBeGreaterThan(1000) // pretty tall
expect(viewWrapper.getScrollerEl()).not.toHaveScrollbars()
})
})
});
['dayGridWeek', 'dayGridDay'].forEach((viewName) => {
describe('in ' + viewName + ' view', () => {
pushOptions({
initialView: viewName,
})
heightPropDescriptions.forEach((testInfo) => {
describe(testInfo.description, () => {
if (testInfo.heightWrapper) {
beforeEach(() => {
$calendarEl.wrap('<div id="calendar-container" style="height: 600px;" />')
})
afterEach(() => {
$('#calendar-container').remove()
})
}
describe('when there are no events', () => {
it('should be the specified height, with no scrollbars', () => {
let calendar = init(testInfo.height)
let viewWrapper = new DayGridViewWrapper(calendar)
expectHeight(600)
expect(viewWrapper.getScrollerEl()).not.toHaveScrollbars()
})
})
describe('when there are many events', () => {
pushOptions({
events: repeatClone({ title: 'event', start: '2014-08-01' }, 100),
})
it('should have the correct height, with scrollbars', () => {
let calendar = init(testInfo.height)
let viewWrapper = new DayGridViewWrapper(calendar)
expectHeight(600)
expect(viewWrapper.getScrollerEl()).toHaveScrollbars()
})
})
})
})
describe('as "auto", when there are many events', () => {
pushOptions({
events: repeatClone({ title: 'event', start: '2014-08-01' }, 100),
})
it('should be really tall with no scrollbars', () => {
let calendar = init('auto')
let viewWrapper = new DayGridViewWrapper(calendar)
expect(heightEl.offsetHeight).toBeGreaterThan(1000) // pretty tall
expect(viewWrapper.getScrollerEl()).not.toHaveScrollbars()
})
})
})
});
['timeGridWeek', 'timeGridDay'].forEach((viewName) => {
describe('in ' + viewName + ' view', () => {
pushOptions({
initialView: viewName,
})
describeOptions({
'with no all-day section': { allDaySlot: false },
'with no all-day events': { },
'with some all-day events': { events: repeatClone({ title: 'event', start: '2014-08-01' }, 6) },
}, () => {
heightPropDescriptions.forEach((testInfo) => {
describe(testInfo.description, () => {
if (testInfo.heightWrapper) {
beforeEach(() => {
$calendarEl.wrap('<div id="calendar-container" style="height: 600px;" />')
})
afterEach(() => {
$('#calendar-container').remove()
})
}
describe('with many slots', () => {
pushOptions({
slotMinTime: '00:00:00',
slotMaxTime: '24:00:00',
})
it('should be the correct height, with scrollbars', () => {
let calendar = init(testInfo.height)
let viewWrapper = new TimeGridViewWrapper(calendar)
expectHeight(600)
expect(viewWrapper.getScrollerEl()).toHaveScrollbars()
})
})
})
})
describe('as "auto", with only a few slots', () => {
pushOptions({
slotMinTime: '06:00:00',
slotMaxTime: '10:00:00',
})
it('should be really short with no scrollbars nor horizontal rule', () => {
let calendar = init('auto')
let viewWrapper = new TimeGridViewWrapper(calendar)
expect(heightEl.offsetHeight).toBeLessThan(500) // pretty short
expect(viewWrapper.getScrollerEl()).not.toHaveScrollbars()
})
})
describe('as a "auto", with many slots', () => {
pushOptions({
slotMinTime: '00:00:00',
slotMaxTime: '24:00:00',
})
it('should be really tall with no scrollbars nor horizontal rule', () => {
let calendar = init('auto')
let viewWrapper = new TimeGridViewWrapper(calendar)
expect(heightEl.offsetHeight).toBeGreaterThan(900) // pretty tall
expect(viewWrapper.getScrollerEl()).not.toHaveScrollbars()
})
})
})
})
})
})
})
})
})
})
it('no height oscillation happens', () => {
let $container = $(
'<div style="width:301px;height:300px;overflow-y:auto">' +
'<div style="margin:0"></div>' +
'</div>',
).appendTo('body')
// will freeze browser if bug exists :)
let calendar = initCalendar({
headerToolbar: false,
initialView: 'dayGridMonth',
aspectRatio: 1,
}, $container.find('div')[0])
calendar.destroy()
$container.remove()
})
function repeatClone(srcObj, times) {
let a = []
let i
for (i = 0; i < times; i += 1) {
a.push($.extend({}, srcObj))
}
return a
} | the_stack |
import { controlsProperty, VideoBase, playsinlineProperty, mutedProperty, srcProperty, currentTimeProperty } from './common';
import { Source } from '../common';
import { knownFolders, path } from '@nativescript/core';
declare const Utils;
@NativeClass()
class NativeObject extends NSObject {
_owner: WeakRef<Video>;
public static initWithOwner(owner: WeakRef<Video>): NativeObject {
const obj = NativeObject.alloc().init() as NativeObject;
obj._owner = owner;
return obj;
}
observeValueForKeyPathOfObjectChangeContext(path: string, obj: Object, change: NSDictionary<any, any>, context: any) {
if (path === 'status') {
const owner = this._owner.get();
if (owner) {
if (owner._player.currentItem.status === AVPlayerItemStatus.Failed) {
const baseError = owner._player.currentItem.error.userInfo.objectForKey(NSUnderlyingErrorKey);
const error = new Error();
/*error: {
code: baseError.code,
domain: baseError.domain
},
stack: error.stack
*/
} else if (owner._player.currentItem.status === AVPlayerItemStatus.ReadyToPlay) {
if (!owner._videoSize) {
owner._videoSize = owner._asset.tracksWithMediaType(AVMediaTypeVideo)?.[0].naturalSize ?? undefined;
}
}
}
} else if (path === 'loadedTimeRanges') {
const playerItem = obj as AVPlayerItem;
if (playerItem) {
const ranges = playerItem.loadedTimeRanges;
const first = ranges?.firstObject as NSValue;
if (first) {
let loaded = first.CMTimeRangeValue.duration.value / first.CMTimeRangeValue.duration.timescale;
let total = playerItem.duration.value / playerItem.duration.timescale;
// console.log('loaded', loaded / total);
}
}
}
}
dealloc() {
// using this to clean up listeners
const owner = this._owner.get();
if (owner) {
if (owner._playEndNotificationId) {
NSNotificationCenter.defaultCenter.removeObserver(owner._playEndNotificationId);
owner._playEndNotificationId = undefined;
NSNotificationCenter.defaultCenter.removeObserver(owner._resumeListenerId);
owner._resumeListenerId = undefined;
NSNotificationCenter.defaultCenter.removeObserver(owner._suspendListenerId);
owner._suspendListenerId = undefined;
owner._destroy();
}
}
}
}
export class Video extends VideoBase {
#videoCtrl: AVPlayerViewController;
#player: AVPlayer;
#sourceView: Source[];
#protocols: NativeObject;
_isCustom: boolean = false;
_readyState: number = 0;
_resumeListenerId: any;
_suspendListenerId: any;
_isInForground = true;
_assetOutput: AVPlayerItemVideoOutput;
_isPlaying = false;
#src: string;
#muted: boolean;
#controls: boolean;
_playEndNotificationId: any;
_playbackTimeObserver: any;
_playbackFramesObserver: any;
_currentUrl: string;
_fps: number;
_ctx: any;
_asset: AVURLAsset;
_videoSize: any;
_render: any;
get _player() {
return this.#player;
}
constructor() {
super();
this.#videoCtrl = AVPlayerViewController.new();
try {
AVAudioSession.sharedInstance().setCategoryError(AVAudioSessionCategoryPlayback);
} catch (e) {}
this.#player = AVPlayer.new();
this.#videoCtrl.player = this.#player;
this.#sourceView = [];
this.#protocols = NativeObject.initWithOwner(new WeakRef(this));
this.setNativeView(this.#videoCtrl.view);
this._suspendListenerId = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(UIApplicationDidEnterBackgroundNotification, null, null, (noti) => {
this._isInForground = false;
});
this._resumeListenerId = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(UIApplicationDidBecomeActiveNotification, null, null, (noti) => {
this._isInForground = true;
});
}
static createCustomView() {
const video = new Video();
video._isCustom = true;
video.width = 300;
video.height = 150;
return video;
}
//@ts-ignore
get readyState() {
return this._readyState;
}
getCurrentFrame(context) {
if (!this._isInForground) {
return;
}
if (this._assetOutput) {
try {
if (!this._render) {
this._render = Utils.setupRender();
this._render.createSurface();
}
Utils.drawFrame(this.#player, this._assetOutput, this._videoSize, this._render, arguments[4], arguments[5], false);
} catch (e) {
console.log('getCurrentFrame error:', e);
}
}
}
createNativeView(): Object {
const ctrl = this.topViewController;
if (ctrl) {
ctrl.addChildViewController(this.#videoCtrl);
this.#videoCtrl.didMoveToParentViewController(ctrl);
}
return this.#videoCtrl.view;
}
initNativeView() {
super.initNativeView();
this.#videoCtrl.showsPlaybackControls = this.controls;
this.#videoCtrl.entersFullScreenWhenPlaybackBegins = !this.playsinline;
this.#player.muted = this.muted;
}
[controlsProperty.setNative](enable: boolean) {
this.#videoCtrl.showsPlaybackControls = enable;
}
[playsinlineProperty.setNative](inline: boolean) {
this.#videoCtrl.entersFullScreenWhenPlaybackBegins = !inline;
}
_addChildFromBuilder(name: string, value: any) {
if (value instanceof Source) {
this.#sourceView.push(value);
}
}
onLoaded() {
super.onLoaded();
const item = this.#sourceView.filter((item) => {
if (item.type.indexOf('video/webm') === -1) {
return item;
}
})[0];
if (item) {
this._loadSrc(item.src);
}
}
get duration() {
const currentItem = this.#player.currentItem;
if (currentItem) {
return CMTimeGetSeconds(currentItem.asset.duration);
}
return NaN;
}
get currentTime() {
const ct = this.#player.currentTime();
return ct.value / ct.timescale;
}
set currentTime(value: number) {
const time = CMTimeMakeWithSeconds(value, this.#player.currentTime().timescale);
this.#player.seekToTime(time);
}
get muted() {
return this.#muted;
}
set muted(value: boolean) {
this.#muted = value;
this.#player.muted = value;
}
get src() {
return this.#src;
}
set src(value: string) {
if(value !== this._currentUrl){
this.#src = value;
this._loadSrc(value);
}
}
get controls() {
return this.#controls;
}
set controls(enabled: boolean) {
this.#controls = enabled;
this.#videoCtrl.showsPlaybackControls = enabled;
}
private _addTimeObserver() {
const _interval = CMTimeMake(1, 1);
this._playbackTimeObserver = this.#player.addPeriodicTimeObserverForIntervalQueueUsingBlock(_interval, null, (currentTime) => {
if (this._isPlaying) {
const _seconds = CMTimeGetSeconds(currentTime);
currentTimeProperty.nativeValueChange(this, _seconds);
this._notifyListener(Video.timeupdateEvent);
}
});
}
private _loadSrc(value: string) {
try {
const src = value;
let url;
if (typeof value === 'string' && value.startsWith('~/')) {
value = path.join(knownFolders.currentApp().path, value.replace('~', ''));
}
if (typeof value === 'string' && value.startsWith('/')) {
url = NSURL.fileURLWithPath(value);
}
if (this._playEndNotificationId) {
NSNotificationCenter.defaultCenter.removeObserver(this._playEndNotificationId);
this._playEndNotificationId = undefined;
}
if (!url) {
url = NSURL.URLWithString(value);
}
this._asset = AVURLAsset.assetWithURL(url);
const keys = ['tracks', 'duration'];
this._asset.loadValuesAsynchronouslyForKeysCompletionHandler(keys, () => {
this._videoSize = this._asset.tracksWithMediaType(AVMediaTypeVideo)?.[0].naturalSize ?? undefined;
const fps = this._asset.tracks.firstObject?.nominalFrameRate ?? 30;
const _interval = CMTimeMake(1, fps);
this._playbackFramesObserver = this.#player.addPeriodicTimeObserverForIntervalQueueUsingBlock(_interval, null, (currentTime) => {
if (this._isPlaying) {
this._notifyVideoFrameCallbacks();
}
});
this._render?.destroy();
this._render = undefined;
const item = AVPlayerItem.alloc().initWithAsset(this._asset);
const settings: any = {};
settings[kCVPixelBufferPixelFormatTypeKey] = NSNumber.numberWithUnsignedInt(kCVPixelFormatType_32BGRA);
this._assetOutput = AVPlayerItemVideoOutput.alloc().initWithOutputSettings(settings);
item.addOutput(this._assetOutput);
item.addObserverForKeyPathOptionsContext(this.#protocols, 'status', 0, null);
item.addObserverForKeyPathOptionsContext(this.#protocols, 'loadedTimeRanges', NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, null);
this._playEndNotificationId = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(AVPlayerItemDidPlayToEndTimeNotification, item, null, (notfi) => {
if (this.loop) {
this.#player.seekToTime(kCMTimeZero);
this.#player.play();
this._isPlaying = true;
this._notifyListener(Video.playingEvent);
}
});
this.#player.replaceCurrentItemWithPlayerItem(item);
this._readyState = Video.HAVE_METADATA;
this._currentUrl = src;
if (this.autoplay) {
this.play();
}
});
} catch (e) {
console.log('_loadSrc', e);
}
}
play() {
if (this._isPlaying) {
return;
}
this._addTimeObserver();
this.#player.play();
this._isPlaying = true;
this._notifyListener(Video.playingEvent);
}
pause() {
if (!this._isPlaying) {
return;
}
if (this._playbackTimeObserver) {
this.#player.removeTimeObserver(this._playbackTimeObserver);
this._playbackTimeObserver = undefined;
}
/*
if (this._playbackTimeObserver) {
this.#player.removeTimeObserver(this._playbackTimeObserver);
this._playbackTimeObserver = undefined;
}
*/
this.#player.pause();
this._isPlaying = false;
}
_destroy() {
this.#player.pause();
}
private static get rootViewController(): UIViewController | undefined {
const keyWindow = UIApplication.sharedApplication.keyWindow;
return keyWindow != null ? keyWindow.rootViewController : undefined;
}
private get topViewController(): UIViewController | undefined {
const root = Video.rootViewController;
if (root == null) {
return undefined;
}
return this.findTopViewController(root);
}
private findTopViewController(root: UIViewController): UIViewController | undefined {
const presented = root.presentedViewController;
if (presented != null) {
return this.findTopViewController(presented);
}
if (root instanceof UISplitViewController) {
const last = root.viewControllers.lastObject;
if (last == null) {
return root;
}
return this.findTopViewController(last);
} else if (root instanceof UINavigationController) {
const top = root.topViewController;
if (top == null) {
return root;
}
return this.findTopViewController(top);
} else if (root instanceof UITabBarController) {
const selected = root.selectedViewController;
if (selected == null) {
return root;
}
return this.findTopViewController(selected);
} else {
return root;
}
}
} | the_stack |
import { Collection, Model } from '@datx/core';
import * as fetch from 'isomorphic-fetch';
import {
fetchModelLink,
fetchModelRefLink,
getModelLinks,
getModelMeta,
getModelRefMeta,
jsonapi,
modelToJsonApi,
config,
} from '../../src';
import { clearAllCache } from '../../src/cache';
import { setRequest, setupNetwork, confirmNetwork } from '../utils/api';
import { Event, Image, TestStore } from '../utils/setup';
import { Response } from '../../src/Response';
const baseTransformRequest = config.transformRequest;
const baseTransformResponse = config.transformResponse;
describe('Network basics', () => {
beforeEach(() => {
config.fetchReference = fetch;
config.baseUrl = 'https://example.com/';
config.transformRequest = baseTransformRequest;
config.transformResponse = baseTransformResponse;
clearAllCache();
setupNetwork();
});
afterEach(confirmNetwork);
it('should fetch the basic data', async () => {
setRequest({
name: 'events-1',
url: 'event',
});
const store = new TestStore();
const events = await store.fetchAll(Event);
expect(events.data).toBeInstanceOf(Array);
expect(events.data).toHaveLength(4);
if (events.data instanceof Array) {
const event = events.data[0];
expect(event['title']).toBe('Test 1');
expect(getModelMeta(event).createdAt).toBe('2017-03-19T16:00:00.000Z');
expect(event.meta.refs.images).toBeInstanceOf(Array);
if (event.meta.refs.images instanceof Array) {
expect(event.meta.refs.images.map((image) => image.id)).toContain('1');
}
expect(event.meta.refs.images).toHaveLength(1);
expect(getModelRefMeta(event).images.foo).toBe('bar');
const data = modelToJsonApi(event);
expect(data.id).toBe('1');
expect(data.type).toBe('event');
expect(data.attributes && data.attributes.title).toBe('Test 1');
expect(
data.relationships && data.relationships.images.data && data.relationships.images.data[0],
).toEqual({ type: 'image', id: '1' });
expect(data.attributes && 'images' in data.attributes).toBe(false);
}
});
it('return null if no data in response', async () => {
setRequest({
name: 'eempty',
url: 'event',
});
const store = new TestStore();
const events = await store.fetchAll(Event);
expect(events.data).toBeNull();
});
it('should handle id changes correctly', async () => {
const store = new TestStore();
const image1 = store.add({}, Image);
const image2 = new Image({});
setRequest({
method: 'POST',
name: 'image-1',
url: 'image',
responseFn(_path: string, req: string) {
const request = JSON.parse(req);
expect(request['data'].relationships.event.data).toBeNull();
},
});
expect(parseInt(image1.id, 10)).toBeLessThan(0); // Temporary id, negative autoincrement
await image1.save(); // Load the image-1.json data
expect(image1.id).toBe('1');
expect(image1.id).toBe(image1.meta.id);
const images = store.findAll(Image);
expect(images).toHaveLength(1);
setRequest({
method: 'POST',
name: 'image-1',
url: 'image',
});
expect(parseInt(image2.id, 10)).toBeLessThan(0); // Temporary id, negative autoincrement
await image2.save(); // Load the image-1.json data
expect(image2.id).toBe('1');
expect(image2.id).toBe(image2.meta.id);
});
it('should serialize existing relationships', async () => {
setRequest({
name: 'events-1',
url: 'event',
});
const store = new TestStore();
const events = await store.fetchAll(Event);
expect(events.data).toBeInstanceOf(Array);
if (events.data) {
const event = events.data[0];
const data = modelToJsonApi(event);
expect(data.attributes && 'id' in data.attributes).toBe(false);
expect(data.relationships).not.toBeUndefined();
if (data.relationships) {
expect(data.relationships.images.data).toHaveLength(1);
expect(data.relationships.image.data).toBeNull();
}
}
});
it('should support transformRequest hook', async () => {
setRequest({
name: 'events-1',
url: 'event/all',
});
let hasTransformRequestHookBeenCalled = false;
const store = new TestStore();
config.transformRequest = (opts): any => {
expect(opts.collection).toBe(store);
hasTransformRequestHookBeenCalled = true;
return { ...opts, url: `${opts.url}/all` };
};
const events = await store.fetchAll('event');
expect(events.data).toBeInstanceOf(Array);
expect(hasTransformRequestHookBeenCalled).toBe(true);
});
it('should support transformResponse hook', async () => {
setRequest({
name: 'events-1',
url: 'event',
});
let hasTransformResponseHookBeenCalled = false;
config.transformResponse = (opts): any => {
expect(opts.status).toBe(200);
hasTransformResponseHookBeenCalled = true;
return { ...opts, status: 201 };
};
const store = new TestStore();
const events = await store.fetchAll('event');
expect(events.data).toBeInstanceOf(Array);
expect(events.status).toBe(201);
expect(hasTransformResponseHookBeenCalled).toBe(true);
});
it('should save the jsonapi data', async () => {
setRequest({
name: 'jsonapi-object',
url: 'event',
});
const store = new TestStore();
const events = await store.fetchAll('event');
expect(events.data).toBeInstanceOf(Array);
expect(events.data).toHaveLength(4);
expect(events.jsonapi).toBeInstanceOf(Object);
if (events.jsonapi) {
expect(events.jsonapi.version).toBe('1.0');
expect(events.jsonapi.meta && events.jsonapi.meta.foo).toBe('bar');
}
});
it('should fetch one item', async () => {
setRequest({
name: 'event-1b',
url: 'event/1',
});
const store = new TestStore();
const events = await store.fetch(Event, '1');
const record = events.data;
expect(record).toBeInstanceOf(Object);
if (record) {
expect(record['title']).toBe('Test 1');
expect(getModelLinks(record)).toBeInstanceOf(Object);
expect(getModelLinks(record).self).toBe('https://example.com/event/1234');
}
});
it('should support pagination', async () => {
setRequest({
name: 'events-1',
url: 'event',
});
const store = new TestStore();
const events = await store.fetchAll(Event);
expect(events.data).toBeInstanceOf(Array);
expect(events.data).toHaveLength(4);
if (events.data instanceof Array) {
expect(events.data instanceof Array && events.data[0]['title']).toBe('Test 1');
expect(events.links).toBeInstanceOf(Object);
if (events.links instanceof Object && typeof events.links.next === 'object') {
expect(events.links.next.href).toBe('https://example.com/event?page=2');
expect(events.links.next.meta.foo).toBe('bar');
}
}
setRequest({
name: 'events-2',
query: {
page: 2,
},
url: 'event',
});
const events2 = await events.next?.();
expect(events2).toBeInstanceOf(Object);
if (events2) {
expect(events2.data).toBeInstanceOf(Array);
expect(events2.data).toHaveLength(2);
expect(events2.data instanceof Array && events2.data[0]['title']).toBe('Test 5');
const events1 = await events2.prev?.();
expect(events1).toBeInstanceOf(Object);
if (events1) {
expect(events1.data).toBeInstanceOf(Array);
expect(events1.data).toHaveLength(4);
expect(events1.data instanceof Array && events1.data[0]['title']).toBe('Test 1');
const events1b = await events2.prev?.();
expect(events1.snapshot).toEqual(events.snapshot);
expect(events1.snapshot).toEqual(events1b?.snapshot);
}
}
});
it('should fetch all pages', async () => {
setRequest({
name: 'events-1',
url: 'event',
});
setRequest({
name: 'events-2',
query: {
page: 2,
},
url: 'event',
});
const store = new TestStore();
const events = await store.getAll(Event);
expect(events.data).toBeInstanceOf(Array);
expect(events.data.length).toBe(6);
expect(events.data[events.data.length - 1].title).toBe('Test 6');
expect(events.responses).toBeInstanceOf(Array);
expect(events.responses.length).toBe(2);
expect(events.lastResponse).toBeInstanceOf(Response);
expect(events.lastResponse).toEqual(events.responses[events.responses.length - 1]);
expect(events.lastResponse.next).toBeUndefined();
});
it('should throw an error if getAll maxRequests is less than 1', async () => {
const store = new TestStore();
try {
await store.getAll(Event, undefined, -1);
} catch (error) {
expect(error).toBeInstanceOf(Error);
}
try {
await store.getAll(Event, undefined, 0);
} catch (error) {
expect(error).toBeInstanceOf(Error);
}
});
it('should support record links', async () => {
setRequest({
name: 'event-1',
url: 'event',
});
const store = new TestStore();
const events = await store.fetchAll('event');
const event = events.data;
setRequest({
name: 'image-1',
url: 'images/1',
});
if (event) {
const image = await fetchModelLink<Image>(event, 'image');
const imageData = image.data as Image;
expect(imageData.meta.id).toBe('1');
expect(imageData.meta.type).toBe('image');
expect(imageData['url']).toBe('https://example.com/1.jpg');
}
});
it('should recover if no link defined', async () => {
setRequest({
name: 'event-1',
url: 'event',
});
const store = new TestStore();
const events = await store.fetchAll(Event);
const event = events.data;
expect(event).toBeInstanceOf(Event);
if (event instanceof Event) {
let hasThrown = false;
try {
const foobar = await fetchModelLink(event, 'foobar');
expect(foobar.data).toBeInstanceOf(Array);
expect(foobar.data).toHaveLength(0);
} catch (e) {
hasThrown = true;
expect(e.message).toBe("[datx exception] Link foobar doesn't exist on the model");
}
expect(hasThrown).toBe(true);
}
});
it('should support relationship link fetch', async () => {
setRequest({
name: 'events-1',
url: 'event',
});
const store = new TestStore();
const events = await store.fetchAll(Event);
const event = events.data && events.data instanceof Array && events.data[0];
setRequest({
name: 'image-1',
url: 'event/1/images',
});
expect(event).toBeInstanceOf(Event);
if (event) {
const image = await fetchModelRefLink(event, 'images', 'self');
const imageData = image.data as Image;
expect(imageData.meta.id).toBe('1');
expect(imageData.meta.type).toBe('image');
expect(imageData['url']).toBe('https://example.com/1.jpg');
}
});
it('should support endpoint', async () => {
class TestEvent extends jsonapi(Model) {
public static type = 'event';
public static endpoint = 'foo/event';
}
class TestCollection extends Collection {
public static types = [TestEvent];
}
const store = new (jsonapi(TestCollection))();
setRequest({
name: 'event-1',
url: 'foo/event',
});
const response = await store.fetchAll(TestEvent);
const event = response.data as TestEvent;
expect(event.meta.type).toBe('event');
const req = setRequest({
method: 'PATCH',
name: 'event-1',
url: 'foo/event/12345',
});
await event.save();
expect(req.isDone()).toBe(true);
});
it('should support functional endpoint', async () => {
class TestEvent extends jsonapi(Model) {
public static type = 'event';
public static endpoint = (baseUrl: string): string => {
return `${baseUrl}foo/event`;
};
}
class TestCollection extends Collection {
public static types = [TestEvent];
}
const store = new (jsonapi(TestCollection))();
setRequest({
name: 'event-1',
url: 'foo/event',
});
const response = await store.fetchAll(TestEvent);
const event = response.data as TestEvent;
expect(event.meta.type).toBe('event');
});
it('should prepend config.baseUrl to the request url', async () => {
setRequest({
name: 'event-1b',
url: 'event/1',
});
const store = new TestStore();
const events = await store.request('event/1');
const record = events.data as Event;
expect(record['title']).toBe('Test 1');
});
it('should prepend config.baseUrl to the request url with special characters', async () => {
setRequest({
name: 'event-1b',
url: 'event/1?test=hello%20world',
});
const store = new TestStore();
const events = await store.request('event/1?test=hello%20world');
const record = events.data as Event;
expect(record['title']).toBe('Test 1');
});
it('should handle the request methods', async () => {
setRequest({
method: 'PUT',
name: 'event-1b',
url: 'event/1',
});
const store = new TestStore();
const events = await store.request('event/1', 'PUT');
const record = events.data as Event;
expect(record['title']).toBe('Test 1');
});
}); | the_stack |
import { ChallengeRegistry } from "@connext/contracts";
import {
ILoggerService,
ChallengeEvents,
ChallengeEvent,
ChallengeEventData,
ChallengeStatus,
Address,
ContractAddressBook,
STATE_PROGRESSED_EVENT,
CHALLENGE_UPDATED_EVENT,
ChallengeUpdatedEventPayload,
StateProgressedEventPayload,
} from "@connext/types";
import { toBN } from "@connext/utils";
import { BigNumber, Contract, Event, providers, utils } from "ethers";
import { Ctx, Evt } from "evt";
const { Interface } = utils;
// While fetching historical data, we query this many blocks at a time
const chunkSize = 30;
// contract events are camel cased while offchain events are all caps
// this type is generated to bridge the gap for the listener
const ChainListenerEvents = {
[CHALLENGE_UPDATED_EVENT]: CHALLENGE_UPDATED_EVENT,
[STATE_PROGRESSED_EVENT]: STATE_PROGRESSED_EVENT,
} as const;
type ChainListenerEvent = keyof typeof ChainListenerEvents;
interface ChainListenerEventsMap {
[CHALLENGE_UPDATED_EVENT]: ChallengeUpdatedEventPayload;
[STATE_PROGRESSED_EVENT]: StateProgressedEventPayload;
}
type ChainListenerEventData = {
[P in keyof ChainListenerEventsMap]: ChainListenerEventsMap[P];
};
////////////////////////////////////////
// Listener interface
interface IChainListener {
////////////////////////////////////////
//// Public methods
attach<T extends ChallengeEvent>(
event: T,
callback: (data: ChallengeEventData[T]) => Promise<void>,
providedFilter?: (data: ChallengeEventData[T]) => boolean,
ctx?: Ctx<ChallengeEventData[T]>,
): void;
attachOnce<T extends ChallengeEvent>(
event: T,
callback: (data: ChallengeEventData[T]) => Promise<void>,
providedFilter?: (data: ChallengeEventData[T]) => boolean,
ctx?: Ctx<ChallengeEventData[T]>,
): void;
waitFor<T extends ChallengeEvent>(
event: T,
timeout: number,
providedFilter?: (data: ChallengeEventData[T]) => boolean,
ctx?: Ctx<ChallengeEventData[T]>,
): Promise<ChallengeEventData[T]>;
detach<T extends ChallengeEvent>(ctx?: Ctx<ChallengeEventData[T]>): void;
enable(): Promise<void>;
disable(): Promise<void>;
parseLogsFrom(startingBlock: number): Promise<void>;
////////////////////////////////////////
//// Unused methods (TODO: rm?)
createContext<T extends ChallengeEvent>(): Ctx<ChallengeEventData[T]>;
}
/**
* This class listens to events emitted by the connext contracts,
* parses them, and emits the properly typed version.
*
* Consumers of the class should instantiate it, then call the
* `enable` method to begin listening + parsing contract events. To
* turn off the listener, call `disable`
*/
export class ChainListener implements IChainListener {
private log: ILoggerService;
private enabled: boolean = false;
private registries: { [chainId: number]: Contract };
constructor(
private readonly providers: { [chainId: number]: providers.JsonRpcProvider },
private readonly context: ContractAddressBook,
loggerService: ILoggerService,
private readonly evtChallengeUpdated: Evt<
ChainListenerEventData[typeof ChainListenerEvents.CHALLENGE_UPDATED_EVENT]
> = Evt.create<ChainListenerEventData[typeof ChainListenerEvents.CHALLENGE_UPDATED_EVENT]>(),
private readonly evtStateProgressed: Evt<
ChainListenerEventData[typeof ChainListenerEvents.STATE_PROGRESSED_EVENT]
> = Evt.create<ChainListenerEventData[typeof ChainListenerEvents.STATE_PROGRESSED_EVENT]>(),
) {
this.log = loggerService.newContext("ChainListener");
const registries = {};
Object.entries(this.providers).forEach(([chainId, provider]) => {
registries[chainId] = new Contract(
this.context[chainId].ChallengeRegistry,
ChallengeRegistry.abi,
provider,
);
});
this.registries = registries;
}
// listens on every block for new contract events
public enable = async (): Promise<void> => {
if (this.enabled) {
return;
}
this.addChallengeRegistryListeners();
this.enabled = true;
};
// turns of the listener and event emission
public disable = async (): Promise<void> => {
if (!this.enabled) {
return;
}
this.detach();
this.removeChallengeRegistryListeners();
this.enabled = false;
};
// parses + emits any event logs from given block to current block
public parseLogsFrom = async (startingBlock: number): Promise<void> => {
const chainIds = Object.keys(this.providers).map((k) => parseInt(k));
for (const chainId of chainIds) {
const currentBlock = await this.providers[chainId].getBlockNumber();
if (startingBlock > currentBlock) {
throw new Error(
`Cannot parse events past current block (current: ${currentBlock}, starting: ${startingBlock})`,
);
}
const nChunks = Math.ceil((currentBlock - startingBlock) / chunkSize);
this.log.info(`Fetching logs from block ${startingBlock} to ${currentBlock}`);
const updatedLogs = [] as providers.Log[];
const progressedLogs = [] as providers.Log[];
for (let index = 0; index <= nChunks; index++) {
const fromBlock = startingBlock + index * chunkSize;
const nextChunk = startingBlock + (index + 1) * chunkSize - 1;
const toBlock = nextChunk >= currentBlock ? currentBlock : nextChunk;
const newUpdatedLogs = await this.providers[chainId].getLogs({
...this.registries[chainId].filters[ChallengeEvents.ChallengeUpdated](),
fromBlock,
toBlock,
});
const newProgressedLogs = await this.providers[chainId].getLogs({
...this.registries[chainId].filters[ChallengeEvents.StateProgressed](),
fromBlock,
toBlock,
});
updatedLogs.push(...newUpdatedLogs);
progressedLogs.push(...newProgressedLogs);
this.log.info(
`Fetched ${progressedLogs.length} StateProgressed & ${newUpdatedLogs.length} ` +
`ChallengeUpdated logs from block ${fromBlock} to ${toBlock} (${index}/${nChunks})`,
);
if (toBlock === currentBlock) break;
}
this.log.info(
`Parsing ${progressedLogs.length} StateProgessed and ${updatedLogs.length} ChallengeUpdated event logs`,
);
progressedLogs.forEach((log) => {
const args = (new Interface(ChallengeRegistry.abi).parseLog(log)).args;
const { action, identityHash, signature, timeout, turnTaker, versionNumber } = args;
this.evtStateProgressed.post({
identityHash,
action,
versionNumber,
timeout,
turnTaker,
signature,
chainId,
});
});
updatedLogs.forEach((log) => {
const args = (new Interface(ChallengeRegistry.abi).parseLog(log)).args;
const { appStateHash, finalizesAt, identityHash, status, versionNumber } = args;
this.evtChallengeUpdated.post({
identityHash,
status,
appStateHash,
versionNumber,
finalizesAt,
chainId,
});
});
}
};
////////////////////////////////////////
// Evt methods
public attach<T extends ChallengeEvent>(
event: T,
callback: (data: ChallengeEventData[T]) => Promise<void>,
providedFilter?: (data: ChallengeEventData[T]) => boolean,
ctx?: Ctx<ChallengeEventData[T]>,
): void {
const filter = (data: ChallengeEventData[T]) => {
if (providedFilter) {
return providedFilter(data);
}
return true;
};
const addToEvt = (evt: Evt<ChallengeEventData[T]>) => {
if (!ctx) {
evt.attach(filter, callback);
return;
}
evt.attach(filter, ctx, callback);
};
return addToEvt(
event === ChallengeEvents.ChallengeUpdated
? (this.evtChallengeUpdated as any)
: (this.evtStateProgressed as any),
);
}
public attachOnce<T extends ChallengeEvent>(
event: T,
callback: (data: ChallengeEventData[T]) => Promise<void>,
providedFilter?: (data: ChallengeEventData[T]) => boolean,
ctx?: Ctx<ChallengeEventData[T]>,
): void {
const filter = (data: ChallengeEventData[T]) => {
if (providedFilter) {
return providedFilter(data);
}
return true;
};
const addToEvt = (evt: Evt<ChallengeEventData[T]>) => {
if (!ctx) {
evt.attachOnce(filter, callback);
return;
}
evt.attachOnce(filter, ctx, callback);
};
return addToEvt(
event === ChallengeEvents.ChallengeUpdated
? (this.evtChallengeUpdated as any)
: (this.evtStateProgressed as any),
);
}
public async waitFor<T extends ChallengeEvent>(
event: T,
timeout: number,
providedFilter?: (data: ChallengeEventData[T]) => boolean,
ctx?: Ctx<ChallengeEventData[T]>,
): Promise<ChallengeEventData[T]> {
const filter = (data: ChallengeEventData[T]) => {
if (providedFilter) {
return providedFilter(data);
}
return true;
};
const addToEvt = (evt: Evt<ChallengeEventData[T]>) => {
if (!ctx) {
return evt.waitFor(filter, timeout);
}
return evt.waitFor(filter, ctx, timeout);
};
return addToEvt(
event === ChallengeEvents.ChallengeUpdated
? (this.evtChallengeUpdated as any)
: (this.evtStateProgressed as any),
);
}
// Creates a new void context for easy listener detachment
public createContext<T extends ChallengeEvent>(): Ctx<ChallengeEventData[T]> {
return Evt.newCtx<ChallengeEventData[T]>();
}
public detach<T extends ChallengeEvent>(ctx?: Ctx<ChallengeEventData[T]>): void {
this.evtChallengeUpdated.detach(ctx as any);
this.evtStateProgressed.detach(ctx as any);
}
////////////////////////////////////////
// Private methods
private removeChallengeRegistryListeners = (): void => {
Object.keys(this.providers).forEach(chainId => {
this.registries[chainId].removeAllListeners(ChallengeEvents.StateProgressed);
this.registries[chainId].removeAllListeners(ChallengeEvents.ChallengeUpdated);
});
this.log.debug("Removed challenge registry listeners");
};
// created listeners for the challenge registry
private addChallengeRegistryListeners = (): void => {
const chainIds = Object.keys(this.providers);
chainIds.forEach((chainIdStr) => {
const chainId = parseInt(chainIdStr);
this.registries[chainId].on(
ChallengeEvents.StateProgressed,
(
identityHash: string,
action: string,
versionNumber: BigNumber,
timeout: BigNumber,
turnTaker: Address,
signature: string,
event: Event,
) => {
this.evtStateProgressed.post({
identityHash,
action,
versionNumber: toBN(versionNumber),
timeout: toBN(timeout),
turnTaker,
signature,
chainId,
});
},
);
this.registries[chainId].on(
ChallengeEvents.ChallengeUpdated,
(
identityHash: string,
status: ChallengeStatus,
appStateHash: string,
versionNumber: BigNumber,
finalizesAt: BigNumber,
) => {
this.evtChallengeUpdated.post({
identityHash,
status,
appStateHash,
versionNumber: toBN(versionNumber),
finalizesAt: toBN(finalizesAt),
chainId,
});
},
);
});
this.log.debug("Registered challenge registry listeners");
};
} | the_stack |
import * as path from "path";
import * as fs from "fs";
import * as assert from "assert";
import { Node } from "../../src/common/node/node";
import { ReactNativeProjectHelper } from "../../src/common/reactNativeProjectHelper";
suite("ReactNativeProjectHelper", function () {
const fsHelper = new Node.FileSystem();
const sampleReactNativeProjectDir = path.join(
__dirname,
"..",
"resources",
"sampleReactNativeProject",
);
suite("isAndroidHermesEnabled", () => {
const buildGradleFilePath = path.join(
sampleReactNativeProjectDir,
"android",
"app",
"build.gradle",
);
suiteSetup(() => {
fsHelper.makeDirectoryRecursiveSync(path.dirname(buildGradleFilePath));
});
suiteTeardown(() => {
fsHelper.removePathRecursivelySync(path.join(sampleReactNativeProjectDir, "android"));
});
test("isAndroidHermesEnabled should return 'true' if Hermes engine is enabled in the build.gradle file", () => {
const buildGradleFileContent =
"project.ext.react = [\nenableHermes: true, // clean and rebuild if changing\n]";
fs.writeFileSync(buildGradleFilePath, buildGradleFileContent);
const androidHermesEnabled = ReactNativeProjectHelper.isAndroidHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(androidHermesEnabled, true);
});
test("isAndroidHermesEnabled should return 'false' if Hermes engine is disabled in the build.gradle file", () => {
const buildGradleFileContent =
"project.ext.react = [\nenableHermes: false, // clean and rebuild if changing\n]";
fs.writeFileSync(buildGradleFilePath, buildGradleFileContent);
const androidHermesEnabled = ReactNativeProjectHelper.isAndroidHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(androidHermesEnabled, false);
});
test("isAndroidHermesEnabled should return 'false' if the Hermes engine parameter is absent in the build.gradle file", () => {
const buildGradleFileContent = "project.ext.react = [\n]";
fs.writeFileSync(buildGradleFilePath, buildGradleFileContent);
const androidHermesEnabled = ReactNativeProjectHelper.isAndroidHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(androidHermesEnabled, false);
});
});
suite("isIOSHermesEnabled", () => {
const podfileFilePath = path.join(sampleReactNativeProjectDir, "ios", "Podfile");
suiteSetup(() => {
fsHelper.makeDirectoryRecursiveSync(path.dirname(podfileFilePath));
});
suiteTeardown(() => {
fsHelper.removePathRecursivelySync(path.join(sampleReactNativeProjectDir, "ios"));
});
test("isIOSHermesEnabled should return 'true' if Hermes engine is enabled in the Podfile file", () => {
const podfileFileContent =
" use_react_native!(\n" +
" :path => config[:reactNativePath],\n" +
" # to enable hermes on iOS, change `false` to `true` and then install pods\n" +
" :hermes_enabled => true\n" +
" )";
fs.writeFileSync(podfileFilePath, podfileFileContent);
const iOSHermesEnabled = ReactNativeProjectHelper.isIOSHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(iOSHermesEnabled, true);
});
test("isIOSHermesEnabled should return 'false' if Hermes engine is disabled in the Podfile file", () => {
const podfileFileContent =
" use_react_native!(\n" +
" :path => config[:reactNativePath],\n" +
" # to enable hermes on iOS, change `false` to `true` and then install pods\n" +
" :hermes_enabled => false\n" +
" )";
fs.writeFileSync(podfileFilePath, podfileFileContent);
const iOSHermesEnabled = ReactNativeProjectHelper.isIOSHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(iOSHermesEnabled, false);
});
test("isIOSHermesEnabled should return 'false' if the Hermes engine parameter is absent in the Podfile file", () => {
const podfileFileContent =
" use_react_native!(\n" + " :path => config[:reactNativePath],\n" + " )";
fs.writeFileSync(podfileFilePath, podfileFileContent);
const iOSHermesEnabled = ReactNativeProjectHelper.isIOSHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(iOSHermesEnabled, false);
});
});
suite("isMacOSHermesEnabled", () => {
const podfileFilePath = path.join(sampleReactNativeProjectDir, "macos", "Podfile");
suiteSetup(() => {
fsHelper.makeDirectoryRecursiveSync(path.dirname(podfileFilePath));
});
suiteTeardown(() => {
fsHelper.removePathRecursivelySync(path.join(sampleReactNativeProjectDir, "macos"));
});
test("isMacOSHermesEnabled should return 'true' if the 'hermes_enabled' parameter in the Podfile file is uncommented and equal to 'true'", () => {
const podfileFileContent =
" use_react_native!(\n" +
" :path => '../node_modules/react-native-macos',\n" +
" # To use Hermes, install the `hermes-engine-darwin` npm package, e.g.:\n" +
" # $ yarn add 'hermes-engine-darwin@~0.5.3'\n" +
" #\n" +
" # Then enable this option:\n" +
" :hermes_enabled => true\n" +
" )";
fs.writeFileSync(podfileFilePath, podfileFileContent);
const macOSHermesEnabled = ReactNativeProjectHelper.isMacOSHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(macOSHermesEnabled, true);
});
test("isMacOSHermesEnabled should return 'true' if the \"pod 'hermes'\" parameter in the Podfile file is uncommented", () => {
const podfileFileContent =
" target 'rnmacos62-macOS' do\n" +
" platform :macos, '10.13'\n" +
" use_native_modules!\n" +
" # Enables Hermes\n" +
" #\n" +
" # Be sure to first install the `hermes-engine-darwin` npm package, e.g.:\n" +
" #\n" +
" # $ yarn add 'hermes-engine-darwin@^0.4.3'\n" +
" #\n" +
" pod 'React-Core/Hermes', :path => '../node_modules/react-native-macos/'\n" +
" pod 'hermes', :path => '../node_modules/hermes-engine-darwin'\n" +
" pod 'libevent', :podspec => '../node_modules/react-native-macos/third-party-podspecs/libevent.podspec'\n" +
" # Pods specifically for macOS target\n" +
" end\n";
fs.writeFileSync(podfileFilePath, podfileFileContent);
const macOSHermesEnabled = ReactNativeProjectHelper.isMacOSHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(macOSHermesEnabled, true);
});
test("isMacOSHermesEnabled should return 'false' if the 'hermes_enabled' parameter in the Podfile file is commented and equal to 'true'", () => {
const podfileFileContent =
" use_react_native!(\n" +
" :path => '../node_modules/react-native-macos',\n" +
" # To use Hermes, install the `hermes-engine-darwin` npm package, e.g.:\n" +
" # $ yarn add 'hermes-engine-darwin@~0.5.3'\n" +
" #\n" +
" # Then enable this option:\n" +
" # :hermes_enabled => true\n" +
" )";
fs.writeFileSync(podfileFilePath, podfileFileContent);
const macOSHermesEnabled = ReactNativeProjectHelper.isMacOSHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(macOSHermesEnabled, false);
});
test("isMacOSHermesEnabled should return 'false' if the Hermes engine parameter is absent in the Podfile file", () => {
const podfileFileContent =
" use_react_native!(\n" +
" :path => '../node_modules/react-native-macos',\n" +
" )";
fs.writeFileSync(podfileFilePath, podfileFileContent);
const macOSHermesEnabled = ReactNativeProjectHelper.isMacOSHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(macOSHermesEnabled, false);
});
});
suite("isWindowsHermesEnabled", () => {
const experimentalFeaturesFilePath = path.join(
sampleReactNativeProjectDir,
"windows",
"ExperimentalFeatures.props",
);
suiteSetup(() => {
fsHelper.makeDirectoryRecursiveSync(path.dirname(experimentalFeaturesFilePath));
});
suiteTeardown(() => {
fsHelper.removePathRecursivelySync(path.join(sampleReactNativeProjectDir, "windows"));
});
test("isWindowsHermesEnabled should return 'true' if Hermes engine is enabled in the ExperimentalFeatures.props file", () => {
const experimentalFeaturesFileContent =
' <PropertyGroup Label="Microsoft.ReactNative Experimental Features">\n' +
" <!--\n" +
" Enables default usage of Hermes.\n" +
" \n" +
" See https://microsoft.github.io/react-native-windows/docs/hermes\n" +
" -->\n" +
" <UseHermes>true</UseHermes>\n" +
" <UseWinUI3>false</UseWinUI3>\n" +
" </PropertyGroup>";
fs.writeFileSync(experimentalFeaturesFilePath, experimentalFeaturesFileContent);
const windowsHermesEnabled = ReactNativeProjectHelper.isWindowsHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(windowsHermesEnabled, true);
});
test("isWindowsHermesEnabled should return 'fasle' if Hermes engine is disabled in the ExperimentalFeatures.props file", () => {
const experimentalFeaturesFileContent =
' <PropertyGroup Label="Microsoft.ReactNative Experimental Features">\n' +
" <!--\n" +
" Enables default usage of Hermes.\n" +
" \n";
" See https://microsoft.github.io/react-native-windows/docs/hermes\n" +
" -->\n" +
" <UseHermes>false</UseHermes>\n" +
" <UseWinUI3>false</UseWinUI3>\n" +
" </PropertyGroup>";
fs.writeFileSync(experimentalFeaturesFilePath, experimentalFeaturesFileContent);
const windowsHermesEnabled = ReactNativeProjectHelper.isWindowsHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(windowsHermesEnabled, false);
});
test("isWindowsHermesEnabled should return 'fasle' if there is no the ExperimentalFeatures.props file", () => {
fsHelper.removePathRecursivelySync(path.join(sampleReactNativeProjectDir, "windows"));
const windowsHermesEnabled = ReactNativeProjectHelper.isWindowsHermesEnabled(
sampleReactNativeProjectDir,
);
assert.strictEqual(windowsHermesEnabled, false);
});
});
}); | the_stack |
import "./test-helpers/staticTime";
import { BigNumber } from "bignumber.js";
import { getCryptoCurrencyById } from "../currencies";
import {
getDates,
getBalanceHistory,
getBalanceHistoryWithCountervalue,
getPortfolio,
getCurrencyPortfolio,
getAssetsDistribution,
} from "../portfolio";
import type { Account } from "../types";
import { genAccount } from "../mock/account";
import { getBTCValues } from "../countervalues/mock";
const baseMockBTCRates = getBTCValues();
const accounts = Array(100)
.fill(null)
.map((_, j) => genAccount("portfolio_" + j));
test("getBalanceHistory(*,month) returns an array of 30 items", () => {
const history = getBalanceHistory(genAccount("seed_1"), "month");
expect(history).toBeInstanceOf(Array);
expect(history.length).toBe(30);
expect(history).toMatchSnapshot();
});
test("getBalanceHistory(*,year) works as well", () => {
const history = getBalanceHistory(genAccount("seed_2"), "year");
expect(history).toBeInstanceOf(Array);
expect(history.length).toBe(52);
expect(history).toMatchSnapshot();
});
test("getDates matches getBalanceHistory dates", () => {
const history = getBalanceHistory(genAccount("seed_2"), "year");
const dates = getDates("year");
expect(history.map((p) => p.date)).toMatchObject(dates);
});
test("getBalanceHistory last item is now and have an amount equals to account balance", () => {
const account = genAccount("seed_3");
const history = getBalanceHistory(account, "month");
expect(history[history.length - 1].date).toMatchObject(new Date());
expect(history[history.length - 1].value).toBe(account.balance);
expect(history).toMatchSnapshot();
});
test("getBalanceHistoryWithCountervalue basic", () => {
const account = genAccount("bro4", {
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "month");
const cv = getBalanceHistoryWithCountervalue(
account,
"month",
(c, value) => value
);
expect(cv.countervalueAvailable).toBe(true);
// expect(
// cv.history.map((p) => ({ date: p.date, value: p.countervalue }))
// ).toMatchObject(history);
expect(
cv.history.map((p) => ({
date: p.date,
value: p.value,
}))
).toMatchObject(history);
});
test("getPortfolio works with one account and is identically to that account history", () => {
const account = genAccount("seed_4", {
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "week");
const portfolio = getPortfolio(
[account],
"week",
(account, value) => value // using identity, at any time, 1 token = 1 USD
);
expect(portfolio.availableAccounts).toMatchObject([account]);
expect(portfolio.balanceAvailable).toBe(true);
expect(portfolio.balanceHistory).toMatchObject(history);
expect(portfolio.balanceHistory).toMatchSnapshot();
});
test("getCurrencyPortfolio works with one account and is identically to that account history", () => {
const account = genAccount("seed_4", {
subAccountsCount: 0,
});
const calc = (account, value) => value.times(0.1);
const { history } = getBalanceHistoryWithCountervalue(account, "week", calc);
const accounts: Account[] = [account];
const portfolio = getCurrencyPortfolio(accounts, "week", calc);
expect(portfolio.countervalueAvailable).toBe(true);
expect(portfolio.history).toMatchObject(history);
expect(portfolio.history).toMatchSnapshot();
});
test("getBalanceHistoryWithCountervalue to have proper countervalues", () => {
const account = genAccount("bro1", {
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "week");
const calc = (account, value) => value.times(3);
const cv = getBalanceHistoryWithCountervalue(account, "week", calc);
expect(
cv.history.map((p) => ({
date: p.date,
value: p.countervalue.div(3),
}))
).toMatchObject(history);
});
test("getBalanceHistoryWithCountervalue is same as getPortfolio with one account", () => {
const account = genAccount("bro2", {
subAccountsCount: 0,
});
const calc = (account, value) => value.times(3);
const cv = getBalanceHistoryWithCountervalue(account, "month", calc);
const portfolio = getPortfolio([account], "month", calc);
expect(
cv.history.map((p) => ({
date: p.date,
value: p.countervalue,
}))
).toMatchObject(portfolio.balanceHistory);
});
test("getPortfolio calculateCounterValue can returns missing countervalue", () => {
const account = genAccount("seed_6", {
currency: getCryptoCurrencyById("bitcoin"),
subAccountsCount: 0,
});
const account2 = genAccount("seed_7", {
currency: getCryptoCurrencyById("ethereum"),
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "month");
const portfolio = getPortfolio([account, account2], "month", (c, value) =>
c.id === "bitcoin" ? value : null
);
expect(portfolio.balanceHistory).toMatchObject(history);
expect(portfolio.balanceAvailable).toBe(true);
expect(portfolio.unavailableCurrencies.length).toBe(1);
});
test("getPortfolio with twice same account will double the amounts", () => {
const account = genAccount("seed_5", {
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "week");
const allHistory = getPortfolio(
[account, account],
"week",
(c, value) => value // using identity, at any time, 1 token = 1 USD
);
allHistory.balanceHistory.forEach((h, i) => {
expect(h.value.toString()).toBe(history[i].value.times(2).toString());
});
});
test("getCurrencyPortfolio with twice same account will double the amounts", () => {
const account = genAccount("seed_5", {
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "week");
const accounts: Account[] = [account, account];
const allHistory = getCurrencyPortfolio(
accounts,
"week",
(c, value) => value // using identity, at any time, 1 token = 1 USD
);
allHistory.history.forEach((h, i) => {
expect(h.value.toString()).toBe(history[i].value.times(2).toString());
});
});
test("getPortfolio calculateCounterValue is taken into account", () => {
const account = genAccount("seed_6", {
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "month");
const portfolio = getPortfolio([account, account], "month", (c, value) =>
value.div(2)
);
expect(portfolio.balanceHistory).toMatchObject(history);
});
test("getCurrencyPortfolio calculateCounterValue is taken into account", () => {
const account = genAccount("seed_6", {
subAccountsCount: 0,
});
const { history } = getBalanceHistoryWithCountervalue(
account,
"month",
(c, value) => value
);
const accounts: Account[] = [account, account];
const portfolio = getCurrencyPortfolio(accounts, "month", (c, value) =>
value.div(2)
);
expect(portfolio.history.map((h) => h.value.div(2).toString())).toMatchObject(
history.map((h) => h.value.toString())
);
expect(portfolio.history.map((h) => h.countervalue.toString())).toMatchObject(
history.map((h) => h.countervalue.toString())
);
});
test("getPortfolio calculateCounterValue can returns missing countervalue", () => {
const account = genAccount("seed_6", {
currency: getCryptoCurrencyById("bitcoin"),
subAccountsCount: 0,
});
const account2 = genAccount("seed_7", {
currency: getCryptoCurrencyById("ethereum"),
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "month");
const portfolio = getPortfolio([account, account2], "month", (c, value) =>
c.id === "bitcoin" ? value : null
);
expect(portfolio.balanceHistory).toMatchObject(history);
expect(portfolio.balanceAvailable).toBe(true);
expect(portfolio.unavailableCurrencies.length).toBe(1);
});
test("getCurrencyPortfolio calculateCounterValue can miss countervalue", () => {
const account = genAccount("seed_6", {
currency: getCryptoCurrencyById("bitcoin"),
subAccountsCount: 0,
});
const account2 = genAccount("seed_7", {
currency: getCryptoCurrencyById("bitcoin"),
subAccountsCount: 0,
});
const history = getBalanceHistory(account, "month");
const history2 = getBalanceHistory(account2, "month");
const accs: Account[] = [account, account2];
const portfolio = getCurrencyPortfolio(accs, "month", () => null);
expect(portfolio.history).toMatchObject(
history.map((p, i) => ({ ...p, value: p.value.plus(history2[i].value) }))
);
expect(portfolio.countervalueAvailable).toBe(false);
});
test("getPortfolio calculateCounterValue can complete fails", () => {
const account = genAccount("seed_6", {
subAccountsCount: 0,
});
const account2 = genAccount("seed_7", {
subAccountsCount: 0,
});
const portfolio = getPortfolio([account, account2], "month", () => null);
expect(portfolio.balanceAvailable).toBe(false);
});
test("getPortfolio with lot of accounts", () => {
const portfolio = getPortfolio(
accounts,
"week",
(c, value) => value // using identity, at any time, 1 token = 1 USD
);
expect(portfolio.balanceHistory).toMatchSnapshot();
});
test("getAssetsDistribution 1", () => {
const assetsDistribution = getAssetsDistribution(
accounts,
(currency, value) => {
const rate = baseMockBTCRates[currency.ticker];
if (rate) return value.times(rate);
}
);
expect(assetsDistribution.isAvailable).toBe(true);
expect(assetsDistribution.showFirst).toBe(2);
expect(
assetsDistribution.list.reduce((sum, o) => sum + o.distribution, 0)
).toBeCloseTo(1);
expect(
assetsDistribution.list.map((o) => [
o.currency.ticker,
o.amount,
o.countervalue,
o.distribution,
])
).toMatchSnapshot();
});
test("getAssetsDistribution mult", () => {
const calc = (currency, value) => {
const rate = baseMockBTCRates[currency.ticker];
if (rate) return value.times(rate);
};
for (let i = 0; i < accounts.length; i++) {
const assetsDistribution = getAssetsDistribution(
accounts.slice(0, i),
calc
);
// identity cached by ref
expect(getAssetsDistribution(accounts.slice(0, i), calc)).toBe(
assetsDistribution
);
if (assetsDistribution.isAvailable) {
expect(assetsDistribution.sum.toString()).toBe(
assetsDistribution.list
.reduce(
(sum: BigNumber, o) => sum.plus(o.countervalue),
new BigNumber(0)
)
.toString()
);
expect(assetsDistribution.showFirst).toBeLessThanOrEqual(
assetsDistribution.list.length
);
expect(
assetsDistribution.list.reduce((sum, o) => sum + o.distribution, 0)
).toBeCloseTo(1);
} else {
expect(assetsDistribution.list.length).toBe(0);
}
}
});
test("getPortfolio do not crash if range history have different size", () => {
let account1 = genAccount("seed_8", {
currency: getCryptoCurrencyById("bitcoin"),
});
let account2 = genAccount("seed_9", {
currency: getCryptoCurrencyById("bitcoin"),
});
let account3 = genAccount("seed_10", {
currency: getCryptoCurrencyById("bitcoin"),
});
const history1 = getBalanceHistory(account1, "month");
const history2 = getBalanceHistory(account2, "month");
const calc = (c, value) => value;
getPortfolio([account1, account2, account3], "month", calc);
account1 = {
...account1,
balanceHistory: {
month: history1.concat(history1),
year: undefined,
week: undefined,
day: undefined,
},
};
getPortfolio([account1, account2, account3], "month", calc);
account2 = {
...account2,
balanceHistory: {
month: history2.slice(5),
year: undefined,
week: undefined,
day: undefined,
},
};
getPortfolio([account1, account2, account3], "month", calc);
account3 = {
...account3,
balanceHistory: {
month: [],
year: undefined,
week: undefined,
day: undefined,
},
};
const portfolio = getPortfolio([account1, account2, account3], "month", calc);
expect(portfolio.balanceAvailable).toBe(true);
expect(portfolio.unavailableCurrencies.length).toBe(0);
}); | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormSalesOrderDetail_Field_Service_Information {
interface tab_address_Sections {
ship_to_address: DevKit.Controls.Section;
}
interface tab_delivery_Sections {
delivery_information: DevKit.Controls.Section;
fulfillment: DevKit.Controls.Section;
}
interface tab_general_Sections {
pricing: DevKit.Controls.Section;
sales_order_detail_information: DevKit.Controls.Section;
}
interface tab_servicemaintenanceline_Sections {
servicemaintenanceline: DevKit.Controls.Section;
}
interface tab_address extends DevKit.Controls.ITab {
Section: tab_address_Sections;
}
interface tab_delivery extends DevKit.Controls.ITab {
Section: tab_delivery_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_servicemaintenanceline extends DevKit.Controls.ITab {
Section: tab_servicemaintenanceline_Sections;
}
interface Tabs {
address: tab_address;
delivery: tab_delivery;
general: tab_general;
servicemaintenanceline: tab_servicemaintenanceline;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the order product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Shows the total amount due for the order product, based on the sum of the unit price, quantity, discounts, and tax. */
ExtendedAmount: DevKit.Controls.Money;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the order product. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the order. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the order product to deduct any negotiated or other savings from the product total on the order. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Select a Agreement for this order line */
msdyn_agreement: DevKit.Controls.Lookup;
/** The field to distinguish the order lines to be of project service or field service */
msdyn_LineType: DevKit.Controls.OptionSet;
/** Type the price per unit of the order product. The default is the value in the price list specified on the order for existing products. */
PricePerUnit: DevKit.Controls.Money;
/** Type a name or description to identify the type of write-in product included in the order. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the order to link the product's pricing and other information to the parent order. */
ProductId: DevKit.Controls.Lookup;
/** Type the amount or quantity of the product ordered by the customer. */
Quantity: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that is back ordered for the order. */
QuantityBackordered: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that was canceled. */
QuantityCancelled: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that was shipped for the order. */
QuantityShipped: DevKit.Controls.Decimal;
/** Enter the delivery date requested by the customer for the order product. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Choose the user responsible for the sale of the order product. */
SalesRepId: DevKit.Controls.Lookup;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.Controls.String;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.Controls.String;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.Controls.String;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.Controls.String;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.Controls.OptionSet;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.Controls.String;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.Controls.String;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.Controls.String;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.Controls.String;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.Controls.String;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.Controls.String;
/** Type the tax amount for the order product. */
Tax: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
/** Select whether the order product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
}
class FormSalesOrderDetail_Field_Service_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form SalesOrderDetail_Field_Service_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form SalesOrderDetail_Field_Service_Information */
Body: DevKit.FormSalesOrderDetail_Field_Service_Information.Body;
}
namespace FormSalesOrderDetail_Information {
interface tab_address_Sections {
ship_to_address: DevKit.Controls.Section;
}
interface tab_delivery_Sections {
delivery_information: DevKit.Controls.Section;
fulfillment: DevKit.Controls.Section;
}
interface tab_editproductpropertiesinlinetab_Sections {
productpropertiessection: DevKit.Controls.Section;
}
interface tab_general_Sections {
pricing: DevKit.Controls.Section;
sales_order_detail_information: DevKit.Controls.Section;
}
interface tab_address extends DevKit.Controls.ITab {
Section: tab_address_Sections;
}
interface tab_delivery extends DevKit.Controls.ITab {
Section: tab_delivery_Sections;
}
interface tab_editproductpropertiesinlinetab extends DevKit.Controls.ITab {
Section: tab_editproductpropertiesinlinetab_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface Tabs {
address: tab_address;
delivery: tab_delivery;
editproductpropertiesinlinetab: tab_editproductpropertiesinlinetab;
general: tab_general;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the order product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Shows the total amount due for the order product, based on the sum of the unit price, quantity, discounts, and tax. */
ExtendedAmount: DevKit.Controls.Money;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the order product. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the order. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the order product to deduct any negotiated or other savings from the product total on the order. */
ManualDiscountAmount: DevKit.Controls.Money;
/** The field to distinguish the order lines to be of project service or field service */
msdyn_LineType: DevKit.Controls.OptionSet;
/** Type the price per unit of the order product. The default is the value in the price list specified on the order for existing products. */
PricePerUnit: DevKit.Controls.Money;
/** Type a name or description to identify the type of write-in product included in the order. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the order to link the product's pricing and other information to the parent order. */
ProductId: DevKit.Controls.Lookup;
editpropertiescontrol: DevKit.Controls.ActionCards;
/** Type the amount or quantity of the product ordered by the customer. */
Quantity: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that is back ordered for the order. */
QuantityBackordered: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that was canceled. */
QuantityCancelled: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that was shipped for the order. */
QuantityShipped: DevKit.Controls.Decimal;
/** Enter the delivery date requested by the customer for the order product. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Shows the order for the product. The ID is used to link product pricing and other details to the total amounts and other information on the order. */
SalesOrderId: DevKit.Controls.Lookup;
/** Shows the order for the product. The ID is used to link product pricing and other details to the total amounts and other information on the order. */
SalesOrderId_1: DevKit.Controls.Lookup;
/** Choose the user responsible for the sale of the order product. */
SalesRepId: DevKit.Controls.Lookup;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.Controls.String;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.Controls.String;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.Controls.String;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.Controls.String;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.Controls.OptionSet;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.Controls.String;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.Controls.String;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.Controls.String;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.Controls.String;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.Controls.String;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.Controls.String;
/** Type the tax amount for the order product. */
Tax: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
/** Select whether the order product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
}
class FormSalesOrderDetail_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form SalesOrderDetail_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form SalesOrderDetail_Information */
Body: DevKit.FormSalesOrderDetail_Information.Body;
}
namespace FormSalesOrderDetail_Project_Information {
interface tab_address_Sections {
ship_to_address: DevKit.Controls.Section;
}
interface tab_ChargeableCategoriesTab_Sections {
ChargeableCategories: DevKit.Controls.Section;
}
interface tab_ChargeableRolesTab_Sections {
ChargeableRoles: DevKit.Controls.Section;
}
interface tab_delivery_Sections {
delivery_information: DevKit.Controls.Section;
fulfillment: DevKit.Controls.Section;
}
interface tab_general_Sections {
pricing: DevKit.Controls.Section;
sales_order_detail_information: DevKit.Controls.Section;
}
interface tab_GeneralProductTab_Sections {
CostSection: DevKit.Controls.Section;
ProductSection: DevKit.Controls.Section;
SalesSection: DevKit.Controls.Section;
}
interface tab_GeneralProjectTab_Sections {
AmountSection: DevKit.Controls.Section;
ProjectSection: DevKit.Controls.Section;
TransactionTypesSection: DevKit.Controls.Section;
}
interface tab_InvoiceScheduleTab_Sections {
InvoiceScheduleSection: DevKit.Controls.Section;
InvoiceScheduleTab_Header: DevKit.Controls.Section;
MilestoneSection: DevKit.Controls.Section;
}
interface tab_ProductTypeTab_Sections {
ProductTypeTab_section_2: DevKit.Controls.Section;
ProductTypeTab_section_3: DevKit.Controls.Section;
tab_8_section_1: DevKit.Controls.Section;
}
interface tab_TransactionsTab_Sections {
TransactionsSection: DevKit.Controls.Section;
}
interface tab_address extends DevKit.Controls.ITab {
Section: tab_address_Sections;
}
interface tab_ChargeableCategoriesTab extends DevKit.Controls.ITab {
Section: tab_ChargeableCategoriesTab_Sections;
}
interface tab_ChargeableRolesTab extends DevKit.Controls.ITab {
Section: tab_ChargeableRolesTab_Sections;
}
interface tab_delivery extends DevKit.Controls.ITab {
Section: tab_delivery_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_GeneralProductTab extends DevKit.Controls.ITab {
Section: tab_GeneralProductTab_Sections;
}
interface tab_GeneralProjectTab extends DevKit.Controls.ITab {
Section: tab_GeneralProjectTab_Sections;
}
interface tab_InvoiceScheduleTab extends DevKit.Controls.ITab {
Section: tab_InvoiceScheduleTab_Sections;
}
interface tab_ProductTypeTab extends DevKit.Controls.ITab {
Section: tab_ProductTypeTab_Sections;
}
interface tab_TransactionsTab extends DevKit.Controls.ITab {
Section: tab_TransactionsTab_Sections;
}
interface Tabs {
address: tab_address;
ChargeableCategoriesTab: tab_ChargeableCategoriesTab;
ChargeableRolesTab: tab_ChargeableRolesTab;
delivery: tab_delivery;
general: tab_general;
GeneralProductTab: tab_GeneralProductTab;
GeneralProjectTab: tab_GeneralProjectTab;
InvoiceScheduleTab: tab_InvoiceScheduleTab;
ProductTypeTab: tab_ProductTypeTab;
TransactionsTab: tab_TransactionsTab;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the order product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Shows the total amount due for the order product, based on the sum of the unit price, quantity, discounts, and tax. */
ExtendedAmount: DevKit.Controls.Money;
/** Shows the total amount due for the order product, based on the sum of the unit price, quantity, discounts, and tax. */
ExtendedAmount_1: DevKit.Controls.Money;
/** Shows the total amount due for the order product, based on the sum of the unit price, quantity, discounts, and tax. */
ExtendedAmount_2: DevKit.Controls.Money;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the order product. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the order. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the order. */
IsProductOverridden_1: DevKit.Controls.Boolean;
/** Type the manual discount amount for the order product to deduct any negotiated or other savings from the product total on the order. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Billing method for the project contract line. Valid values are Time and Material and Fixed Price */
msdyn_BillingMethod: DevKit.Controls.OptionSet;
/** Select the billing start date for the project contract line. */
msdyn_BillingStartDate: DevKit.Controls.Date;
/** Select the billing status for the project contract line. */
msdyn_BillingStatus: DevKit.Controls.OptionSet;
/** Enter the amount the customer has set aside or is willing to pay for the project contract component. */
msdyn_BudgetAmount: DevKit.Controls.Money;
/** Enter the amount the customer has set aside or is willing to pay for the project contract component. */
msdyn_BudgetAmount_1: DevKit.Controls.Money;
/** Shows the total cost price of the product based on the cost price per unit and quantity. */
msdyn_CostAmount: DevKit.Controls.Money;
/** Cost per unit of the product. The default is the cost price of the product. */
msdyn_CostPricePerUnit: DevKit.Controls.Money;
/** Select whether to include expenses in the project contract line. */
msdyn_IncludeExpense: DevKit.Controls.Boolean;
/** Select whether to include fees in the project contract line. */
msdyn_IncludeFee: DevKit.Controls.Boolean;
/** Select whether to include time transactions in the project contract line. */
msdyn_IncludeTime: DevKit.Controls.Boolean;
/** Select the frequency for the automatic invoice creation job to create the invoice. */
msdyn_invoicefrequency: DevKit.Controls.Lookup;
/** The field to distinguish the order lines to be of project service or field service */
msdyn_LineType: DevKit.Controls.OptionSet;
/** Select the project of the project contract line. */
msdyn_Project: DevKit.Controls.Lookup;
/** Type the price per unit of the order product. The default is the value in the price list specified on the order for existing products. */
PricePerUnit: DevKit.Controls.Money;
/** Type the price per unit of the order product. The default is the value in the price list specified on the order for existing products. */
PricePerUnit_1: DevKit.Controls.Money;
/** Type the price per unit of the order product. The default is the value in the price list specified on the order for existing products. */
PricePerUnit_2: DevKit.Controls.Money;
/** Type a name or description to identify the type of write-in product included in the order. */
ProductDescription: DevKit.Controls.String;
/** Type a name or description to identify the type of write-in product included in the order. */
ProductDescription_1: DevKit.Controls.String;
/** Type a name or description to identify the type of write-in product included in the order. */
ProductDescription_2: DevKit.Controls.String;
/** Choose the product to include on the order to link the product's pricing and other information to the parent order. */
ProductId: DevKit.Controls.Lookup;
/** Choose the product to include on the order to link the product's pricing and other information to the parent order. */
ProductId_1: DevKit.Controls.Lookup;
/** Product Type */
ProductTypeCode: DevKit.Controls.OptionSet;
/** Product Type */
ProductTypeCode_1: DevKit.Controls.OptionSet;
/** Product Type */
ProductTypeCode_2: DevKit.Controls.OptionSet;
/** Product Type */
ProductTypeCode_3: DevKit.Controls.OptionSet;
/** Type the amount or quantity of the product ordered by the customer. */
Quantity: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product ordered by the customer. */
Quantity_1: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that is back ordered for the order. */
QuantityBackordered: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that was canceled. */
QuantityCancelled: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product that was shipped for the order. */
QuantityShipped: DevKit.Controls.Decimal;
/** Enter the delivery date requested by the customer for the order product. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Enter the delivery date requested by the customer for the order product. */
RequestDeliveryBy_1: DevKit.Controls.Date;
/** Shows the order for the product. The ID is used to link product pricing and other details to the total amounts and other information on the order. */
SalesOrderId: DevKit.Controls.Lookup;
/** Shows the order for the product. The ID is used to link product pricing and other details to the total amounts and other information on the order. */
SalesOrderId_1: DevKit.Controls.Lookup;
/** Shows the order for the product. The ID is used to link product pricing and other details to the total amounts and other information on the order. */
SalesOrderId_2: DevKit.Controls.Lookup;
/** Shows the order for the product. The ID is used to link product pricing and other details to the total amounts and other information on the order. */
SalesOrderId_3: DevKit.Controls.Lookup;
/** Choose the user responsible for the sale of the order product. */
SalesRepId: DevKit.Controls.Lookup;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.Controls.String;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.Controls.String;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.Controls.String;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.Controls.String;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.Controls.OptionSet;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.Controls.String;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.Controls.String;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.Controls.String;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.Controls.String;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.Controls.String;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.Controls.String;
/** Type the tax amount for the order product. */
Tax: DevKit.Controls.Money;
/** Type the tax amount for the order product. */
Tax_1: DevKit.Controls.Money;
/** Type the tax amount for the order product. */
Tax_2: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId_1: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
/** Select whether the order product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
interface Grid {
ChargeableRolesGrid: DevKit.Controls.Grid;
ChargeableCategoriesGrid: DevKit.Controls.Grid;
ContractLineDetails: DevKit.Controls.Grid;
InvoiceScheduleGrid: DevKit.Controls.Grid;
MilestonesGrid: DevKit.Controls.Grid;
}
}
class FormSalesOrderDetail_Project_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form SalesOrderDetail_Project_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form SalesOrderDetail_Project_Information */
Body: DevKit.FormSalesOrderDetail_Project_Information.Body;
/** The Grid of form SalesOrderDetail_Project_Information */
Grid: DevKit.FormSalesOrderDetail_Project_Information.Grid;
}
namespace FormSalesOrderDetail {
interface tab_general_Sections {
delivery: DevKit.Controls.Section;
pricing: DevKit.Controls.Section;
sales_order_detail_information: DevKit.Controls.Section;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface Tabs {
general: tab_general;
}
interface Body {
Tab: Tabs;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the order product. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the order. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the order product to deduct any negotiated or other savings from the product total on the order. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Type the price per unit of the order product. The default is the value in the price list specified on the order for existing products. */
PricePerUnit: DevKit.Controls.Money;
/** Type a name or description to identify the type of write-in product included in the order. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the order to link the product's pricing and other information to the parent order. */
ProductId: DevKit.Controls.Lookup;
/** Type the amount or quantity of the product ordered by the customer. */
Quantity: DevKit.Controls.Decimal;
/** Enter the delivery date requested by the customer for the order product. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Shows the order for the product. The ID is used to link product pricing and other details to the total amounts and other information on the order. */
SalesOrderId: DevKit.Controls.Lookup;
/** Choose the user responsible for the sale of the order product. */
SalesRepId: DevKit.Controls.Lookup;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.Controls.String;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.Controls.String;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.Controls.String;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.Controls.String;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.Controls.OptionSet;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.Controls.String;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.Controls.String;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.Controls.String;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.Controls.String;
/** Type the tax amount for the order product. */
Tax: DevKit.Controls.Money;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Select whether the order product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
}
class FormSalesOrderDetail extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form SalesOrderDetail
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form SalesOrderDetail */
Body: DevKit.FormSalesOrderDetail.Body;
}
class SalesOrderDetailApi {
/**
* DynamicsCrm.DevKit SalesOrderDetailApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Shows the total price of the order product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.WebApi.MoneyValue;
/** Value of the Amount in base currency. */
BaseAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Type additional information to describe the order product, such as manufacturing details or acceptable substitutions. */
Description: DevKit.WebApi.StringValue;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Shows the total amount due for the order product, based on the sum of the unit price, quantity, discounts, and tax. */
ExtendedAmount: DevKit.WebApi.MoneyValue;
/** Value of the Extended Amount in base currency. */
ExtendedAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Select whether the invoice line item is copied from another item or data source. */
IsCopied: DevKit.WebApi.BooleanValue;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the order product. */
IsPriceOverridden: DevKit.WebApi.BooleanValue;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the order. */
IsProductOverridden: DevKit.WebApi.BooleanValue;
/** Type the line item number for the order product to easily identify the product in the order and make sure it's listed in the correct sequence. */
LineItemNumber: DevKit.WebApi.IntegerValue;
/** Type the manual discount amount for the order product to deduct any negotiated or other savings from the product total on the order. */
ManualDiscountAmount: DevKit.WebApi.MoneyValue;
/** Value of the Manual Discount in base currency. */
ManualDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Select a Agreement for this order line */
msdyn_agreement: DevKit.WebApi.LookupValue;
/** Billing method for the project contract line. Valid values are Time and Material and Fixed Price */
msdyn_BillingMethod: DevKit.WebApi.OptionSetValue;
/** Select the billing start date for the project contract line. */
msdyn_BillingStartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Select the billing status for the project contract line. */
msdyn_BillingStatus: DevKit.WebApi.OptionSetValue;
/** Enter the amount the customer has set aside or is willing to pay for the project contract component. */
msdyn_BudgetAmount: DevKit.WebApi.MoneyValue;
/** Value of the Budget Amount in base currency. */
msdyn_budgetamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total cost price of the product based on the cost price per unit and quantity. */
msdyn_CostAmount: DevKit.WebApi.MoneyValue;
/** Value of the Cost Amount in base currency. */
msdyn_costamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Cost per unit of the product. The default is the cost price of the product. */
msdyn_CostPricePerUnit: DevKit.WebApi.MoneyValue;
/** Value of the Cost Price Per Unit in base currency. */
msdyn_costpriceperunit_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select whether to include expenses in the project contract line. */
msdyn_IncludeExpense: DevKit.WebApi.BooleanValue;
/** Select whether to include fees in the project contract line. */
msdyn_IncludeFee: DevKit.WebApi.BooleanValue;
/** Select whether to include materials in the project contract line. */
msdyn_IncludeMaterial: DevKit.WebApi.BooleanValue;
/** Select whether to include time transactions in the project contract line. */
msdyn_IncludeTime: DevKit.WebApi.BooleanValue;
/** Select the frequency for the automatic invoice creation job to create the invoice. */
msdyn_invoicefrequency: DevKit.WebApi.LookupValue;
/** The field to distinguish the order lines to be of project service or field service */
msdyn_LineType: DevKit.WebApi.OptionSetValue;
/** Select the project of the project contract line. */
msdyn_Project: DevKit.WebApi.LookupValue;
/** (Deprecated) Shows the quote line related to the project contract line. */
msdyn_QuoteLine: DevKit.WebApi.StringValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValueReadonly;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Choose the parent bundle associated with this product */
ParentBundleId: DevKit.WebApi.GuidValue;
/** Choose the parent bundle associated with this product */
ParentBundleIdRef: DevKit.WebApi.LookupValue;
/** Type the price per unit of the order product. The default is the value in the price list specified on the order for existing products. */
PricePerUnit: DevKit.WebApi.MoneyValue;
/** Value of the Price Per Unit in base currency. */
PricePerUnit_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select the type of pricing error, such as a missing or invalid product, or missing quantity. */
PricingErrorCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the product line item association with bundle in the sales order */
ProductAssociationId: DevKit.WebApi.GuidValue;
/** Type a name or description to identify the type of write-in product included in the order. */
ProductDescription: DevKit.WebApi.StringValue;
/** Choose the product to include on the order to link the product's pricing and other information to the parent order. */
ProductId: DevKit.WebApi.LookupValue;
/** Calculated field that will be populated by name and description of the product. */
ProductName: DevKit.WebApi.StringValue;
/** User-defined product ID. */
ProductNumber: DevKit.WebApi.StringValueReadonly;
/** Product Type */
ProductTypeCode: DevKit.WebApi.OptionSetValue;
/** Status of the property configuration. */
PropertyConfigurationStatus: DevKit.WebApi.OptionSetValue;
/** Type the amount or quantity of the product ordered by the customer. */
Quantity: DevKit.WebApi.DecimalValue;
/** Type the amount or quantity of the product that is back ordered for the order. */
QuantityBackordered: DevKit.WebApi.DecimalValue;
/** Type the amount or quantity of the product that was canceled. */
QuantityCancelled: DevKit.WebApi.DecimalValue;
/** Type the amount or quantity of the product that was shipped for the order. */
QuantityShipped: DevKit.WebApi.DecimalValue;
/** Unique identifier for Quote Line associated with Order Line. */
QuoteDetailId: DevKit.WebApi.LookupValue;
/** Enter the delivery date requested by the customer for the order product. */
RequestDeliveryBy_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Unique identifier of the product specified in the order. */
SalesOrderDetailId: DevKit.WebApi.GuidValue;
/** Sales Order Detail Name. Added for 1:n referential relationship (internal purposes only) */
SalesOrderDetailName: DevKit.WebApi.StringValue;
/** Shows the order for the product. The ID is used to link product pricing and other details to the total amounts and other information on the order. */
SalesOrderId: DevKit.WebApi.LookupValue;
/** Tells whether product pricing is locked for the order. */
SalesOrderIsPriceLocked: DevKit.WebApi.BooleanValueReadonly;
/** Shows the status of the order that the order detail is associated with. */
SalesOrderStateCode: DevKit.WebApi.OptionSetValueReadonly;
/** Choose the user responsible for the sale of the order product. */
SalesRepId: DevKit.WebApi.LookupValue;
/** Shows the ID of the data that maintains the sequence. */
SequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the shipping address. */
ShipTo_AddressId: DevKit.WebApi.GuidValue;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.WebApi.StringValue;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.WebApi.StringValue;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.WebApi.StringValue;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.WebApi.StringValue;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.WebApi.OptionSetValue;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.WebApi.StringValue;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.WebApi.StringValue;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.WebApi.StringValue;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.WebApi.StringValue;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.WebApi.StringValue;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.WebApi.StringValue;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.WebApi.StringValue;
/** Skip the price calculation */
SkipPriceCalculation: DevKit.WebApi.OptionSetValue;
/** Type the tax amount for the order product. */
Tax: DevKit.WebApi.MoneyValue;
/** Value of the Tax in base currency. */
Tax_Base: DevKit.WebApi.MoneyValueReadonly;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.WebApi.LookupValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Volume Discount in base currency. */
VolumeDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select whether the order product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.WebApi.BooleanValue;
}
}
declare namespace OptionSet {
namespace SalesOrderDetail {
enum msdyn_BillingMethod {
/** 192350001 */
Fixed_Price,
/** 192350000 */
Time_and_Material
}
enum msdyn_BillingStatus {
/** 192350003 */
Canceled,
/** 192350001 */
Customer_Invoice_Created,
/** 192350002 */
Customer_Invoice_Posted,
/** 192350004 */
Ready_to_Invoice,
/** 192350000 */
Unbilled_Sales_Created,
/** 690970000 */
Work_order_closed_posted
}
enum msdyn_LineType {
/** 690970001 */
Field_Service_Line,
/** 690970000 */
Project_Service_Line
}
enum PricingErrorCode {
/** 36 */
Base_Currency_Attribute_Overflow,
/** 37 */
Base_Currency_Attribute_Underflow,
/** 1 */
Detail_Error,
/** 27 */
Discount_Type_Invalid_State,
/** 33 */
Inactive_Discount_Type,
/** 3 */
Inactive_Price_Level,
/** 20 */
Invalid_Current_Cost,
/** 28 */
Invalid_Discount,
/** 26 */
Invalid_Discount_Type,
/** 19 */
Invalid_Price,
/** 17 */
Invalid_Price_Level_Amount,
/** 34 */
Invalid_Price_Level_Currency,
/** 18 */
Invalid_Price_Level_Percentage,
/** 9 */
Invalid_Pricing_Code,
/** 30 */
Invalid_Pricing_Precision,
/** 7 */
Invalid_Product,
/** 29 */
Invalid_Quantity,
/** 24 */
Invalid_Rounding_Amount,
/** 23 */
Invalid_Rounding_Option,
/** 22 */
Invalid_Rounding_Policy,
/** 21 */
Invalid_Standard_Cost,
/** 15 */
Missing_Current_Cost,
/** 14 */
Missing_Price,
/** 2 */
Missing_Price_Level,
/** 12 */
Missing_Price_Level_Amount,
/** 13 */
Missing_Price_Level_Percentage,
/** 8 */
Missing_Pricing_Code,
/** 6 */
Missing_Product,
/** 31 */
Missing_Product_Default_UOM,
/** 32 */
Missing_Product_UOM_Schedule_,
/** 4 */
Missing_Quantity,
/** 16 */
Missing_Standard_Cost,
/** 5 */
Missing_Unit_Price,
/** 10 */
Missing_UOM,
/** 0 */
None,
/** 35 */
Price_Attribute_Out_Of_Range,
/** 25 */
Price_Calculation_Error,
/** 11 */
Product_Not_In_Price_Level,
/** 38 */
Transaction_currency_is_not_set_for_the_product_price_list_item
}
enum ProductTypeCode {
/** 2 */
Bundle,
/** 4 */
Optional_Bundle_Product,
/** 1 */
Product,
/** 5 */
Project_based_Service,
/** 3 */
Required_Bundle_Product
}
enum PropertyConfigurationStatus {
/** 0 */
Edit,
/** 2 */
Not_Configured,
/** 1 */
Rectify
}
enum SalesOrderStateCode {
}
enum ShipTo_FreightTermsCode {
/** 1 */
FOB,
/** 2 */
No_Charge
}
enum SkipPriceCalculation {
/** 0 */
DoPriceCalcAlways,
/** 1 */
SkipPriceCalcOnCreate,
/** 2 */
SkipPriceCalcOnUpdate,
/** 3 */
SkipPriceCalcOnUpSert
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Field Service Information','Information','Project Information','SalesOrderDetail'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
export interface CompilerMessageBase {
type: CompilerMessage["type"];
correlationId?: number;
}
/**
* Ask the compiler to compile a source file
*/
export interface CompileFileMessage extends CompilerMessageBase {
type: "CompileFile";
filename: string;
options?: CompilerOptions;
}
/**
* Ask the compiler to compile the specified source text
*/
export interface CompileSourceMessage extends CompilerMessageBase {
type: "Compile";
sourceText: string;
options?: CompilerOptions;
}
/**
* All compiler requests
*/
export type CompilerRequestMessage = CompileFileMessage | CompileSourceMessage;
/**
* Result of the assembler call
*/
export interface AssemblerOutputResponse extends CompilerMessageBase {
type: "CompileResult";
result: CompilerOutput;
}
/**
* All compiler responses
*/
export type CompilerResponseMessage = AssemblerOutputResponse;
/**
* Defines the messages the compiler accepts
*/
export type CompilerMessage = CompilerRequestMessage | CompilerResponseMessage;
// ----------------------------------------------------------------------------
// The compiler service and related DTO types
/**
* This interface defines the operations of the Z80 Compiler service
*/
export interface IZ80CompilerService {
/**
* Compiles the Z80 Assembly code in the specified file into Z80
* binary code.
* @param filename Z80 assembly source file (absolute path)
* @param options Compiler options. If not defined, the compiler uses the default options.
* @returns Output of the compilation
*/
compileFile(
filename: string,
options?: CompilerOptions
): Promise<CompilerOutput>;
/**
* Compiles the passed Z80 Assembly code into Z80 binary code.
* binary code.
* @param sourceText Z80 assembly source code text
* @param options Compiler options. If not defined, the compiler uses the default options.
* @returns Output of the compilation
*/
compile(
sourceText: string,
options?: CompilerOptions
): Promise<CompilerOutput>;
}
/**
* The type of the Spectrum model
*/
export enum SpectrumModelType {
Spectrum48,
Spectrum128,
SpectrumP3,
Next,
}
/**
* Represents the possible types of an expression value
*/
export enum ExpressionValueType {
Error = 0,
Bool,
Integer,
Real,
String,
NonEvaluated,
}
/**
* Represents the value of an evaluated expression
*/
export type ExpressionValue = {
/**
* Gets the type of the expression
*/
readonly type: ExpressionValueType;
/**
* Checks if the value of this expression is valid
*/
readonly isValid: boolean;
/**
* Checks if the value of this expression is not evaluated
*/
readonly isNonEvaluated: boolean;
/**
* Gets the value of this instance
*/
readonly value: number;
};
/**
* Represents the input options of the Klive Z80 Compiler
*/
export type CompilerOptions = {
/**
* Predefined compilation symbols
*/
predefinedSymbols: Record<string, ExpressionValue>;
/**
* The default start address of the compilation
*/
defaultStartAddress?: number;
/**
* The current ZX Spectrum model
*/
currentModel: SpectrumModelType;
/**
* The maximum number of errors to report within a loop
*/
maxLoopErrorsToReport: number;
/**
* Signs that PROC labels and symbols are not locals by default
*/
procExplicitLocalsOnly: boolean;
/**
* Indicates that assembly symbols should be case sensitively.
*/
useCaseSensitiveSymbols: boolean;
/**
* Allows flexible use of DEFx pragmas
*/
flexibleDefPragmas: boolean;
};
/**
* This enum defines the types of assembly symbols
*/
export enum SymbolType {
None,
Label,
Var,
}
export type AssemblySymbolInfo = {
/**
* Symbol name
*/
readonly name: string;
/**
* Symbol type
*/
readonly type: SymbolType;
/**
* Symbol value
*/
readonly value: ExpressionValue;
/**
* Tests if this symbol is a local symbol within a module.
*/
readonly isModuleLocal: boolean;
/**
* Tests if this symbol is a short-term symbol.
*/
readonly isShortTerm: boolean;
/**
* Signs if the object has been used
*/
readonly isUsed: boolean;
};
/**
* Defines a section of assembly lines
*/
export type DefinitionSection = {
readonly firstLine: number;
readonly lastLine: number;
};
/**
* Defines a field of a structure
*/
export type FieldDefinition = {
readonly offset: number;
readonly isUsed: boolean;
};
/**
* Represents a struct
*/
export type StructDefinition = {
readonly structName: string;
/**
* Struct definition section
*/
readonly section: DefinitionSection;
/**
* The fields of the structure
*/
readonly fields: Record<string, FieldDefinition>;
/**
* The size of the structure
*/
readonly size: number;
};
/**
* Represents the definition of a macro
*/
export type MacroDefinition = {
/**
* Name of the macro
*/
readonly macroName: string;
/**
* Macro identifier
*/
readonly argNames: IdentifierNode[];
/**
* End label of the macro
*/
readonly endLabel: string | null;
/**
* The section of the macro
*/
readonly section: DefinitionSection;
};
export type IdentifierNode = {
/**
* Identifies the node type as an identifier
*/
readonly type: "Identifier";
/**
* Identifier name
*/
readonly name: string;
/**
* The expression source code (used for macro argument replacement)
*/
readonly sourceText: string;
/**
* Start line number of the start token of the node
*/
readonly line: number;
/**
* Start position (inclusive) of the node
*/
readonly startPosition: number;
/**
* End position (exclusive)
*/
readonly endPosition: number;
/**
* Start column number (inclusive) of the node
*/
readonly startColumn: number;
/**
* End column number (exclusive) of the node
*/
readonly endColumn: number;
};
export type SymbolScope = {
/**
* Owner of this scope
*/
readonly ownerScope: SymbolScope | null;
/**
* Indicates that this scope is for a loop
*/
readonly isLoopScope: boolean;
/**
* Indicates that this scope is for a proc
*/
readonly isProcScope: boolean;
/**
* The current loop counter in the scope
*/
readonly loopCounter: number;
/**
* Indicates if this is a temporary scope
*/
readonly isTemporaryScope: boolean;
/**
* The symbol table with properly defined symbols
*/
readonly symbols: Record<string, AssemblySymbolInfo>;
/**
* Local symbol bookings
*/
readonly localSymbolBookings: Set<string>;
/**
* Indicates if a break statement has been reached in this scope
*/
readonly breakReached: boolean;
/**
* Indicates if a continue statement has been reached in this scope
*/
readonly continueReached: boolean;
/**
* Optional macro arguments
*/
macroArguments: Record<string, ExpressionValue> | null;
/**
* Tests if this context is a macro context
*/
readonly isMacroContext: boolean;
};
/**
* Represents the output of a compiled module
*/
export interface CompiledModule {
/**
* Parent of this module
*/
readonly parentModule: CompiledModule | null;
/**
* Case sensitive module?
*/
readonly caseSensitive: boolean;
/**
* Points to the root module
*/
readonly rootModule: CompiledModule;
/**
* Child modules
*/
readonly nestedModules: Record<string, CompiledModule>;
/**
* The symbol table with properly defined symbols
*/
readonly symbols: Record<string, AssemblySymbolInfo>;
/**
* The map of structures within the module
*/
readonly structs: Record<string, StructDefinition>;
/**
* The map of macro definitions within the module
*/
readonly macros: Record<string, MacroDefinition>;
/**
* Local symbol scopes
*/
readonly localScopes: SymbolScope[];
}
/**
* Describes a source file item
*/
export type SourceFileItem = {
/**
* The name of the source file
*/
readonly filename: string;
/**
* Optional parent item
*/
parent?: SourceFileItem;
/**
* Included files
*/
readonly includes: SourceFileItem[];
};
/**
* A single segment of the code compilation
*/
export type BinarySegment = {
/**
* The bank of the segment
*/
readonly bank?: number;
/**
* Start offset used for banks
*/
readonly bankOffset: number;
/**
* Maximum code length of this segment
*/
readonly maxCodeLength: number;
/**
* Start address of the compiled block
*/
readonly startAddress: number;
/**
* Optional displacement of this segment
*/
readonly displacement?: number;
/**
* The current assembly address when the .disp pragma was used
*/
readonly dispPragmaOffset?: number;
/**
* Intel hex start address of this segment
*/
readonly xorgValue?: number;
/**
* Emitted Z80 binary code
*/
readonly emittedCode: number[];
/**
* Signs if segment overflow has been detected
*/
readonly overflowDetected: boolean;
/**
* Shows the offset of the instruction being compiled
*/
readonly currentInstructionOffset?: number;
/**
* The current code generation offset
*/
readonly currentOffset: number;
};
/**
* Represents a compilation error
*/
export interface AssemblerErrorInfo {
/**
* Error code
*/
readonly errorCode: string;
/**
* File in which the error is found
*/
readonly fileName: string;
/**
* Error line number
*/
readonly line: number;
/**
* Error start position
*/
readonly startPosition: number;
/**
* Error end position
*/
readonly endPosition: number | null;
/**
* Complete error message
*/
readonly message: string;
/**
* Is it just warning?
*/
readonly isWarning?: boolean;
}
/**
* Represents a file line in the compiled assembler output
*/
export type FileLine = {
fileIndex: number;
line: number;
};
/**
* Represents an item in the output list
*/
export type ListFileItem = {
fileIndex: number;
address: number;
segmentIndex: number;
codeStartIndex: number;
codeLength: number;
lineNumber: number;
sourceText: string;
};
/**
* Represents the entire compiler output
*/
export interface CompilerOutput extends CompiledModule {
/**
* Source file item of the compiled code
*/
readonly sourceItem: SourceFileItem;
/**
* The segments of the compilation output
*/
readonly segments: BinarySegment[];
/**
* The errors found during the compilation
*/
readonly errors: AssemblerErrorInfo[];
/**
* Number of errors
*/
get errorCount(): number;
/**
* The type of Spectrum model to use
*/
modelType?: SpectrumModelType;
/**
* Entry address of the code
*/
entryAddress?: number;
/**
* Entry address of the code to use when exporting it
*/
exportEntryAddress?: number;
/**
* Inject options
*/
injectOptions: Record<string, boolean>;
/**
* The source files involved in this compilation, in
* their file index order
*/
readonly sourceFileList: SourceFileItem[];
/**
* Source map information that assigns source file info with
* the address
*/
readonly sourceMap: Record<number, FileLine>;
/**
* Source map information that assigns source file info with the address
*/
readonly addressMap: Map<FileLine, number[]>;
/**
* Items of the list file
*/
readonly listFileItems: ListFileItem[];
/**
* The type of the source that resulted in this compilation (for example, ZX BASIC)
*/
sourceType?: string;
/**
* Trace outputs
*/
readonly traceOutput: string[];
} | the_stack |
import {IApp} from '../../IApp';
import IDisplayContext = etch.drawing.IDisplayContext;
import Point = etch.primitives.Point;
import {SignalToValue} from '../../Core/Audio/Components/SignalToValue';
import {SoundCloudAudioType} from '../../Core/Audio/SoundCloud/SoundCloudAudioType';
import {SoundCloudAPI} from '../../Core/Audio/SoundCloud/SoundCloudAPI';
import {SoundCloudTrack} from '../../Core/Audio/SoundCloud/SoundcloudTrack';
import {Source} from '../Source';
declare var App: IApp;
export class Granular extends Source {
public Sources: Tone.Signal[];
public Grains: Tone.SimplePlayer[] = [];
public GrainEnvelopes: Tone.AmplitudeEnvelope[] = [];
public Timeout;
public EndTimeout;
private _FirstRelease: boolean = true;
private _CurrentGrain: number = 0;
private _IsLoaded: boolean;
public GrainsAmount: number;
private _NoteOn: boolean = false;
private _WaveForm: number[];
private _FirstBuffer: any;
private _LoadFromShare: boolean = false;
private _FallBackTrack: SoundCloudTrack;
public LoadTimeout: any;
private _tempPlaybackRate: number;
private _RampLength: number;
public ReleaseTimeout;
public Params: GranularParams;
public Defaults: GranularParams;
Init(drawTo: IDisplayContext): void {
this.BlockName = App.L10n.Blocks.Source.Blocks.Granular.name;
if (this.Params) {
this._LoadFromShare = true;
setTimeout(() => {
this.FirstSetup();
},100);
}
this.Defaults = {
playbackRate: 0,
detune: 0,
density: 10,
region: 0,
spread: 1.5,
grainlength: 0.25,
track: 'https://files.blokdust.io/samples/sequence_fuzz_pad2.wav',
trackName: 'Fuzz Pad 2',
user: 'BlokDust',
permalink: ''
};
this.PopulateParams();
this.GrainsAmount = 12;
this._RampLength = 0.4;
this._tempPlaybackRate = this.Params.playbackRate;
this._WaveForm = [];
this.SearchResults = [];
this.Searching = false;
this._FallBackTrack = new SoundCloudTrack(this.Params.trackName,this.Params.user,this.Params.track,this.Params.permalink);
super.Init(drawTo);
//this.Params.track = SoundCloudAudio.PickRandomTrack(SoundCloudAudioType.Granular);
this.CreateSource();
this.CreateEnvelope();
this.CreateGrains();
this.CreateFirstVoice();
this.PlaybackSignal = new SignalToValue();
// Define Outline for HitTest
this.Outline.push(new Point(-1, 0),new Point(0, -1),new Point(1, -1),new Point(2, 0),new Point(2, 1),new Point(1, 2));
}
Reset(){
this.Grains.length = 0;
this.GrainEnvelopes.length = 0;
}
Search(query: string) {
this.Searching = true;
App.MainScene.OptionsPanel.Animating = true; //TODO: make searching an event
this.ResultsPage = 1;
this.SearchResults = [];
SoundCloudAPI.MultiSearch(query, App.Config.GranularMaxTrackLength, this);
}
SetSearchResults(results) {
super.SetSearchResults(results);
this.Searching = false;
App.MainScene.OptionsPanel.Animating = false;
var len = results.length;
for (var i=0; i<len; i++) {
var track = results[i];
this.SearchResults.push(new SoundCloudTrack(track.title, track.user.username, track.uri, track.permalink_url));
}
}
LoadTrack(track,fullUrl?:boolean) { // TODO: make this a generic function with a function argument (to pass SetupGrains or SetupBuffers etc)
fullUrl = fullUrl || false;
if (fullUrl) {
this.Params.track = track.URI;
} else {
this.Params.track = SoundCloudAPI.LoadTrack(track);
}
this.Params.permalink = track.Permalink;
this.Params.trackName = track.TitleShort;
this.Params.user = track.UserShort;
this._WaveForm = [];
this.SetupGrains();
this.RefreshOptionsPanel("animate");
}
TrackFallBack() {
this._LoadFromShare = false;
// IF CURRENT FAILING TRACK MATCHES FALLBACK, SET FALLBACK TO DEFAULT (to end perpetual load loops) //
if (this.Params.track === this._FallBackTrack.URI) {
this._FallBackTrack = new SoundCloudTrack(this.Defaults.trackName,this.Defaults.user,this.Defaults.track,this.Defaults.permalink);
}
this.LoadTrack(this._FallBackTrack,true);
App.Message("Load Failed: This Track Is Unavailable. Reloading last track.");
}
CreateGrains() {
if (!this.Grains[0]) {
for (var i=0; i<this.GrainsAmount; i++) {
// CREATE PLAYER //
this.Grains[i] = new Tone.SimplePlayer();
// CREATE ENVELOPE //
this.GrainEnvelopes[i] = new Tone.AmplitudeEnvelope(
this.Params.grainlength * this._RampLength, // Attack
0.01, // Decay
1, // Sustain
this.Params.grainlength * this._RampLength // Release
);
// CONNECT //
this.Grains[i].connect(this.GrainEnvelopes[i]);
this.GrainEnvelopes[i].connect(this.Sources[0]);
if ((<any>Tone).isSafari){
(<any>this.Grains[i]).playbackRate = this.Params.playbackRate;
} else {
this.Grains[i].playbackRate.value = this.Params.playbackRate;
}
}
//this.Sources[0].connect(this.AudioInput);
this.Envelopes.forEach((e: Tone.AmplitudeEnvelope)=> {
e.connect(this.AudioInput);
});
this.Sources.forEach((s: Tone.Signal, i: number)=> {
s.connect(this.Envelopes[i]);
});
}
}
SetupGrains() {
// RESET //
this._IsLoaded = false;
var duration = this.GetDuration();
// LOAD FIRST BUFFER //
App.AnimationsLayer.AddToList(this); // load animations
if (this._FirstBuffer) { // cancel previous loads
this._FirstBuffer.dispose();
}
this._FirstBuffer = new Tone.SimplePlayer(this.Params.track, (e) => {
clearTimeout(this.LoadTimeout);
this._WaveForm = App.Audio.Waveform.GetWaveformFromBuffer(e.buffer._buffer,200,2,80);
App.AnimationsLayer.RemoveFromList(this);
this._IsLoaded = true;
// COPY BUFFER TO GRAINS //
for (var i=0; i<this.GrainsAmount; i++) {
this.Grains[i].buffer = e.buffer;
}
var duration = this.GetDuration();
if (!this._LoadFromShare) {
this.Params.region = duration / 2;
}
this._LoadFromShare = false;
this._FallBackTrack = new SoundCloudTrack(this.Params.trackName,this.Params.user,this.Params.track,this.Params.permalink);
// UPDATE OPTIONS FORM //
this.RefreshOptionsPanel();
// start if powered //
this.GrainLoop();
});
var me = this;
clearTimeout(this.LoadTimeout);
this.LoadTimeout = setTimeout( function() {
me.TrackFallBack();
},(App.Config.SoundCloudLoadTimeout*1000));
//TODO - onerror doesn't seem to work
this._FirstBuffer.onerror = function() {
me.TrackFallBack();
};
}
FirstSetup() {
if (this._FirstRelease) {
this.Sources.forEach((s: Tone.Signal, i: number) => {
s.connect(this.Envelopes[i]);
});
this.Envelopes.forEach((e: Tone.AmplitudeEnvelope)=> {
e.connect(this.AudioInput);
});
//this.Search(App.MainScene.SoundcloudPanel.RandomSearch(this));
this.SetupGrains();
this._FirstRelease = false;
}
}
GetDuration(): number {
if (this._FirstBuffer){
return this._FirstBuffer.buffer.duration;
} else {
return 0;
}
}
Update() {
super.Update();
if (this.PlaybackSignal) {
var value = this.PlaybackSignal.UpdateValue();
if (value!==0) {
this.Params.detune = value;
this.NoteUpdate();
} else {
this.Params.detune = 0;
}
}
}
Draw() {
super.Draw();
this.DrawSprite(this.BlockName);
}
CreateSource(){
this.Sources.push( new Tone.Signal() );
// return it
//TODO these extra sources need setting up somehow
return super.CreateSource();
}
CreateEnvelope(){
this.Envelopes.push( new Tone.AmplitudeEnvelope(
this.Settings.envelope.attack,
this.Settings.envelope.decay,
this.Settings.envelope.sustain,
this.Settings.envelope.release
) );
return super.CreateEnvelope();
}
TriggerAttack(index) {
super.TriggerAttack(index);
if (this._IsLoaded) {
//this._NoteOn = true;
/*this._Envelopes.forEach((e: Tone.AmplitudeEnvelope)=> {
e.triggerAttack();
});*/
//clearTimeout(this.EndTimeout);
if (!this._NoteOn) {
this._NoteOn = true;
this.GrainLoop();
}
}
}
TriggerRelease(index) {
super.TriggerRelease(index);
/*this._Envelopes.forEach((e: Tone.AmplitudeEnvelope)=> {
e.triggerRelease();
});*/
//clearTimeout(this.EndTimeout);
var that = this;
this.EndTimeout = setTimeout(() => {
if (that.ActiveVoices.length===0) {
that._NoteOn = false;
}
}, <number>this.Envelopes[0].release*1000);
}
TriggerAttackRelease(index: number|string = 0, duration: Tone.Time = App.Config.PulseLength){
if (this._IsLoaded) {
clearTimeout(this.EndTimeout);
if (!this._NoteOn) {
this._NoteOn = true;
this.GrainLoop();
}
}
this.ReleaseTimeout = setTimeout(() => {
this.EndTimeout = setTimeout(() => {
this._NoteOn = false;
}, <number>this.GrainEnvelopes[0].release*1000);
}, duration);
}
MouseUp() {
this.FirstSetup();
super.MouseUp();
}
GrainLoop() {
// CYCLES THROUGH GRAINS AND PLAYS THEM //
if (this.GrainEnvelopes[this._CurrentGrain] && (this.IsPowered() || this._NoteOn)) {
var location = this.LocationRange(
this.Params.region - (this.Params.spread * 0.5) + (Math.random() * this.Params.spread)
);
// MAKE SURE THESE ARE IN SYNC //
// this.GrainEnvelopes[this._CurrentGrain].triggerAttackRelease(this.Params.grainlength * (1 - this._RampLength));
// const time = this.Params.grainlength * (1 - this._RampLength);
// let now = this.GrainEnvelopes[0].context.currentTime;
// console.log('trigger attack', now);
// this.GrainEnvelopes[this._CurrentGrain].triggerAttack();
// console.log('trigger release', now + time);
// this.GrainEnvelopes[this._CurrentGrain].triggerRelease(time + now);
//this.GrainEnvelopes[this._CurrentGrain].triggerRelease();
this.Grains[this._CurrentGrain].stop();
//this.Grains[this._CurrentGrain].playbackRate.value = this._tempPlaybackRate;
if (this.GetDuration()>0) {
this.Grains[this._CurrentGrain].start(location, (this.Params.grainlength*this._tempPlaybackRate)*1.9);
//this.GrainEnvelopes[this._CurrentGrain].triggerAttackRelease((this.Params.grainlength * (1 - this._RampLength))*1000);
var grain = this.GrainEnvelopes[this._CurrentGrain];
this.GrainEnvelopes[this._CurrentGrain].triggerAttack();
setTimeout(() => {
grain.triggerRelease();
}, Math.round((this.Params.grainlength * (1 - this._RampLength))*1000));
}
clearTimeout(this.Timeout);
this.Timeout = setTimeout(() => {
this.GrainLoop();
}, Math.round(((this.Params.grainlength*2) / this.Params.density)*1500));
this._CurrentGrain += 1;
if (this._CurrentGrain >= this.Params.density) {
this._CurrentGrain = 0;
}
}
}
// CAP POSITIONS OF GRAINS TO STAY WITHIN TRACK LENGTH //
LocationRange(location: number) {
var locationCap = this.GetDuration() - this.Params.grainlength;
if (location < 0) {
location = 0;
} else if (location > locationCap) {
location = locationCap;
}
return location;
}
SetPitch(note: number, voiceNo?: number, glide?: Tone.Time) {
super.SetPitch(note,voiceNo,glide);
this._tempPlaybackRate = this.MidiToPlayback(note);
}
SetParam(param: string,value: number) {
super.SetParam(param,value);
switch (param){
case "density": this.Params.density = value;
break;
case "grainlength":
this.Params.grainlength = value;
for (var i=0; i< this.GrainsAmount; i++) {
this.GrainEnvelopes[i].attack = value * this._RampLength;
this.GrainEnvelopes[i].release = value * this._RampLength;
}
break;
case "spread": this.Params.spread = value;
break;
case "region": this.Params.region = value;
break;
}
}
UpdateOptionsForm() {
super.UpdateOptionsForm();
this.OptionsForm =
{
"name" : "Granular",
"parameters" : [
{
"type" : "waveslider",
"name" : "Location",
"setting" :"region",
"props" : {
"value" : this.Params.region,
"min" : 0,
"max" : this.GetDuration(),
"quantised" : false,
"centered" : false,
"wavearray" : this._WaveForm,
"spread" : this.Params.spread
}
},
{
"type" : "sample",
"name" : "Sample",
"setting" :"sample",
"props" : {
"track" : this.Params.trackName,
"user" : this.Params.user,
"permalink" : this.Params.permalink
}
},
{
"type" : "slider",
"name" : "Spread",
"setting" :"spread",
"props" : {
"value" : this.Params.spread,
"min" : 0,
"max" : 4,
"quantised" : false,
"centered" : false
}
},
{
"type" : "slider",
"name" : "Grain Size",
"setting" :"grainlength",
"props" : {
"value" : this.Params.grainlength,
"min" : 0.03,
"max" : 0.6,
"quantised" : false,
"centered" : false
}
},
{
"type" : "slider",
"name" : "Density",
"setting" :"density",
"props" : {
"value" : this.Params.density,
"min" : 2,
"max" : this.GrainsAmount,
"quantised" : true,
"centered" : false
}
}
]
};
}
Dispose(){
super.Dispose();
clearTimeout(this.Timeout);
this._NoteOn = false;
this.Grains.forEach((g: Tone.SimplePlayer)=> {
g.dispose();
});
this.GrainEnvelopes.forEach((e: Tone.AmplitudeEnvelope)=> {
e.dispose();
});
this.Envelopes.forEach((e: Tone.AmplitudeEnvelope)=> {
e.dispose();
});
this.Sources.forEach((s: Tone.Signal)=> {
s.dispose();
});
this.Grains.length = 0;
this.GrainEnvelopes.length = 0;
}
} | the_stack |
import { Injectable } from '@angular/core';
import { AbstractControl, FormArray, FormGroup } from '@angular/forms';
import { FormlyConfig, FormlyFieldConfig } from '@ngx-formly/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { FieldsService } from './fields.service';
import { DesignerTypeOption, DESIGNER_WRAPPER_TYPES, FormlyDesignerConfig } from './formly-designer-config';
import { cloneDeep, get, isArray, isEmpty, isFunction, isString, set, unset } from './util';
export enum FieldType {
Plain,
Designer,
}
@Injectable()
export class FormlyDesignerService {
constructor(
private designerConfig: FormlyDesignerConfig,
private fieldsService: FieldsService,
private formlyConfig: FormlyConfig,
) { }
private readonly _disabled = new BehaviorSubject<boolean>(false);
private readonly _designerFields = new BehaviorSubject<FormlyFieldConfig[]>([]);
private readonly _fields = new BehaviorSubject<FormlyFieldConfig[]>([]);
private readonly _selectedField = new BehaviorSubject<FormlyFieldConfig | null>(null);
private readonly _model = new BehaviorSubject<any>({});
get disabled(): boolean {
return this._disabled.value;
}
set disabled(value: boolean) {
this._disabled.next(!!value);
}
get disabled$(): Observable<boolean> {
return this._disabled.asObservable();
}
get selectedField$(): Observable<FormlyFieldConfig | null> {
return this._selectedField.asObservable();
}
get selectedDesignerId(): string {
return this._selectedField.getValue()?.templateOptions?.$designerId;
}
get designerFields(): FormlyFieldConfig[] {
return this._designerFields.value;
}
set designerFields(value: FormlyFieldConfig[]) {
// Prune the fields because ngx-formly pollutes them with internal state
// causing incorrect behavior when re-applied.
const fields = isArray(value) ? cloneDeep(value) : [];
const designerFields = this.createPrunedFields(fields, FieldType.Designer);
this._designerFields.next(designerFields);
this._fields.next(this.createPrunedFields(cloneDeep(designerFields), FieldType.Plain));
}
get designerFields$(): Observable<FormlyFieldConfig[]> {
return this._designerFields.asObservable();
}
get fields(): FormlyFieldConfig[] {
return this._fields.value;
}
set fields(value: FormlyFieldConfig[]) {
// Prune the fields because ngx-formly pollutes them with internal state
// causing incorrect behavior when re-applied.
const fields = cloneDeep(value);
const designerFields = this.createPrunedFields(fields, FieldType.Designer);
this.fieldsService.mutateFields(designerFields, false);
this._selectedField.next(null);
this._designerFields.next(designerFields);
this._fields.next(this.createPrunedFields(cloneDeep(designerFields), FieldType.Plain));
}
get fields$(): Observable<FormlyFieldConfig[]> {
return this._fields.asObservable();
}
get model(): unknown {
return this._model.value;
}
set model(value: unknown) {
this._model.next(value == null ? {} : value);
}
get model$(): Observable<unknown> {
return this._model.asObservable();
}
addField(field: FormlyFieldConfig, index?: number): void {
this.fieldsService.mutateField(field, false);
const fields = cloneDeep(this.designerFields);
const fieldIndex = (index == null || isNaN(index)) ? this.fields.length :
Math.min(this.fields.length, Math.max(0, index));
fields.splice(fieldIndex, 0, field);
this.updateFields(fields);
}
createField(type: string): FormlyFieldConfig {
const field = {} as FormlyFieldConfig;
if (type !== 'formly-group') {
field.type = type;
}
const designerType = this.designerConfig.types[type];
if (designerType?.fieldArray) {
field.fieldArray = { fieldGroup: [] };
}
if (type === 'formly-group' || designerType?.fieldGroup) {
field.fieldGroup = [];
}
return field;
}
didClickField(value: FormlyFieldConfig): void {
this._selectedField.next(value);
}
removeField(field: FormlyFieldConfig): void {
this.unsetField(field);
const designerId = field.templateOptions?.$designerId;
if (this.replaceField(designerId, null, this.designerFields)) {
this.removeControl(field.formControl);
}
this.updateFields();
}
updateField(original: FormlyFieldConfig | null, modified: FormlyFieldConfig): void {
const pruned = this.fieldsService.mutateField(this.createPrunedField(modified), false);
const designerId = original?.templateOptions?.$designerId;
if (this.replaceField(designerId, pruned, this.designerFields)) {
if (original && original.formControl !== pruned.formControl) {
this.unsetField(original);
this.removeControl(original.formControl);
}
this.updateFields();
}
}
getWrappers(field: FormlyFieldConfig): string[] {
if (!field || !isArray(field.wrappers)) {
return [];
}
const clonedField = cloneDeep(field);
let wrappers = clonedField.wrappers = (clonedField.wrappers || []);
const filterWrapper = this.designerConfig.settings.filterWrapper ?? ((wrapper, _) => wrapper !== 'form-field');
if (filterWrapper && isFunction(filterWrapper)) {
wrappers = wrappers.filter(w => filterWrapper(w, clonedField));
}
// Determine wrappers part of the formly configuration (static and dynamic) to exclude them from the result
const staticWrappers = (field.type && this.formlyConfig.getType(field.type).wrappers) || [];
const typeWrappers = staticWrappers
.concat(this.formlyConfig.templateManipulators.preWrapper.map(m => m(clonedField)))
.concat(this.formlyConfig.templateManipulators.postWrapper.map(m => m(clonedField)))
.concat(DESIGNER_WRAPPER_TYPES);
// Remove wrappers part of the formly configuration from the result
if (typeWrappers.length > 0) {
for (let i = wrappers.length - 1; i >= 0; i--) {
for (let j = typeWrappers.length - 1; j >= 0; j--) {
if (wrappers[i] === typeWrappers[j]) {
typeWrappers.splice(j, 1);
wrappers.splice(i, 1);
break;
}
}
}
}
return wrappers;
}
/** Prunes field of unrecognized properties */
createPrunedField(field: FormlyFieldConfig, fieldType = FieldType.Designer): FormlyFieldConfig {
const designerType = this.getDesignerType(field);
const pruned: FormlyFieldConfig = isEmpty(field.key) ? {} : { key: field.key };
if (designerType) {
pruned.type = designerType.name;
if (fieldType === FieldType.Designer && field.templateOptions?.$designerId) {
pruned.templateOptions = { $designerId: field.templateOptions.$designerId };
}
this.applyProperties(field, pruned, designerType.fields);
if (designerType.fieldArray) {
pruned.fieldArray = {
fieldGroup: this.createPrunedFields(field.fieldGroup, fieldType)
};
}
}
if (isArray(field.fieldGroup) && !isArray(pruned.fieldArray)) {
pruned.fieldGroup = this.createPrunedFields(field.fieldGroup, fieldType);
let fieldGroupClassName: string;
if (isString(field.fieldGroupClassName) &&
(fieldGroupClassName = (field.fieldGroupClassName as string).trim()).length > 0) {
pruned.fieldGroupClassName = fieldGroupClassName;
}
}
let className: string;
if (isString(field.className) && (className = (field.className as string).trim()).length > 0) {
pruned.className = className;
}
const wrappers = this.getWrappers(field);
if (wrappers.length > 0) {
pruned.wrappers = wrappers;
const designerWrapperFields = wrappers.map(wrapper => this.designerConfig.wrappers[wrapper])
.filter(designerOption => designerOption && isArray(designerOption.fields))
.reduce<FormlyFieldConfig[]>((previous, current) => previous.concat(current.fields || []), []);
this.applyProperties(field, pruned, designerWrapperFields);
}
return pruned;
}
/** Prunes fields of unrecognized properties */
createPrunedFields(fields: FormlyFieldConfig[] | undefined, fieldType = FieldType.Designer): FormlyFieldConfig[] {
const prunedFields: FormlyFieldConfig[] = [];
if (isArray(fields)) {
fields.forEach(field => {
const pruned = this.createPrunedField(field, fieldType);
if (field.fieldArray) {
pruned.fieldArray = this.createPrunedField(field.fieldArray, fieldType);
} else if (field.fieldGroup && !pruned.fieldArray) {
pruned.fieldGroup = this.createPrunedFields(field.fieldGroup, fieldType);
}
if (Object.keys(pruned).length > 0) {
prunedFields.push(pruned);
}
});
}
return prunedFields;
}
getTypeName(type: string | null | undefined): string {
if (type === 'formly-group') {
return 'fieldGroup';
}
return type ?? '';
}
private applyProperties(field: FormlyFieldConfig, designed: FormlyFieldConfig, designerFields: FormlyFieldConfig[] | undefined): void {
if (isArray(designerFields)) {
designerFields.forEach(designerField => {
const key = designerField.key;
if (key == null) {
return;
}
const value = get(field, key);
if (value != null && (!isString(value) || value.length > 0) && value !== designerField.defaultValue) {
set(designed, key, value);
}
});
}
}
private getDesignerType(field: FormlyFieldConfig): DesignerTypeOption | undefined {
const type = field?.templateOptions?.$fieldArray?.type ?? field.type;
const designerType = this.designerConfig.types[type];
if (designerType) {
return designerType;
}
if (field.type === 'formly-group' || (!field.type && isArray(field.fieldGroup))) {
return { name: field.type as string, fieldGroup: true, fields: [] };
}
return;
}
private replaceField(id: string, field: FormlyFieldConfig | null, fields: FormlyFieldConfig[]): boolean {
if (!id || !isArray(fields)) {
return false;
}
for (let i = 0, l = fields.length; i < l; i++) {
const otherField = fields[i];
if (otherField.templateOptions?.$designerId === id) {
if (field == null) {
fields.splice(i, 1);
} else {
fields[i] = field;
}
return true;
}
if (otherField.fieldGroup && this.replaceField(id, field, otherField.fieldGroup)) {
return true;
}
if (otherField.fieldArray && this.replaceFieldArray(id, field, otherField)) {
return true;
}
}
return false;
}
private replaceFieldArray(id: string | null, field: FormlyFieldConfig | null, parent: FormlyFieldConfig): boolean {
if (!id) {
return false;
}
const fieldArray = parent.fieldArray;
if (!fieldArray) {
return false;
}
if (fieldArray.templateOptions?.$designerId === id) {
if (field) {
parent.fieldArray = field;
return true;
}
return false;
}
if (fieldArray.fieldGroup && this.replaceField(id, field, fieldArray.fieldGroup)) {
return true;
}
return fieldArray.fieldArray != null && this.replaceFieldArray(id, field, fieldArray);
}
private buildPath(key: string, path: string, arrayNext: boolean = false) {
return path ? key + (arrayNext ? path : '.' + path) : key;
}
private path(control: AbstractControl, includeSelf: boolean = true): string {
let path = '';
let arrayNext = false;
let root = includeSelf ? control : control?.parent;
for (let child = root, parent = root?.parent; !!parent; child = parent, parent = parent.parent) {
if (parent instanceof FormGroup) {
for (const key in parent.controls) {
if (parent.controls[key] === child) {
path = this.buildPath(key, path, arrayNext);
arrayNext = false;
break;
}
}
} else if (parent instanceof FormArray) {
for (let i = 0; i < parent.length; i++) {
if (parent.at(i) === child) {
path = this.buildPath('[' + i + ']', path, arrayNext);
arrayNext = true;
break;
}
}
}
}
return path;
}
private unsetField(field: FormlyFieldConfig): void {
if (field.fieldArray) {
this.unsetField(field.fieldArray);
}
if (field.fieldGroup) {
field.fieldGroup.forEach(f => this.unsetField(f));
}
if (field.formControl) {
const path = this.path(field.formControl);
unset(this.model, path);
}
}
private removeControl(control: AbstractControl | undefined): void {
const parent = control?.parent;
if (parent instanceof FormGroup) {
for (const key in parent.controls) {
if (parent.controls[key] === control) {
parent.removeControl(key);
return;
}
}
} else if (parent instanceof FormArray) {
for (let i = 0; i < parent.length; i++) {
if (parent.at(i) === control) {
parent.removeAt(i);
return;
}
}
}
}
private updateFields(fields?: FormlyFieldConfig[], model?: any): void {
this.designerFields = fields ?? cloneDeep(this.designerFields);
// Update the selected field to use the updated instance, if any
this._selectedField.next(this.fieldsService.find(this.selectedDesignerId, this.designerFields) ?? null);
this.model = model ?? cloneDeep(this.model);
}
} | the_stack |
import { Client, TableQualifier } from "beneath";
import { sortedUniqBy } from "lodash";
import { useEffect, useState } from "react";
import { FetchMoreFunction, FetchMoreOptions } from "./shared";
const DEFAULT_PAGE_SIZE = 25;
const DEFAULT_FLASH_DURATION = 2000;
const DEFAULT_RENDER_FREQUENCY = 250;
const DEFAULT_SUBSCRIBE_POLL_FREQUENCY = 250;
/**
* Options passed to {@linkcode useRecords}
*/
export interface UseRecordsOptions {
/** Secret to use for authentication */
secret?: string;
/** Identifier for the table or instance to query */
table: TableQualifier;
/** Query to run. Defaults to an unfiltered index query. */
query?: { type: "index", filter?: string } | { type: "log", peek?: boolean };
/** Number of records to fetch per request (limit). Defaults to 25. */
pageSize?: number;
/** If configured, will open a websocket and trigger a re-render when new records are received. */
subscribe?: boolean | { pageSize?: number, pollFrequencyMs?: number };
/** If set, will truncate results to `maxRecords` by removing records */
truncatePolicy?: "start" | "end" | "auto";
/** Max number of records to keep in memory before applying `truncatePolicy` */
maxRecords?: number;
/** If subscribed to websockets, sets the duration that each new record will have `record["@meta"].flash === true` */
flashDurationMs?: number;
/** If subscribed to websockets, sets the max frequency at which re-renders are triggered (to prevent lagging) */
renderFrequencyMs?: number;
}
export interface UseRecordsResult<TRecord> {
/** Client used to connect (see the non-react beneath library) */
client?: Client;
/** Records returned by query. If subscribed to websockets, may change on re-renders */
records: Record<TRecord>[];
/** Error returned by the query */
error?: Error;
/** Callback to trigger fetching another page */
fetchMore?: FetchMoreFunction;
/** Callback to trigger fetching changes (not applicable if subscribed to websockets) */
fetchMoreChanges?: FetchMoreFunction;
/** True if currently loading for the first time (not if subscribed to websockets) */
loading: boolean;
/** Status on the websockets subscription */
subscription: {
/** True if a websocket connection is open */
online: boolean;
/** Error returned from the websocket connection */
error?: Error;
};
/** Status on whether records have been truncated under the truncation policy */
truncation: {
/** True if records were truncated from the start */
start: boolean;
/** True if records were truncated from the start */
end: boolean;
};
}
// like beneath.Record, but with @meta.flash added
export type Record<TRecord = any> = TRecord & {
"@meta": {
key: string;
timestamp: number;
flash?: boolean;
_key?: Buffer;
_flashTime?: number;
};
};
/**
* React hook that you can use to query tables, including paging through data
* and getting real-time updates over websockets.
* @param opts Options, including required parameters. See {@linkcode UseRecordsOptions} for details.
*/
export function useRecords<TRecord = any>(opts: UseRecordsOptions): UseRecordsResult<TRecord> {
// values
const [client, setClient] = useState<Client>(() => new Client({ secret: opts.secret }));
const [data, setData] = useState<{ records: Record<TRecord>[] }>({ records: [] });
const [error, setError] = useState<Error | undefined>(undefined);
const [fetchMore, setFetchMore] = useState<FetchMoreFunction | undefined>(undefined);
const [fetchMoreChanges, setFetchMoreChanges] = useState<FetchMoreFunction | undefined>(undefined);
// flags
const [loading, setLoading] = useState<boolean>(true);
const [truncatedStart, setTruncatedStart] = useState<boolean>(false);
const [truncatedEnd, setTruncatedEnd] = useState<boolean>(false);
const [subscriptionOnline, setSubscriptionOnline] = useState<boolean>(false);
const [subscriptionError, setSubscriptionError] = useState<Error | undefined>(undefined);
// // fetch (and maybe subscribe to) records (will get called every time opts change)
useEffect(() => {
// Section: PARSING OPTIONS
const queryType = opts.query?.type || "index";
const queryPeek = opts.query?.type === "log" ? opts.query.peek || false : undefined;
const queryFilter = opts.query?.type === "index" ? opts.query.filter : undefined;
const pageSize = opts.pageSize || DEFAULT_PAGE_SIZE;
const maxRecords = opts.maxRecords;
const truncatePolicy = opts.truncatePolicy || "auto";
const flashDuration = opts.flashDurationMs === undefined ? DEFAULT_FLASH_DURATION : opts.flashDurationMs;
const renderFrequency = opts.renderFrequencyMs || DEFAULT_RENDER_FREQUENCY;
const subscribeEnabled = typeof window === "undefined" ? false : !!opts.subscribe;
const subscribeOpts = (typeof opts.subscribe === "object") ? opts.subscribe : {};
const subscribePageSize = subscribeOpts.pageSize || pageSize;
const subscribePollFrequency = subscribeOpts.pollFrequencyMs || DEFAULT_SUBSCRIBE_POLL_FREQUENCY;
if (!maxRecords && opts.truncatePolicy) {
throw Error("useRecords cannot apply a truncate policy when maxRecords is not specified");
}
// SECTION: State stored outside async scope
// cancellation mechanism for async/await (dirty, but it works)
// tslint:disable-next-line: max-line-length
// see: https://dev.to/n1ru4l/homebrew-react-hooks-useasynceffect-or-how-to-handle-async-operations-with-useeffect-1fa8
let cancel = false;
let loadedMore = false;
let subscriptionUnsubscribe: (() => any) | undefined;
// async scope
(async () => {
// Section: INITIAL LOAD
// get table object
const table = client.findTable(opts.table);
// query table
const query =
queryType === "index"
? await table.queryIndex({ filter: queryFilter, pageSize })
: queryType === "log"
? await table.queryLog({ pageSize, peek: queryPeek })
: undefined;
if (!query) {
throw Error(`invalid view option <${queryType}>`);
}
if (cancel) { return; } // check cancel after await
// parse query
if (query.error) {
setError(query.error);
setLoading(false);
return;
}
const cursor = query.cursor;
if (!cursor) {
throw Error("internal error: expected cursor");
}
// fetch first page and set
if (cursor.hasNext()) {
const read = await cursor.readNext({ pageSize });
if (cancel) { return; } // check cancel after await
if (read.error) {
setError(read.error);
setLoading(false);
return;
}
setData({ records: read.data || [] });
}
// done loading
setLoading(false);
// Section: BUFFERED RENDERING LOGIC
let lastRender = 0;
let renderScheduled = false;
let deflashScheduled = false;
let moreBuffer: Record<TRecord>[] = [];
let changesBuffer: Record<TRecord>[] = [];
const deflash = (records: Record<TRecord>[]) => {
const cutoff = Date.now() - flashDuration;
for (const record of records) {
if (record["@meta"]._flashTime && record["@meta"]._flashTime <= cutoff) {
delete record["@meta"].flash;
delete record["@meta"]._flashTime;
}
}
return records;
};
const render = () => {
if (cancel) { return; }
// update records
let data: undefined | { records: Record<TRecord>[] };
setData((currentData) => {
data = currentData;
return currentData;
});
// NOTE: This manoeuvre to get a fresh copy of data is horrible! It only works because there's
// no async code before the next call to setData. Why not just put the whole block below in the
// setData callback above? Because the setXXX calls in the code somehow triggered a nested rerun
// of the setData callback precisely on the 20th run. This is such a weird bug, and this horrible
// hack (seemingly) solves it.
if (!data) {
throw Error("unexpected internal error!");
}
let result = data.records;
if (deflashScheduled) {
result = deflash(result);
}
if (moreBuffer.length > 0) {
result.push(...moreBuffer);
}
if (changesBuffer.length > 0) {
if (queryType === "index") {
result = mergeIndexedRecordsAndChanges(result, changesBuffer, false, cursor.hasNext());
} else if (queryType === "log") {
if (queryPeek) {
result.unshift(...changesBuffer.reverse());
} else {
result.push(...changesBuffer);
}
}
}
if (maxRecords && result.length > maxRecords) {
if (truncatePolicy === "start") {
result = result.slice(result.length - maxRecords);
setTruncatedStart(true);
} else if (truncatePolicy === "end") {
result = result.slice(0, maxRecords);
setTruncatedEnd(true);
} else if (truncatePolicy === "auto") {
if (queryType === "log" && !queryPeek) {
// truncate start
result = result.slice(result.length - maxRecords);
setTruncatedStart(true);
} else {
if (loadedMore) {
// truncate start
result = result.slice(result.length - maxRecords);
setTruncatedStart(true);
// disable subscription (since the user is likely paging anyway)
if (subscriptionUnsubscribe) {
subscriptionUnsubscribe();
}
setSubscriptionError(Error("Real-time updates were disabled since too many rows have been loaded (refresh page to reset)"));
setSubscriptionOnline(false);
} else {
// truncate end
result = result.slice(0, maxRecords);
setTruncatedEnd(true);
// disable fetching more (since ends wouldn't match)
setFetchMore(undefined);
}
}
}
}
setData({ records: result });
lastRender = Date.now();
renderScheduled = false;
deflashScheduled = false;
moreBuffer = [];
changesBuffer = [];
};
const scheduleRender = (deflash: boolean) => {
if (deflash) {
deflashScheduled = true;
}
if (!renderScheduled) {
renderScheduled = true;
const delta = Math.max(0, Date.now() - lastRender);
const wait = renderFrequency - delta;
if (wait > 0) {
setTimeout(render, wait);
} else {
render();
}
}
};
const handleFlash = (data: Record<TRecord>[], flash: boolean) => {
flash = flash && flashDuration !== 0;
if (flash) {
const now = Date.now();
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < data.length; i++) {
const record = data[i] as Record<TRecord>;
record["@meta"].flash = true;
record["@meta"]._flashTime = now;
}
// schedule deflash
setTimeout(() => {
if (cancel) { return; }
scheduleRender(true);
}, flashDuration);
}
};
const handleChangeData = (data: Record<TRecord>[], flash: boolean) => {
handleFlash(data, flash);
changesBuffer = changesBuffer.concat(data);
scheduleRender(false);
};
const handleMoreData = (data: Record<TRecord>[], flash: boolean) => {
handleFlash(data, flash);
moreBuffer = moreBuffer.concat(data);
scheduleRender(false);
};
// SECTION: Fetching more
// set fetch more
if (cursor.hasNext()) {
const fetchMore = async (fetchMoreOpts?: FetchMoreOptions) => {
// stop if cancelled
if (cancel) { return; }
// normalize fetchMoreOpts
const fetchMorePageSize = fetchMoreOpts?.pageSize || pageSize;
// set loading
setLoading(true);
// update flag used for 'auto' truncate policy
loadedMore = true;
// fetch more
const read = await cursor.readNext({ pageSize: fetchMorePageSize });
if (cancel) { return; } // check cancel after await
if (read.error) {
setError(read.error);
setLoading(false);
return;
}
// append to records
handleMoreData(read.data || [], true);
// update fetch more
if (!cursor.hasNext()) {
setFetchMore(undefined);
}
// done loading
setLoading(false);
return;
};
setFetchMore(() => fetchMore);
}
// SECTION: Changes
if (cursor.hasNextChanges() && !queryFilter) {
if (subscribeEnabled && !(queryType === "log" && !queryPeek && cursor.hasNext())) {
// create subscription
const { unsubscribe } = cursor.subscribeChanges({
pageSize: subscribePageSize,
pollAtMostEveryMilliseconds: subscribePollFrequency,
onData: (data) => {
handleChangeData(data, true);
},
onComplete: (error) => {
if (cancel) { return; }
setSubscriptionOnline(false);
setSubscriptionError(error);
},
});
subscriptionUnsubscribe = unsubscribe;
setSubscriptionOnline(true);
} else {
// create manual fetch changes handler
const fetchMoreChanges = async (fetchMoreOpts?: FetchMoreOptions) => {
// stop if cancelled
if (cancel) { return; }
// normalize fetchMoreOpts
const fetchMorePageSize = fetchMoreOpts?.pageSize || pageSize;
// set loading
setLoading(true);
// fetch more
const read = await cursor.readNextChanges({ pageSize: fetchMorePageSize });
if (cancel) { return; } // check cancel after await
if (read.error) {
setError(read.error);
setLoading(false);
return;
}
// append to records
handleChangeData(read.data || [], true);
// update fetch more
if (!cursor.hasNextChanges()) {
setFetchMoreChanges(undefined);
}
// done loading
setLoading(false);
return;
};
setFetchMoreChanges(() => fetchMoreChanges);
}
}
// done with effect
})();
return function cleanup() {
// cancel async/await
cancel = true;
// stop subscription if open
if (subscriptionUnsubscribe) {
subscriptionUnsubscribe();
}
// reset state (cleanup is also called when reacting to opts changes), so complete dealloc is not guaranteed
setSubscriptionError(undefined);
setSubscriptionOnline(false);
setTruncatedEnd(false);
setTruncatedStart(false);
setLoading(true);
setFetchMoreChanges(undefined);
setFetchMore(undefined);
setError(undefined);
setData({ records: [] });
// cleanup subscription
};
}, [
opts.secret,
(typeof opts.table === "string") ? opts.table : ("instanceID" in opts.table) ? opts.table.instanceID : `${opts.table.organization}/${opts.table.project}/${opts.table.table}`,
opts.query?.type,
opts.query?.type === "log" ? opts.query.peek : opts.query?.type === "index" ? opts.query.filter : undefined,
opts.pageSize,
!!opts.subscribe,
]);
// UseRecordsResult
return {
client,
records: data.records,
error,
loading,
fetchMore,
fetchMoreChanges,
subscription: {
online: subscriptionOnline,
error: subscriptionError,
},
truncation: {
start: truncatedStart,
end: truncatedEnd,
},
};
}
function mergeIndexedRecordsAndChanges<TRecord>(
records: Record<TRecord>[],
changes: Record<TRecord>[],
skipStart: boolean,
skipEnd: boolean,
): Record<TRecord>[] {
// sort changes a) lexicographically by _key, b) equal keys sorted descending by timestamp
changes.sort((a, b) => {
const ak = getBufferKey(a);
const bk = getBufferKey(b);
const c = ak.compare(bk);
if (c === 0) {
const at = a["@meta"].timestamp;
const bt = b["@meta"].timestamp;
if (at < bt) {
return 1;
} else if (at > bt) {
return -1;
} else {
return 0;
}
}
return c;
});
// remove duplicates (keeps order, keeps first occurence)
const sortedUniqChanges = sortedUniqBy(changes, (record) => record["@meta"].key);
// construuct new merged array
const result = [];
let recordsIdx = 0;
let changesIdx = 0;
// iterate and merge
while (changesIdx < sortedUniqChanges.length || recordsIdx < records.length) {
if (changesIdx < sortedUniqChanges.length && recordsIdx < records.length) {
const changeRecord = sortedUniqChanges[changesIdx];
const existingRecord = records[recordsIdx];
const changeKey = getBufferKey(changeRecord);
const existingKey = getBufferKey(existingRecord);
const comp = changeKey.compare(existingKey);
if (comp < 0) {
if (!skipStart || recordsIdx !== 0) {
result.push(changeRecord);
}
changesIdx++;
} else if (comp > 0) {
result.push(existingRecord);
recordsIdx++;
} else {
if (changeRecord["@meta"].timestamp >= existingRecord["@meta"].timestamp) {
result.push(changeRecord);
} else {
result.push(existingRecord);
}
changesIdx++;
recordsIdx++;
}
} else if (recordsIdx < records.length) {
result.push(records[recordsIdx]);
recordsIdx++;
} else if (changesIdx < sortedUniqChanges.length) {
if (skipEnd) {
changesIdx = sortedUniqChanges.length;
} else {
result.push(sortedUniqChanges[changesIdx]);
changesIdx++;
}
}
}
// done
return result;
}
function getBufferKey<TRecord>(record: Record<TRecord>): Buffer {
if (record["@meta"]._key === undefined) {
record["@meta"]._key = Buffer.from(record["@meta"].key, "base64");
}
return record["@meta"]._key;
} | the_stack |
"use strict";
// uuid: 2460e386-36d9-49ec-afd6-30963ab2e387
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
// The code shared by the server and cli
import { RelConsts } from "../shared/rel-consts.js";
export namespace OptsParser {
export const DEFAULT_OUT_PATTERN = '__PROJDIR__/story-frames/frame%05d.png';
export const DEFAULT_OUT_REPORT = '__FRAMES_DIR__/frame-report.json';
export const ON_ERROR_EXIT_VALUE = -1;
/** For security reasons, the user can't access this constant */
export const DEFAULT_MAX_WIDTH = 3840;
/** For security reasons, the user can't access this constant */
export const DEFAULT_MAX_HEIGHT = 2160;
/** For security reasons, the user can't access this constant */
export const DEFAULT_MAX_FPS = 50;
/** For security reasons, the user can't access this constant */
export const DEFAULT_MAX_FRAME_COUNT = 20 * 60 * 60 * 1; // limits to 1h at 20fps
export const DEFAULT_PROGRESS = 25;
export type MultipleValue = { [index: string]: string } | string[];
/**
* Map of all the common options to both the cli and the render server agent.
* Each key represents an option in both camelCase and Dash format.
*/
export let argOpts = {
ll: { param: 'int', desc: `log level. 0 has no verbosity` },
version: { desc: `version` },
url: {
param: 'string', desc:
`url of the page containing the animation
e.g. http://www.abeamer.com/
e.g. file:///home/abeamer/Documents/test/`},
file: {
param: 'string', desc:
`for running local files with relative paths
if --out isn't defined it sets to ${DEFAULT_OUT_PATTERN}
e.g --file gallery/hello-world/`},
out: {
param: 'string', desc:
`output file pattern. use %(0<n>)d for sequence,
creates the destination folder if doesn't exists
if it's defined after --file, the macro will be file value
e.g. --out ${DEFAULT_OUT_PATTERN}`,
},
report: {
param: 'string', desc:
`output report filename providing information about dimensions and fps
default is ${DEFAULT_OUT_REPORT}`,
},
allowedPlugins: {
param: 'string', desc:
`filename of the the list of the allowed plugins`,
},
injectPage: {
param: 'string', desc:
`filename of the index.html that will receive the injection`,
},
width: {
param: 'int', desc:
`frame output width. default is ${RelConsts.DEFAULT_WIDTH}`,
},
maxWidth: {
param: 'int', desc:
`maximum frame output width. default is ${DEFAULT_MAX_WIDTH}`,
},
height: {
param: 'int', desc:
`frame output height. default is ${RelConsts.DEFAULT_HEIGHT}`,
},
maxHeight: {
param: 'int', desc:
`maximum frame output height. default is ${DEFAULT_MAX_HEIGHT}`,
},
scale: {
param: 'string', desc: `scales to gif or movie movie generators.
e.g.
--scale 25%
--scale 200,400
--scale 40%,30%
`,
},
noframes: {
desc:
`doesn't render the frames to file nor generates the report.
use it only for debugging`},
server: {
param: 'string', desc:
`name of the server. default is ${RelConsts.DEFAULT_SERVER}`,
},
serverExec: {
param: 'string', desc:
`name of the server executable. default puppeteer=node. slimerjs=slimerjs`,
},
fps: {
param: 'int', desc:
`overrides frames per second defined on project`,
},
maxFps: {
param: 'int', desc:
`maximum frame per second. default is ${DEFAULT_MAX_FPS}`,
},
maxFrameCount: {
param: 'int', desc:
`maximum number of frames. default is ${DEFAULT_MAX_FRAME_COUNT}`,
},
progress: {
param: 'int', desc:
`number of frames it displays a progress info. if 0 doesn't shows progress. default is ${DEFAULT_PROGRESS}`,
},
timeout: {
param: 'int', desc:
`server timeout. default is 0`,
},
teleport: { desc: `makes the web browser run on teleport mode, and generates the story on the exit` },
dp: { desc: `deletes previous frames` },
config: {
param: 'string', desc:
`loads the config from a ini or json file
see https://www.abeamer.com/docs/latest/end-user/en/site/config-file/`,
},
var: {
param: 'object', desc:
`allows to pass multiple variables to client web library.
accessible as story.args.vars or in expressions.
if the variable name has dashes, it will be converted to camelCase
e.g --var name=end-user --var value=1.2.3`,
},
} as {
[name: string]: {
param?: string,
value?: string | number | boolean,
multipleValue?: MultipleValue,
hasOption?: boolean,
allowOption?: boolean,
desc: string,
},
};
// ------------------------------------------------------------------------
// Iterate Arg Options
// ------------------------------------------------------------------------
/** Returns true, if the argument is an option */
export const isOption = (arg: string) => arg.indexOf('--') === 0;
/**
* Iterates the command line arguments.
* For each option, it calls callback.
* If callback returns different from `undefined`, it exists immediately with
* the return value of the callback.
* Otherwise it iterates until all arguments are consumed and returns undefined.
*/
export function iterateArgOpts(toParseValue: boolean,
getNext: () => string,
callback: (option: string | 'param',
value: string | number | boolean, multipleValue?: MultipleValue) => int | undefined,
): int | undefined {
do {
const name = (getNext() || '').trim();
if (!name) {
break;
}
if (isOption(name)) {
const optName = name.substr(2)
// converts part1-part2-part3 => part1Part2Part3
.replace(/-(\w)/g, (_all, firstLetter: string) => firstLetter.toUpperCase())
// removes the suffix to solve the `--config` option conflict on slimerjs
.replace(/__\d+$/, '');
const opt = argOpts[optName];
if (opt === undefined) {
throw `Unknown option ${optName}`;
}
opt.hasOption = true;
if (opt.param) {
opt.value = getNext();
if (!opt.value || (isOption(opt.value) && !opt.allowOption)) {
throw `Missing value for ${name}`;
}
if (toParseValue) {
switch (opt.param) {
case 'int':
if (opt.value.match(/[^\d]/)) {
throw `${name} ${opt.value} isn't a integer value`;
}
opt.value = parseInt(opt.value);
break;
case 'boolean':
opt.value = opt.value === 'true'
|| opt.value === '1';
break;
case 'object':
opt.multipleValue = opt.multipleValue || {};
const [, key, value] = opt.value.match(/^([^=]+)=(.*)$/) || ['', '', ''];
if (!key) {
throw `${name} requires the key field`;
}
opt.multipleValue[key] = value;
break;
case 'array':
opt.multipleValue = opt.multipleValue || [];
(opt.multipleValue as string[]).push(opt.value);
break;
}
}
}
const res = callback(optName, opt.value, opt.multipleValue);
if (res !== undefined) {
return res;
}
} else {
callback('@param', name);
}
} while (true);
}
// ------------------------------------------------------------------------
// Compute Scale
// ------------------------------------------------------------------------
export function computeScale(width: int, height: int): string[] {
function computeScaleItem(item: string, dim: int): string {
let scale = 1;
if (item.endsWith('%')) {
scale = dim / 100;
item = item.substr(0, item.length - 1);
}
const value = parseInt(item, 10) * scale;
return Math.round(value).toString();
}
const sScale = (argOpts.scale.value as string || '').trim();
if (!sScale) {
return undefined;
}
const scaleItems = sScale.split(/\s*,\s*/);
return [
computeScaleItem(scaleItems[0], width),
computeScaleItem(scaleItems[1] || scaleItems[0], height)];
}
// ------------------------------------------------------------------------
// Print Usage
// ------------------------------------------------------------------------
/**
* Converts Options key to dash format, by replacing the uppercase to
* dash + lowercase.
*/
function _getDashKey(key: string): string {
return key.replace(/([A-Z])/g, (_all, p: string) =>
'-' + p.toLowerCase());
}
/** Outputs to the console the program usage */
export function printUsage(): void {
const names = Object.keys(argOpts);
let max = 0;
names.forEach(key => { max = Math.max(_getDashKey(key).length, max); });
const fromKeyToDesc = max + 3;
const descPos = 5 + fromKeyToDesc + 2;
console.log(`
The options are:
` + names.map(key => {
const dashKey = _getDashKey(key);
return ` --${dashKey}${Array(fromKeyToDesc - dashKey.length).join(' ')}`
+ `${argOpts[key].desc.split('\n').map((line, lineIndex) =>
Array(lineIndex ? descPos : 0).join(' ') + line.trim(),
).join('\n')}\n\n`;
}).join('\n'));
}
} | the_stack |
import {
GetFeature,
GetFeatureRequest,
GetFeatureResponse,
GetFeaturePayload,
GetFeatureCodeRequest,
GetFeatureCodePayload,
GetFeatureCode,
GetFeatureCodeResponse,
GetFeatureDescriptionRequest,
GetFeatureDescription,
GetFeatureDescriptionPayload,
GetFeatureDescriptionResponse,
UpdateFeatureDescriptionRequest,
UpdateFeatureDescriptionPayload,
UpdateFeatureDescriptionResponse,
UpdateFeatureDescription,
UpdateFeatureOwnerRequest,
UpdateFeatureOwnerResponse,
UpdateFeatureOwner,
GetFeaturePreviewDataRequest,
GetFeaturePreviewData,
GetFeaturePreviewDataResponse,
GetFeaturePreviewPayload,
} from 'ducks/feature/types';
import {
GetFeatureLineage,
GetFeatureLineageRequest,
GetFeatureLineageResponse,
GetFeatureLineagePayload,
} from 'ducks/lineage/types';
import {
FeatureCode,
FeatureMetadata,
FeaturePreviewQueryParams,
} from 'interfaces/Feature';
import { Lineage } from 'interfaces/Lineage';
import { UpdateOwnerPayload } from 'interfaces/TableMetadata';
import { User } from 'interfaces/User';
import { PreviewData } from 'interfaces/PreviewData';
/* Actions */
export function getFeature(
key: string,
index?: string,
source?: string
): GetFeatureRequest {
return {
payload: {
key,
index,
source,
},
type: GetFeature.REQUEST,
};
}
export function getFeatureSuccess(
payload: GetFeaturePayload
): GetFeatureResponse {
return {
payload,
type: GetFeature.SUCCESS,
};
}
export function getFeatureFailure(
payload: GetFeaturePayload
): GetFeatureResponse {
return {
payload,
type: GetFeature.FAILURE,
};
}
export function getFeatureLineage(key: string): GetFeatureLineageRequest {
return {
payload: {
key,
depth: 1,
direction: 'upstream',
},
type: GetFeatureLineage.REQUEST,
};
}
export function getFeatureLineageSuccess(
payload: GetFeatureLineagePayload
): GetFeatureLineageResponse {
return {
payload,
type: GetFeatureLineage.SUCCESS,
};
}
export function getFeatureLineageFailure(
payload: GetFeatureLineagePayload
): GetFeatureLineageResponse {
return {
payload,
type: GetFeatureLineage.FAILURE,
};
}
export function getFeatureCode(key: string): GetFeatureCodeRequest {
return {
payload: {
key,
},
type: GetFeatureCode.REQUEST,
};
}
export function getFeatureCodeSuccess(
payload: GetFeatureCodePayload
): GetFeatureCodeResponse {
return {
payload,
type: GetFeatureCode.SUCCESS,
};
}
export function getFeatureCodeFailure(
payload: GetFeatureCodePayload
): GetFeatureCodeResponse {
return {
payload,
type: GetFeatureCode.FAILURE,
};
}
export function getFeaturePreviewData(
payload: FeaturePreviewQueryParams
): GetFeaturePreviewDataRequest {
return {
payload,
type: GetFeaturePreviewData.REQUEST,
};
}
export function getFeaturePreviewDataSuccess(
payload: GetFeaturePreviewPayload
): GetFeaturePreviewDataResponse {
return {
payload,
type: GetFeaturePreviewData.SUCCESS,
};
}
export function getFeaturePreviewDataFailure(
payload: GetFeaturePreviewPayload
): GetFeaturePreviewDataResponse {
return {
payload,
type: GetFeaturePreviewData.FAILURE,
};
}
export function getFeatureDescription(
onSuccess?: () => any,
onFailure?: () => any
): GetFeatureDescriptionRequest {
return {
payload: {
onSuccess,
onFailure,
},
type: GetFeatureDescription.REQUEST,
};
}
export function getFeatureDescriptionSuccess(
payload: GetFeatureDescriptionPayload
) {
return {
payload,
type: GetFeatureDescription.SUCCESS,
};
}
export function getFeatureDescriptionFailure(
payload: GetFeatureDescriptionPayload
): GetFeatureDescriptionResponse {
return {
payload,
type: GetFeatureDescription.FAILURE,
};
}
export function updateFeatureDescription(
newValue: string,
onSuccess?: () => any,
onFailure?: () => any
): UpdateFeatureDescriptionRequest {
return {
payload: {
newValue,
onSuccess,
onFailure,
},
type: UpdateFeatureDescription.REQUEST,
};
}
export function updateFeatureDescriptionSuccess(
payload: UpdateFeatureDescriptionPayload
) {
return {
payload,
type: UpdateFeatureDescription.SUCCESS,
};
}
export function updateFeatureDescriptionFailure(
payload: UpdateFeatureDescriptionPayload
): UpdateFeatureDescriptionResponse {
return {
payload,
type: UpdateFeatureDescription.FAILURE,
};
}
export function updateFeatureOwner(
updateArray: UpdateOwnerPayload[],
onSuccess?: () => any,
onFailure?: () => any
): UpdateFeatureOwnerRequest {
return {
payload: {
onSuccess,
onFailure,
updateArray,
},
type: UpdateFeatureOwner.REQUEST,
};
}
export function updateFeatureOwnerFailure(
owners: User[]
): UpdateFeatureOwnerResponse {
return {
type: UpdateFeatureOwner.FAILURE,
payload: {
owners,
},
};
}
export function updateFeatureOwnerSuccess(
owners: User[]
): UpdateFeatureOwnerResponse {
return {
type: UpdateFeatureOwner.SUCCESS,
payload: {
owners,
},
};
}
/* Reducer */
export interface FeatureCodeState {
featureCode: FeatureCode;
isLoading: boolean;
statusCode: number | null;
}
export interface FeatureLineageState {
featureLineage: Lineage;
isLoading: boolean;
statusCode: number | null;
}
export interface FeaturePreviewDataState {
previewData: PreviewData;
isLoading: boolean;
status: number | null;
}
export interface FeatureReducerState {
isLoading: boolean;
isLoadingOwners: boolean;
statusCode: number | null;
feature: FeatureMetadata;
featureCode: FeatureCodeState;
featureLineage: FeatureLineageState;
preview: FeaturePreviewDataState;
}
export const initialFeatureState: FeatureMetadata = {
key: '',
name: '',
version: '',
status: '',
feature_group: '',
entity: '',
data_type: '',
availability: [],
description: '',
owners: [],
badges: [],
owner_tags: [],
tags: [],
programmatic_descriptions: [],
watermarks: [],
stats: [],
last_updated_timestamp: 0,
created_timestamp: 0,
};
export const emptyFeatureCode: FeatureCode = {
text: '',
source: '',
key: '',
};
export const initialPreviewState = {
previewData: {},
isLoading: false,
status: null,
};
export const initialFeatureCodeState: FeatureCodeState = {
featureCode: emptyFeatureCode,
isLoading: false,
statusCode: null,
};
export const emptyFeatureLineage: Lineage = {
upstream_entities: [],
downstream_entities: [],
depth: 1,
direction: 'upstream',
key: '',
};
export const initialFeatureLineageState: FeatureLineageState = {
featureLineage: emptyFeatureLineage,
isLoading: false,
statusCode: null,
};
export const initialState: FeatureReducerState = {
isLoading: false,
isLoadingOwners: false,
statusCode: null,
feature: initialFeatureState,
featureCode: initialFeatureCodeState,
featureLineage: initialFeatureLineageState,
preview: initialPreviewState,
};
export default function reducer(
state: FeatureReducerState = initialState,
action
): FeatureReducerState {
switch (action.type) {
case GetFeature.REQUEST:
return {
...state,
statusCode: null,
isLoading: true,
};
case GetFeature.FAILURE:
return {
...state,
isLoading: false,
statusCode: action.payload.statusCode,
feature: initialFeatureState,
};
case GetFeature.SUCCESS:
return {
...state,
isLoading: false,
statusCode: action.payload.statusCode,
feature: action.payload.feature,
};
case GetFeatureCode.REQUEST:
return {
...state,
featureCode: {
featureCode: emptyFeatureCode,
isLoading: true,
statusCode: null,
},
};
case GetFeatureCode.FAILURE:
return {
...state,
featureCode: {
featureCode: emptyFeatureCode,
isLoading: false,
statusCode: action.payload.statusCode,
},
};
case GetFeatureCode.SUCCESS:
return {
...state,
featureCode: {
featureCode: action.payload.featureCode,
statusCode: action.payload.statusCode,
isLoading: false,
},
};
case GetFeatureLineage.REQUEST:
return {
...state,
featureLineage: {
featureLineage: emptyFeatureLineage,
isLoading: true,
statusCode: null,
},
};
case GetFeatureLineage.FAILURE:
return {
...state,
featureLineage: {
featureLineage: emptyFeatureLineage,
isLoading: false,
statusCode: action.payload.statusCode,
},
};
case GetFeatureLineage.SUCCESS:
return {
...state,
featureLineage: {
featureLineage: action.payload.data,
isLoading: false,
statusCode: action.payload.statusCode,
},
};
case GetFeaturePreviewData.REQUEST:
return {
...state,
preview: {
isLoading: true,
previewData: {},
status: null,
},
};
case GetFeaturePreviewData.SUCCESS:
case GetFeaturePreviewData.FAILURE:
return {
...state,
preview: {
isLoading: false,
previewData: action.payload.previewData,
status: action.payload.status,
},
};
case GetFeatureDescription.FAILURE:
case GetFeatureDescription.SUCCESS:
return {
...state,
feature: {
...state.feature,
description: action.payload.description,
},
};
case UpdateFeatureDescription.FAILURE:
case UpdateFeatureDescription.SUCCESS:
return {
...state,
feature: {
...state.feature,
description: action.payload.description,
},
};
case UpdateFeatureOwner.REQUEST:
return { ...state, isLoadingOwners: true };
case UpdateFeatureOwner.FAILURE:
case UpdateFeatureOwner.SUCCESS:
return {
...state,
isLoadingOwners: false,
feature: {
...state.feature,
owners: (<UpdateFeatureOwnerResponse>action).payload.owners,
},
};
default:
return state;
}
} | the_stack |
namespace ts.pxtc.assembler {
export let debug = false
export interface InlineError {
scope: string;
message: string;
line: string;
lineNo: number;
coremsg: string;
hints: string;
}
export interface EmitResult {
stack: number;
opcode: number;
opcode2?: number; // in case of a 32-bit instruction
opcode3?: number; // really, for the VM, where opcodes are 8 bit
numArgs?: number[];
error?: string;
errorAt?: string;
labelName?: string;
}
export function lf(fmt: string, ...args: any[]) { // @ignorelf@
return fmt.replace(/{(\d+)}/g, (match, index) => args[+index]);
}
let badNameError = emitErr("opcode name doesn't match", "<name>")
// An Instruction represents an instruction class with meta-variables
// that should be substituted given an actually line (Line) of assembly
// Thus, the Instruction helps us parse a sequence of tokens in a Line
// as well as extract the relevant values to substitute for the meta-variables.
// The Instruction also knows how to convert the particular instance into
// machine code (EmitResult)
export class Instruction {
public name: string;
public args: string[];
public friendlyFmt: string;
public code: string;
protected ei: AbstractProcessor;
public canBeShared = false;
constructor(ei: AbstractProcessor, format: string, public opcode: number, public mask: number, public is32bit: boolean) {
assert((opcode & mask) == opcode)
this.ei = ei;
this.code = format.replace(/\s+/g, " ");
this.friendlyFmt = format.replace(/\$\w+/g, m => {
if (this.ei.encoders[m])
return this.ei.encoders[m].pretty
return m
})
let words = tokenize(format)
this.name = words[0]
this.args = words.slice(1)
}
emit(ln: Line): EmitResult {
let tokens = ln.words;
if (tokens[0] != this.name) return badNameError;
let r = this.opcode;
let j = 1;
let stack = 0;
let numArgs: number[] = []
let labelName: string = null
let bit32_value: number = null
let bit32_actual: string = null
for (let i = 0; i < this.args.length; ++i) {
let formal = this.args[i]
let actual = tokens[j++]
if (formal[0] == "$") {
let enc = this.ei.encoders[formal]
let v: number = null
if (enc.isRegister) {
v = this.ei.registerNo(actual);
if (v == null) return emitErr("expecting register name", actual)
if (this.ei.isPush(this.opcode)) // push
stack++;
else if (this.ei.isPop(this.opcode)) // pop
stack--;
} else if (enc.isImmediate) {
actual = actual.replace(/^#/, "")
v = ln.bin.parseOneInt(actual);
if (v == null) {
return emitErr("expecting number", actual)
} else {
// explicit manipulation of stack pointer (SP)
// ARM only
if (this.ei.isAddSP(this.opcode))
stack = -(v / this.ei.wordSize());
else if (this.ei.isSubSP(this.opcode))
stack = (v / this.ei.wordSize());
}
} else if (enc.isRegList) {
// register lists are ARM-specific - this code not used in AVR
if (actual != "{") return emitErr("expecting {", actual);
v = 0;
while (tokens[j] != "}") {
actual = tokens[j++];
if (!actual)
return emitErr("expecting }", tokens[j - 2])
let no = this.ei.registerNo(actual);
if (no == null) return emitErr("expecting register name", actual)
if (v & (1 << no)) return emitErr("duplicate register name", actual)
v |= (1 << no);
if (this.ei.isPush(this.opcode)) // push
stack++;
else if (this.ei.isPop(this.opcode)) // pop
stack--;
if (tokens[j] == ",") j++;
}
actual = tokens[j++]; // skip close brace
} else if (enc.isLabel) {
actual = actual.replace(/^#/, "")
if (/^[+-]?\d+$/.test(actual)) {
v = parseInt(actual, 10)
labelName = "rel" + v
} else if (/^0x[0-9a-fA-F]+$/.test(actual)) {
v = parseInt(actual, 16)
labelName = "abs" + v
} else {
labelName = actual
v = this.ei.getAddressFromLabel(ln.bin, this, actual, enc.isWordAligned)
if (v == null) {
if (ln.bin.finalEmit)
return emitErr("unknown label", actual)
else
// just need some value when we are
// doing some pass other than finalEmit
v = 8; // needs to be divisible by 4 etc
}
}
if (this.ei.is32bit(this)) {
// console.log(actual + " " + v.toString())
bit32_value = v
bit32_actual = actual
continue
}
} else {
oops()
}
if (v == null) return emitErr("didn't understand it", actual); // shouldn't happen
numArgs.push(v)
v = enc.encode(v)
// console.log("enc(v) = ",v)
if (v == null) return emitErr("argument out of range or mis-aligned", actual);
assert((r & v) == 0)
r |= v;
} else if (formal == actual) {
// skip
} else {
return emitErr("expecting " + formal, actual)
}
}
if (tokens[j]) return emitErr("trailing tokens", tokens[j])
if (this.ei.is32bit(this)) {
return this.ei.emit32(r, bit32_value, ln.bin.normalizeExternalLabel(bit32_actual));
}
return {
stack: stack,
opcode: r,
numArgs: numArgs,
labelName: ln.bin.normalizeExternalLabel(labelName)
}
}
toString() {
return this.friendlyFmt;
}
}
// represents a line of assembly from a file
export class Line {
public type: string;
public lineNo: number;
public words: string[]; // the tokens in this line
public scope: string;
public location: number;
public instruction: Instruction;
public numArgs: number[];
public opcode: number;
public stack: number;
public isLong: boolean;
constructor(public bin: File, public text: string) {
}
public getOpExt() {
return this.instruction ? this.instruction.code : "";
}
public getOp() {
return this.instruction ? this.instruction.name : "";
}
public update(s: string) {
this.bin.peepOps++;
s = s.replace(/^\s*/, "")
if (!s)
this.bin.peepDel++;
if (s) s += " ";
s = " " + s;
this.text = s + "; WAS: " + this.text.trim();
this.instruction = null;
this.numArgs = null;
this.words = tokenize(s) || [];
if (this.words.length == 0)
this.type = "empty";
else if (this.words[0][0] == "@")
this.type = "directive";
}
}
// File is the center of the action: parsing a file into a sequence of Lines
// and also emitting the binary (buf)
export class File {
constructor(ei: AbstractProcessor) {
this.currLine = new Line(this, "<start>");
this.currLine.lineNo = 0;
this.ei = ei;
this.ei.file = this;
}
public baseOffset: number = 0;
public finalEmit: boolean;
public reallyFinalEmit: boolean;
public checkStack = true;
public inlineMode = false;
public lookupExternalLabel: (name: string) => number;
public normalizeExternalLabel = (n: string) => n;
public ei: AbstractProcessor;
public lines: Line[];
private currLineNo: number = 0;
private realCurrLineNo: number;
private currLine: Line;
private scope = "";
private scopeId = 0;
public errors: InlineError[] = [];
public buf: number[];
private labels: pxt.Map<number> = {};
private equs: pxt.Map<number> = {};
private userLabelsCache: pxt.Map<number>;
private stackpointers: pxt.Map<number> = {};
private stack = 0;
public commPtr = 0;
public peepOps = 0;
public peepDel = 0;
public peepCounts: pxt.Map<number> = {}
private stats = "";
public throwOnError = false;
public disablePeepHole = false;
public stackAtLabel: pxt.Map<number> = {};
private prevLabel: string;
protected emitShort(op: number) {
assert(0 <= op && op <= 0xffff);
this.buf.push(op);
}
protected emitOpCode(op: number) {
this.emitShort(op)
}
public location() {
// store one short (2 bytes) per buf location
return this.buf.length * 2;
}
public pc() {
return this.location() + this.baseOffset;
}
// parsing of an "integer", well actually much more than
// just that
public parseOneInt(s: string): number {
if (!s)
return null;
// fast path
if (/^\d+$/.test(s))
return parseInt(s, 10)
const minP = s.indexOf("-")
if (minP > 0)
return this.parseOneInt(s.slice(0, minP)) - this.parseOneInt(s.slice(minP + 1))
let mul = 1
// recursive-descent parsing of multiplication
if (s.indexOf("*") >= 0) {
let m: RegExpExecArray = null;
while (null != (m = /^([^\*]*)\*(.*)$/.exec(s))) {
let tmp = this.parseOneInt(m[1])
if (tmp == null) return null;
mul *= tmp;
s = m[2]
}
}
if (s[0] == "-") {
mul *= -1;
s = s.slice(1)
} else if (s[0] == "+") {
s = s.slice(1)
}
// decimal encoding; fast-ish path
if (/^\d+$/.test(s))
return mul * parseInt(s, 10)
// allow or'ing of 1 to least-signficant bit
if (U.endsWith(s, "|1")) {
return this.parseOneInt(s.slice(0, s.length - 2)) | 1
}
// allow subtracting 1 too
if (U.endsWith(s, "-1")) {
return this.parseOneInt(s.slice(0, s.length - 2)) - 1
}
// allow adding 1 too
if (U.endsWith(s, "+1")) {
return this.parseOneInt(s.slice(0, s.length - 2)) + 1
}
let shm = /(.*)>>(\d+)$/.exec(s)
if (shm) {
let left = this.parseOneInt(shm[1])
let mask = this.baseOffset & ~0xffffff
left &= ~mask;
return left >> parseInt(shm[2])
}
let v: number = null
// handle hexadecimal and binary encodings
if (s[0] == "0") {
if (s[1] == "x" || s[1] == "X") {
let m = /^0x([a-f0-9]+)$/i.exec(s)
if (m) v = parseInt(m[1], 16)
} else if (s[1] == "b" || s[1] == "B") {
let m = /^0b([01]+)$/i.exec(s)
if (m) v = parseInt(m[1], 2)
}
}
// stack-specific processing
// more special characters to handle
if (s.indexOf("@") >= 0) {
let m = /^(\w+)@(-?\d+)$/.exec(s)
if (m) {
if (mul != 1)
this.directiveError(lf("multiplication not supported with saved stacks"));
if (this.stackpointers.hasOwnProperty(m[1])) {
// console.log(m[1] + ": " + this.stack + " " + this.stackpointers[m[1]] + " " + m[2])
v = this.ei.wordSize() * this.ei.computeStackOffset(m[1], this.stack - this.stackpointers[m[1]] + parseInt(m[2]))
// console.log(v)
}
else
this.directiveError(lf("saved stack not found"))
}
m = /^(.*)@(hi|lo|fn)$/.exec(s)
if (m && this.looksLikeLabel(m[1])) {
v = this.lookupLabel(m[1], true)
if (v != null) {
if (m[2] == "fn") {
v = this.ei.toFnPtr(v, this.baseOffset, m[1])
} else {
v >>= 1;
if (0 <= v && v <= 0xffff) {
if (m[2] == "hi")
v = (v >> 8) & 0xff
else if (m[2] == "lo")
v = v & 0xff
else
oops()
} else {
this.directiveError(lf("@hi/lo out of range"))
v = null
}
}
}
}
}
if (v == null && this.looksLikeLabel(s)) {
v = this.lookupLabel(s, true);
if (v != null) {
if (this.ei.postProcessRelAddress(this, 1) == 1)
v += this.baseOffset
}
}
if (v == null || isNaN(v)) return null;
return v * mul;
}
private looksLikeLabel(name: string) {
if (/^(r\d|pc|sp|lr)$/i.test(name))
return false
return /^[\.a-zA-Z_][\.:\w+]*$/.test(name)
}
private scopedName(name: string) {
if (name[0] == "." && this.scope)
return this.scope + "$" + name;
else return name;
}
public lookupLabel(name: string, direct = false) {
let v: number = null;
let scoped = this.scopedName(name)
if (this.labels.hasOwnProperty(scoped)) {
v = this.labels[scoped];
v = this.ei.postProcessRelAddress(this, v)
} else if (this.lookupExternalLabel) {
v = this.lookupExternalLabel(name)
if (v != null) {
v = this.ei.postProcessAbsAddress(this, v)
}
}
if (v == null && this.equs.hasOwnProperty(scoped)) {
v = this.equs[scoped]
// no post-processing
}
if (v == null && direct) {
if (this.finalEmit) {
this.directiveError(lf("unknown label: {0}", name));
} else
// use a number over 1 byte
v = 11111;
}
return v;
}
private align(n: number) {
assert(n == 2 || n == 4 || n == 8 || n == 16)
while (this.location() % n != 0)
this.emitOpCode(0);
}
public pushError(msg: string, hints: string = "") {
let err = <InlineError>{
scope: this.scope,
message: lf(" -> Line {2} ('{1}'), error: {0}\n{3}", msg, this.currLine.text, this.currLine.lineNo, hints),
lineNo: this.currLine.lineNo,
line: this.currLine.text,
coremsg: msg,
hints: hints
}
this.errors.push(err)
if (this.throwOnError)
throw new Error(err.message)
}
private directiveError(msg: string) {
this.pushError(msg)
// this.pushError(lf("directive error: {0}", msg))
}
private emitString(l: string, utf16 = false) {
function byteAt(s: string, i: number) { return (s.charCodeAt(i) || 0) & 0xff }
let m = /^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(l)
let s: string;
if (!m || null == (s = parseString(m[2]))) {
this.directiveError(lf("expecting string"))
} else {
this.align(2);
if (utf16) {
for (let i = 0; i < s.length; i++) {
this.emitShort(s.charCodeAt(i))
}
} else {
// s.length + 1 to NUL terminate
for (let i = 0; i < s.length + 1; i += 2) {
this.emitShort((byteAt(s, i + 1) << 8) | byteAt(s, i))
}
}
}
}
private parseNumber(words: string[]): number {
let v = this.parseOneInt(words.shift())
if (v == null) return null;
return v;
}
private parseNumbers(words: string[]) {
words = words.slice(1)
let nums: number[] = []
while (true) {
let n = this.parseNumber(words)
if (n == null) {
this.directiveError(lf("cannot parse number at '{0}'", words[0]))
break;
} else
nums.push(n)
if (words[0] == ",") {
words.shift()
if (words[0] == null)
break;
} else if (words[0] == null) {
break;
} else {
this.directiveError(lf("expecting number, got '{0}'", words[0]))
break;
}
}
return nums
}
private emitSpace(words: string[]) {
let nums = this.parseNumbers(words);
if (nums.length == 1)
nums.push(0)
if (nums.length != 2)
this.directiveError(lf("expecting one or two numbers"))
else if (nums[0] % 2 != 0)
this.directiveError(lf("only even space supported"))
else {
let f = nums[1] & 0xff;
f = f | (f << 8)
for (let i = 0; i < nums[0]; i += 2)
this.emitShort(f)
}
}
private emitBytes(words: string[]) {
let nums = this.parseNumbers(words)
if (nums.length % 2 != 0) {
this.directiveError(".bytes needs an even number of arguments")
nums.push(0)
}
for (let i = 0; i < nums.length; i += 2) {
let n0 = nums[i]
let n1 = nums[i + 1]
if (0 <= n0 && n1 <= 0xff &&
0 <= n1 && n0 <= 0xff)
this.emitShort((n0 & 0xff) | ((n1 & 0xff) << 8))
else
this.directiveError(lf("expecting uint8"))
}
}
private emitHex(words: string[]) {
words.slice(1).forEach(w => {
if (w == ",") return
// TODO: why 4 and not 2?
if (w.length % 4 != 0)
this.directiveError(".hex needs an even number of bytes")
else if (!/^[a-f0-9]+$/i.test(w))
this.directiveError(".hex needs a hex number")
else
for (let i = 0; i < w.length; i += 4) {
let n = parseInt(w.slice(i, i + 4), 16)
n = ((n & 0xff) << 8) | ((n >> 8) & 0xff)
this.emitShort(n)
}
})
}
private handleDirective(l: Line) {
let words = l.words;
let expectOne = () => {
if (words.length != 2)
this.directiveError(lf("expecting one argument"));
}
let num0: number;
switch (words[0]) {
case ".ascii":
case ".asciz":
case ".string":
this.emitString(l.text);
break;
case ".utf16":
this.emitString(l.text, true);
break;
case ".align":
expectOne();
num0 = this.parseOneInt(words[1]);
if (num0 != null) {
if (num0 == 0) return;
if (num0 <= 4) {
this.align(1 << num0);
} else {
this.directiveError(lf("expecting 1, 2, 3 or 4 (for 2, 4, 8, or 16 byte alignment)"))
}
} else this.directiveError(lf("expecting number"));
break;
case ".balign":
expectOne();
num0 = this.parseOneInt(words[1]);
if (num0 != null) {
if (num0 == 1) return;
if (num0 == 2 || num0 == 4 || num0 == 8 || num0 == 16) {
this.align(num0);
} else {
this.directiveError(lf("expecting 2, 4, 8, or 16"))
}
} else this.directiveError(lf("expecting number"));
break;
case ".p2align":
expectOne();
num0 = this.parseOneInt(words[1]);
if (num0 != null) {
this.align(1 << num0);
} else this.directiveError(lf("expecting number"));
break;
case ".byte":
this.emitBytes(words);
break;
case ".hex":
this.emitHex(words);
break;
case ".hword":
case ".short":
case ".2bytes":
this.parseNumbers(words).forEach(n => {
// we allow negative numbers
if (-0x8000 <= n && n <= 0xffff)
this.emitShort(n & 0xffff)
else
this.directiveError(lf("expecting int16"))
})
break;
case ".word":
case ".4bytes":
case ".long":
// TODO: a word is machine-dependent (16-bit for AVR, 32-bit for ARM)
this.parseNumbers(words).forEach(n => {
// we allow negative numbers
if (-0x80000000 <= n && n <= 0xffffffff) {
this.emitShort(n & 0xffff)
this.emitShort((n >> 16) & 0xffff)
} else {
this.directiveError(lf("expecting int32"))
}
})
break;
case ".skip":
case ".space":
this.emitSpace(words);
break;
case ".set":
case ".equ":
if (!/^\w+$/.test(words[1]))
this.directiveError(lf("expecting name"))
const nums = this.parseNumbers(words.slice(words[2] == "," || words[2] == "="
? 2 : 1))
if (nums.length != 1)
this.directiveError(lf("expecting one value"))
if (this.equs[words[1]] !== undefined &&
this.equs[words[1]] != nums[0])
this.directiveError(lf("redefinition of {0}", words[1]))
this.equs[words[1]] = nums[0]
break;
case ".startaddr":
if (this.location())
this.directiveError(lf(".startaddr can be only be specified at the beginning of the file"))
expectOne()
this.baseOffset = this.parseOneInt(words[1]);
break;
// The usage for this is as follows:
// push {...}
// @stackmark locals ; locals := sp
// ... some push/pops ...
// ldr r0, [sp, locals@3] ; load local number 3
// ... some push/pops ...
// @stackempty locals ; expect an empty stack here
case "@stackmark":
expectOne();
this.stackpointers[words[1]] = this.stack;
break;
case "@stackempty":
if (this.checkStack) {
if (this.stackpointers[words[1]] == null)
this.directiveError(lf("no such saved stack"))
else if (this.stackpointers[words[1]] != this.stack)
this.directiveError(lf("stack mismatch"))
}
break;
case "@scope":
this.scope = words[1] || "";
this.currLineNo = this.scope ? 0 : this.realCurrLineNo;
break;
case ".syntax":
case "@nostackcheck":
this.checkStack = false
break
case "@dummystack":
expectOne()
this.stack += this.parseOneInt(words[1]);
break
case ".section":
case ".global":
this.stackpointers = {};
this.stack = 0;
this.scope = "$S" + this.scopeId++
break;
case ".comm": {
words = words.filter(x => x != ",")
words.shift()
let sz = this.parseOneInt(words[1])
let align = 0
if (words[2])
align = this.parseOneInt(words[2])
else
align = 4 // not quite what AS does...
let val = this.lookupLabel(words[0])
if (val == null) {
if (!this.commPtr) {
this.commPtr = this.lookupExternalLabel("_pxt_comm_base") || 0
if (!this.commPtr)
this.directiveError(lf("PXT_COMM_BASE not defined"))
}
while (this.commPtr & (align - 1))
this.commPtr++
this.labels[this.scopedName(words[0])] = this.commPtr - this.baseOffset
this.commPtr += sz
}
break
}
case ".file":
case ".text":
case ".cpu":
case ".fpu":
case ".eabi_attribute":
case ".code":
case ".thumb_func":
case ".type":
case ".fnstart":
case ".save":
case ".size":
case ".fnend":
case ".pad":
case ".globl": // TODO might need this one
case ".local":
break;
case "@":
// @ sp needed
break;
default:
if (/^\.cfi_/.test(words[0])) {
// ignore
} else {
this.directiveError(lf("unknown directive"))
}
break;
}
}
private handleOneInstruction(ln: Line, instr: Instruction) {
let op = instr.emit(ln);
if (!op.error) {
this.stack += op.stack;
if (this.checkStack && this.stack < 0)
this.pushError(lf("stack underflow"))
ln.location = this.location()
ln.opcode = op.opcode
ln.stack = op.stack
this.emitOpCode(op.opcode);
if (op.opcode2 != null)
this.emitOpCode(op.opcode2);
if (op.opcode3 != null)
this.emitOpCode(op.opcode3);
ln.instruction = instr;
ln.numArgs = op.numArgs;
return true;
}
return false;
}
private handleInstruction(ln: Line) {
if (ln.instruction) {
if (this.handleOneInstruction(ln, ln.instruction))
return;
}
let getIns = (n: string) => this.ei.instructions.hasOwnProperty(n) ? this.ei.instructions[n] : [];
if (!ln.instruction) {
let ins = getIns(ln.words[0])
for (let i = 0; i < ins.length; ++i) {
if (this.handleOneInstruction(ln, ins[i]))
return;
}
}
let w0 = ln.words[0].toLowerCase().replace(/s$/, "").replace(/[^a-z]/g, "")
let hints = ""
let possibilities = getIns(w0).concat(getIns(w0 + "s"))
if (possibilities.length > 0) {
possibilities.forEach(i => {
let err = i.emit(ln);
hints += lf(" Maybe: {0} ({1} at '{2}')\n", i.toString(), err.error, err.errorAt)
})
}
this.pushError(lf("assembly error"), hints);
}
public buildLine(tx: string, lst: Line[]) {
let mkLine = (tx: string) => {
let l = new Line(this, tx);
l.scope = this.scope;
l.lineNo = this.currLineNo;
lst.push(l)
return l;
}
let l = mkLine(tx);
let words = tokenize(l.text) || [];
l.words = words;
let w0 = words[0] || ""
if (w0.charAt(w0.length - 1) == ":") {
let m = /^([\.\w]+):$/.exec(words[0])
if (m) {
l.type = "label";
l.text = m[1] + ":"
l.words = [m[1]]
if (words.length > 1) {
words.shift()
l = mkLine(tx.replace(/^[^:]*:/, ""))
l.words = words
w0 = words[0] || ""
} else {
return;
}
}
}
let c0 = w0.charAt(0)
if (c0 == "." || c0 == "@") {
l.type = "directive";
if (l.words[0] == "@scope")
this.handleDirective(l);
} else {
if (l.words.length == 0)
l.type = "empty";
else
l.type = "instruction";
}
}
private prepLines(text: string) {
this.currLineNo = 0;
this.realCurrLineNo = 0;
this.lines = [];
text.split(/\r?\n/).forEach(tx => {
if (this.errors.length > 10)
return;
this.currLineNo++;
this.realCurrLineNo++;
this.buildLine(tx, this.lines)
})
}
private iterLines() {
this.stack = 0;
this.buf = [];
this.scopeId = 0;
this.lines.forEach(l => {
if (this.errors.length > 10)
return;
this.currLine = l;
if (l.words.length == 0) return;
if (l.type == "label") {
let lblname = this.scopedName(l.words[0])
this.prevLabel = lblname
if (this.finalEmit) {
if (this.equs[lblname] != null)
this.directiveError(lf(".equ redefined as label"))
let curr = this.labels[lblname]
if (curr == null)
oops()
if (this.errors.length == 0 && curr != this.location()) {
oops(`invalid location: ${this.location()} != ${curr} at ${lblname}`)
}
assert(this.errors.length > 0 || curr == this.location())
if (this.reallyFinalEmit) {
this.stackAtLabel[lblname] = this.stack
}
} else {
if (this.labels.hasOwnProperty(lblname))
this.directiveError(lf("label redefinition"))
else if (this.inlineMode && /^_/.test(lblname))
this.directiveError(lf("labels starting with '_' are reserved for the compiler"))
else {
this.labels[lblname] = this.location();
}
}
l.location = this.location()
} else if (l.type == "directive") {
this.handleDirective(l);
} else if (l.type == "instruction") {
this.handleInstruction(l);
} else if (l.type == "empty") {
// nothing
} else {
oops()
}
})
}
public getSourceMap() {
const sourceMap: pxt.Map<number[]> = {}
let locFile = ""
let locLn = 0
let locPos = 0
let locEnd = 0
this.lines.forEach((ln, i) => {
const m = /^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(ln.text)
if (m) {
flush()
locFile = m[1]
locLn = parseInt(m[2])
}
if (ln.type == "instruction") {
if (!locPos) locPos = ln.location
locEnd = ln.location
}
})
flush()
function flush() {
if (locFile && locPos) {
if (!sourceMap[locFile])
sourceMap[locFile] = []
sourceMap[locFile].push(locLn, locPos, locEnd - locPos)
}
locPos = 0
locEnd = 0
}
return sourceMap
}
public getSource(clean: boolean, numStmts = 1, flashSize = 0) {
let lenPrev = 0
let size = (lbl: string) => {
let curr = this.labels[lbl] || lenPrev
let sz = curr - lenPrev
lenPrev = curr
return sz
}
let lenTotal = this.buf ? this.location() : 0
let lenCode = size("_code_end")
let lenHelpers = size("_helpers_end")
let lenVtables = size("_vtables_end")
let lenLiterals = size("_literals_end")
let lenAllCode = lenPrev
let totalSize = (lenTotal + this.baseOffset) & 0xffffff
if (flashSize && totalSize > flashSize)
U.userError(lf("program too big by {0} bytes!", totalSize - flashSize))
flashSize = flashSize || 128 * 1024
let totalInfo = lf("; total bytes: {0} ({1}% of {2}k flash with {3} free)",
totalSize, (100 * totalSize / flashSize).toFixed(1), (flashSize / 1024).toFixed(1),
flashSize - totalSize)
let res =
// ARM-specific
lf("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",
lenAllCode, lenCode, lenHelpers, lenVtables, lenLiterals,
lenTotal - lenAllCode) +
lf("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",
this.lines.length,
Math.round(100 * lenCode / numStmts) / 100, numStmts) +
totalInfo + "\n" +
this.stats + "\n\n"
let skipOne = false
this.lines.forEach((ln, i) => {
if (ln.words[0] == "_stored_program") {
res += "_stored_program: .string \"...\"\n"
skipOne = true
return
}
if (skipOne) {
skipOne = false
return
}
let text = ln.text
if (clean) {
if (ln.words[0] == "@stackempty" &&
this.lines[i - 1].text == ln.text)
return;
text = text.replace(/; WAS: .*/, "")
if (!text.trim()) return;
}
if (debug)
if (ln.type == "label" || ln.type == "instruction")
text += ` \t; 0x${(ln.location + this.baseOffset).toString(16)}`
res += text + "\n"
})
return res;
}
private peepHole() {
// TODO add: str X; ldr X -> str X ?
let mylines = this.lines.filter(l => l.type != "empty")
for (let i = 0; i < mylines.length; ++i) {
let ln = mylines[i];
if (/^user/.test(ln.scope)) // skip opt for user-supplied assembly
continue;
let lnNext = mylines[i + 1];
if (!lnNext) continue;
let lnNext2 = mylines[i + 2]
if (ln.type == "instruction") {
this.ei.peephole(ln, lnNext, lnNext2)
}
}
}
private clearLabels() {
this.labels = {}
this.commPtr = 0
}
private peepPass(reallyFinal: boolean) {
if (this.disablePeepHole)
return;
this.peepOps = 0;
this.peepDel = 0;
this.peepCounts = {}
this.peepHole();
this.throwOnError = true;
this.finalEmit = false;
this.clearLabels();
this.iterLines();
assert(!this.checkStack || this.stack == 0);
this.finalEmit = true;
this.reallyFinalEmit = reallyFinal || this.peepOps == 0;
this.iterLines();
this.stats += lf("; peep hole pass: {0} instructions removed and {1} updated\n", this.peepDel, this.peepOps - this.peepDel)
}
public getLabels() {
if (!this.userLabelsCache)
this.userLabelsCache = U.mapMap(this.labels, (k, v) => v + this.baseOffset)
return this.userLabelsCache
}
public emit(text: string) {
assert(this.buf == null);
this.prepLines(text);
if (this.errors.length > 0)
return;
this.clearLabels();
this.iterLines();
if (this.checkStack && this.stack != 0)
this.directiveError(lf("stack misaligned at the end of the file"))
if (this.errors.length > 0)
return;
this.ei.expandLdlit(this);
this.clearLabels();
this.iterLines();
this.finalEmit = true;
this.reallyFinalEmit = this.disablePeepHole;
this.iterLines();
if (this.errors.length > 0)
return;
let maxPasses = 5
for (let i = 0; i < maxPasses; ++i) {
pxt.debug(`Peephole OPT, pass ${i}`)
this.peepPass(i == maxPasses);
if (this.peepOps == 0) break;
}
pxt.debug("emit done")
}
}
export class VMFile extends File {
constructor(ei: AbstractProcessor) {
super(ei)
}
}
// describes the encodings of various parts of an instruction
// (registers, immediates, register lists, labels)
export interface Encoder {
name: string;
pretty: string;
// given a value, check it is the right number of bits and
// translate the value to the proper set of bits
encode: (v: number) => number;
isRegister: boolean;
isImmediate: boolean;
isRegList: boolean;
isLabel: boolean;
isWordAligned?: boolean;
}
// an assembler provider must inherit from this
// class and provide Encoders and Instructions
export abstract class AbstractProcessor {
public encoders: pxt.Map<Encoder>;
public instructions: pxt.Map<Instruction[]>;
public file: File = null;
constructor() {
this.encoders = {};
this.instructions = {}
}
public toFnPtr(v: number, baseOff: number, lbl: string) {
return v;
}
public wordSize() {
return -1;
}
public computeStackOffset(kind: string, offset: number) {
return offset;
}
public is32bit(i: Instruction) {
return false;
}
public emit32(v1: number, v2: number, actual: string): EmitResult {
return null;
}
public postProcessRelAddress(f: File, v: number): number {
return v;
}
public postProcessAbsAddress(f: File, v: number): number {
return v;
}
public peephole(ln: Line, lnNext: Line, lnNext2: Line) {
return;
}
public registerNo(actual: string): number {
return null;
}
public getAddressFromLabel(f: File, i: Instruction, s: string, wordAligned = false): number {
return null;
}
public isPop(opcode: number): boolean {
return false;
}
public isPush(opcode: number): boolean {
return false;
}
public isAddSP(opcode: number): boolean {
return false;
}
public isSubSP(opcode: number): boolean {
return false;
}
public testAssembler() {
assert(false)
}
public expandLdlit(f: File): void {
}
protected addEnc = (n: string, p: string, e: (v: number) => number) => {
let ee: Encoder = {
name: n,
pretty: p,
encode: e,
isRegister: /^\$r\d/.test(n),
isImmediate: /^\$i\d/.test(n),
isRegList: /^\$rl\d/.test(n),
isLabel: /^\$l[a-z]/.test(n),
}
this.encoders[n] = ee
return ee
}
protected inrange = (max: number, v: number, e: number) => {
if (Math.floor(v) != v) return null;
if (v < 0) return null;
if (v > max) return null;
return e;
}
protected inminmax = (min: number, max: number, v: number, e: number) => {
if (Math.floor(v) != v) return null;
if (v < min) return null;
if (v > max) return null;
return e;
}
protected inseq = (seq: number[], v: number) => {
let ind = seq.indexOf(v);
if (ind < 0) return null
return ind;
}
protected inrangeSigned = (max: number, v: number, e: number) => {
if (Math.floor(v) != v) return null;
if (v < -(max + 1)) return null;
if (v > max) return null;
let mask = (max << 1) | 1
return e & mask;
}
protected addInst = (name: string, code: number, mask: number, is32Bit?: boolean) => {
let ins = new Instruction(this, name, code, mask, is32Bit)
if (!this.instructions.hasOwnProperty(ins.name))
this.instructions[ins.name] = [];
this.instructions[ins.name].push(ins)
return ins
}
}
// utility functions
function tokenize(line: string): string[] {
let words: string[] = []
let w = ""
loop: for (let i = 0; i < line.length; ++i) {
switch (line[i]) {
case "[":
case "]":
case "!":
case "{":
case "}":
case ",":
if (w) { words.push(w); w = "" }
words.push(line[i])
break;
case " ":
case "\t":
case "\r":
case "\n":
if (w) { words.push(w); w = "" }
break;
case ";":
// drop the trailing comment
break loop;
default:
w += line[i]
break;
}
}
if (w) { words.push(w); w = "" }
if (!words[0]) return null
return words
}
function parseString(s: string) {
s = s.replace(/\\\\/g, "\\B") // don't get confused by double backslash
.replace(/\\(['\?])/g, (f, q) => q) // these are not valid in JSON yet valid in C
.replace(/\\[z0]/g, "\u0000") // \0 is valid in C
.replace(/\\x([0-9a-f][0-9a-f])/gi, (f, h) => "\\u00" + h)
.replace(/\\B/g, "\\\\") // undo anti-confusion above
try {
return JSON.parse(s)
} catch (e) {
return null
}
}
export function emitErr(msg: string, tok: string) {
return {
stack: <number>null,
opcode: <number>null,
error: msg,
errorAt: tok
}
}
function testOne(ei: AbstractProcessor, op: string, code: number) {
let b = new File(ei)
b.checkStack = false;
b.emit(op)
assert(b.buf[0] == code)
}
export function expectError(ei: AbstractProcessor, asm: string) {
let b = new File(ei);
b.emit(asm);
if (b.errors.length == 0) {
oops("ASMTEST: expecting error for: " + asm)
}
// console.log(b.errors[0].message)
}
export function tohex(n: number) {
if (n < 0 || n > 0xffff)
return ("0x" + n.toString(16)).toLowerCase()
else
return ("0x" + ("000" + n.toString(16)).slice(-4)).toLowerCase()
}
export function expect(ei: AbstractProcessor, disasm: string) {
let exp: number[] = []
let asm = disasm.replace(/^([0-9a-fA-F]{4,8})\s/gm, (w, n) => {
exp.push(parseInt(n.slice(0, 4), 16))
if (n.length == 8)
exp.push(parseInt(n.slice(4, 8), 16))
return ""
})
let b = new File(ei);
b.throwOnError = true;
b.disablePeepHole = true;
b.emit(asm);
if (b.errors.length > 0) {
console.debug(b.errors[0].message)
oops("ASMTEST: not expecting errors")
}
if (b.buf.length != exp.length)
oops("ASMTEST: wrong buf len")
for (let i = 0; i < exp.length; ++i) {
if (b.buf[i] != exp[i])
oops("ASMTEST: wrong buf content at " + i + " , exp:" + tohex(exp[i]) + ", got: " + tohex(b.buf[i]))
}
}
} | the_stack |
import { Autowired, Injectable } from '@opensumi/di';
import {
AppConfig,
CommandRegistry,
CorePreferences,
Deferred,
ExtensionActivateEvent,
getPreferenceLanguageId,
IClientApp,
ILogger,
Disposable,
} from '@opensumi/ide-core-browser';
import { IProgressService } from '@opensumi/ide-core-browser/lib/progress';
import { localize, OnEvent, WithEventBus, ProgressLocation, ExtensionDidContributes } from '@opensumi/ide-core-common';
import { IExtensionStorageService } from '@opensumi/ide-extension-storage';
import { FileSearchServicePath, IFileSearchService } from '@opensumi/ide-file-search/lib/common';
import { IDialogService, IMessageService } from '@opensumi/ide-overlay';
import { IWorkspaceService } from '@opensumi/ide-workspace';
import {
ExtensionHostType,
ExtensionNodeServiceServerPath,
ExtensionService,
IExtensionNodeClientService,
IExtCommandManagement,
IExtensionMetaData,
LANGUAGE_BUNDLE_FIELD,
} from '../common';
import { ActivatedExtension } from '../common/activator';
import {
AbstractNodeExtProcessService,
AbstractViewExtProcessService,
AbstractWorkerExtProcessService,
} from '../common/extension.service';
import { isLanguagePackExtension, MainThreadAPIIdentifier } from '../common/vscode';
import { Extension } from './extension';
import {
ExtensionApiReadyEvent,
ExtensionDidEnabledEvent,
ExtensionBeforeActivateEvent,
ExtensionDidUninstalledEvent,
IActivationEventService,
AbstractExtInstanceManagementService,
ExtensionsInitializedEvent,
} from './types';
@Injectable()
export class ExtensionServiceImpl extends WithEventBus implements ExtensionService {
static extraMetadata = {
[LANGUAGE_BUNDLE_FIELD]: './package.nls.json',
};
@Autowired(ExtensionNodeServiceServerPath)
private readonly extensionNodeClient: IExtensionNodeClientService;
@Autowired(AppConfig)
private readonly appConfig: AppConfig;
@Autowired(CommandRegistry)
private readonly commandRegistry: CommandRegistry;
@Autowired(IActivationEventService)
private readonly activationEventService: IActivationEventService;
@Autowired(IWorkspaceService)
private readonly workspaceService: IWorkspaceService;
@Autowired(IExtensionStorageService)
private readonly extensionStorageService: IExtensionStorageService;
@Autowired(IProgressService)
private readonly progressService: IProgressService;
@Autowired(IDialogService)
private readonly dialogService: IDialogService;
@Autowired(IClientApp)
private readonly clientApp: IClientApp;
@Autowired(ILogger)
private readonly logger: ILogger;
@Autowired(IMessageService)
private readonly messageService: IMessageService;
@Autowired(CorePreferences)
private readonly corePreferences: CorePreferences;
@Autowired(AbstractWorkerExtProcessService)
private readonly workerExtensionService: AbstractWorkerExtProcessService;
@Autowired(AbstractNodeExtProcessService)
private readonly nodeExtensionService: AbstractNodeExtProcessService;
@Autowired(AbstractViewExtProcessService)
private readonly viewExtensionService: AbstractViewExtProcessService;
@Autowired(IExtCommandManagement)
private readonly extensionCommandManager: IExtCommandManagement;
@Autowired(AbstractExtInstanceManagementService)
private readonly extensionInstanceManageService: AbstractExtInstanceManagementService;
@Autowired(FileSearchServicePath)
private readonly fileSearchService: IFileSearchService;
/**
* 这里的 ready 是区分环境,将 node/worker 区分开使用
*/
private ready = new Map<string, Deferred<void>>();
// 存储 extension 的 meta 数据
private extensionMetaDataArr: IExtensionMetaData[];
// 插件进程是否正在重启中
private isExtProcessRestarting = false;
// 插件进程是否正在等待重启,页面不可见的时候被设置
private isExtProcessWaitingForRestart = false;
// 针对 activationEvents 为 * 的插件
public eagerExtensionsActivated: Deferred<void> = new Deferred();
/**
* @internal 提供获取所有运行中的插件的列表数据
*/
async getActivatedExtensions(): Promise<{ [key in ExtensionHostType]?: ActivatedExtension[] }> {
const activated = {};
if (this.nodeExtensionService.protocol) {
activated['node'] = await this.nodeExtensionService.getActivatedExtensions();
}
if (this.workerExtensionService.protocol) {
activated['worker'] = await this.workerExtensionService.getActivatedExtensions();
}
return activated;
}
/**
* 插件目录
* 主要为插件的读取目录
*/
private extensionScanDir = new Set<string>();
/**
* 补充的插件列表
* 主要为插件的读取路径
*/
private extensionCandidatePath = new Set<string>();
@OnEvent(ExtensionActivateEvent)
protected async onActivateExtension(e: ExtensionActivateEvent) {
await this.activationEventService.fireEvent(e.payload.topic, e.payload.data);
}
/**
* 插件激活后需更新插件进程数据
*/
@OnEvent(ExtensionDidEnabledEvent)
protected async onExtensionEnabled(e: ExtensionDidEnabledEvent) {
const extension = e.payload;
await this.updateExtHostData();
await this.fireActivationEventsIfNeed(extension.packageJSON.activationEvents);
}
/**
* 插件卸载后需更新插件进程数据
*/
@OnEvent(ExtensionDidUninstalledEvent)
protected async onExtensionUninstalled() {
await this.updateExtHostData();
}
public async activate(): Promise<void> {
await this.initExtensionMetaData();
await this.initExtensionInstanceData();
await this.runExtensionContributes();
this.doActivate();
// 监听页面展示状态,当页面状态变为可见且插件进程待重启的时候执行
const onPageVisibilitychange = () => {
if (
document.visibilityState === 'visible' &&
this.isExtProcessWaitingForRestart &&
!this.isExtProcessRestarting
) {
this.extProcessRestartHandler();
}
};
document.addEventListener('visibilitychange', onPageVisibilitychange, false);
this.addDispose(
Disposable.create(() => {
document.removeEventListener('visibilitychange', onPageVisibilitychange);
}),
);
}
/**
* 初始化插件列表数据
* 包括插件目录和插件 Candidate
* 以及 ExtensionMetaData
*/
private async initExtensionMetaData() {
const { extensionDir, extensionCandidate } = this.appConfig;
if (extensionDir) {
this.extensionScanDir.add(extensionDir);
}
if (extensionCandidate) {
extensionCandidate.forEach((extension) => {
this.extensionCandidatePath.add(extension.path);
});
}
this.extensionMetaDataArr = await this.getExtensionsMetaData(
Array.from(this.extensionScanDir),
Array.from(this.extensionCandidatePath),
);
this.logger.verbose('ExtensionMetaDataArr', this.extensionMetaDataArr);
}
/**
* 初始化插件实例数据
*/
private async initExtensionInstanceData() {
for (const extensionMetaData of this.extensionMetaDataArr) {
const isBuiltin = this.extensionInstanceManageService.checkIsBuiltin(extensionMetaData);
const isDevelopment = this.extensionInstanceManageService.checkIsDevelopment(extensionMetaData);
const extension = await this.extensionInstanceManageService.createExtensionInstance(
extensionMetaData,
isBuiltin,
isDevelopment,
);
if (extension) {
this.extensionInstanceManageService.addExtensionInstance(extension);
}
}
this.eventBus.fire(new ExtensionsInitializedEvent(this.extensionInstanceManageService.getExtensionInstances()));
const extensionInstanceList = this.extensionInstanceManageService.getExtensionInstances();
this.nodeExtensionService.updateExtensionData(extensionInstanceList);
this.workerExtensionService.updateExtensionData(extensionInstanceList);
this.viewExtensionService.initExtension(extensionInstanceList);
}
private async doActivate() {
await this.workspaceService.whenReady;
await this.extensionStorageService.whenReady;
await this.viewExtensionService.activate();
// 启动插件进程
await this.startExtProcess(true);
try {
await this.eventBus.fireAndAwait(new ExtensionBeforeActivateEvent());
await this.activationEventService.fireEvent('*');
} catch (err) {
this.logger.error(`[Extension Activate Error], \n ${err.message || err}`);
} finally {
// 表示 * 的插件全部激活完了
this.eagerExtensionsActivated.resolve();
this.activationEventService.fireEvent('onStartupFinished');
// 表示 * 的插件可以调了
this.eventBus.fire(new ExtensionApiReadyEvent());
}
}
/**
* 重启插件进程
*/
public async restartExtProcess() {
/**
* 只有在页面可见的情况下才执行插件进程重启操作
* 如果当前页面不可见,那么 chrome 会对 socket 进行限流,导致进程重启的 rpc 调用得不到返回从而卡住
*/
if (document.visibilityState === 'visible') {
this.extProcessRestartHandler();
} else {
this.isExtProcessWaitingForRestart = true;
}
}
private async extProcessRestartHandler() {
if (this.isExtProcessRestarting) {
return;
}
const restartProgress = () => {
this.progressService.withProgress(
{
location: ProgressLocation.Notification,
title: localize('extension.exthostRestarting.content'),
},
async () => {
try {
await this.startExtProcess(false);
} catch (err) {
this.logger.error(`[ext-restart]: ext-host restart failure, error: ${err}`);
}
this.isExtProcessRestarting = false;
this.isExtProcessWaitingForRestart = false;
},
);
};
this.isExtProcessRestarting = true;
if (this.isExtProcessWaitingForRestart) {
/**
* 只有当页面不可见的时候被通知执行重启操作,isExtProcessWaitingForRestart 才会为 true
* 目前观察到页面从不可见恢复至可见状态后,可能出现 socket 堆积的现象,因此延迟 1000ms 后再进行重启操作
* 这里延时并不能保证一定能够正确重启,只是降低失败的可能性。在解决了 socket 堆积的情况后,可以直接去掉
*/
setTimeout(restartProgress, 1000);
} else {
restartProgress();
}
}
private async startExtProcess(init: boolean) {
/**
* 重启插件进程步骤:
* 1、重置所有插件实例的状态至未激活
* 2、dispose 掉所有被激活且在 contributes 里申明过 browserView 的 sumi 插件
* 3、将负责前后端通信的 main.thread 全部 dispose 掉
* 4、杀掉后端插件进程
* 5、走正常激活插件流程,重新激活对应插件进程
* 6、将之前已经激活的插件重新激活一遍
*/
if (!init) {
this.resetExtensionInstances();
this.disposeSumiViewExtension();
await this.disposeExtProcess();
}
// set ready for node/worker
await Promise.all([this.startNodeExtHost(init), this.startWorkerExtHost(init)]);
if (!init) {
// 重启场景下需要将申明过 browserView 的 sumi 插件的 contributes 重新跑一遍
await this.rerunSumiViewExtensionContributes();
// 重启场景下把 ActivationEvent 再发一次
if (this.activationEventService.activatedEventSet.size) {
const activatedEventArr = Array.from(this.activationEventService.activatedEventSet);
this.activationEventService.activatedEventSet.clear();
await Promise.all(
activatedEventArr.map((event) => {
const { topic, data } = JSON.parse(event);
this.logger.verbose('fireEvent', 'event.topic', topic, 'event.data', data);
return this.activationEventService.fireEvent(topic, data);
}),
);
}
}
}
private async startNodeExtHost(init: boolean) {
// 激活 node 插件进程
if (!this.appConfig.noExtHost) {
const protocol = await this.nodeExtensionService.activate();
this.extensionCommandManager.registerProxyCommandExecutor(
'node',
protocol.get(MainThreadAPIIdentifier.MainThreadCommands),
);
if (init) {
this.ready.set('node', this.nodeExtensionService.ready);
}
}
}
private async startWorkerExtHost(init: boolean) {
// 激活 worker 插件进程
if (this.appConfig.extWorkerHost) {
try {
const protocol = await this.workerExtensionService.activate();
this.extensionCommandManager.registerProxyCommandExecutor(
'worker',
protocol.get(MainThreadAPIIdentifier.MainThreadCommands),
);
if (init) {
this.ready.set('worker', this.workerExtensionService.ready);
}
} catch (err) {
this.logger.error(`Worker host activate fail, \n ${err.message}`);
}
}
}
/**
* 更新插件进程中插件的数据
*/
private async updateExtHostData() {
const extensions = this.extensionInstanceManageService.getExtensionInstances();
if (!this.appConfig.noExtHost) {
await this.nodeExtensionService.updateExtensionData(extensions);
}
if (this.appConfig.extWorkerHost) {
await this.workerExtensionService.updateExtensionData(extensions);
}
}
/**
* 发送 ActivationEvents
*/
private async fireActivationEventsIfNeed(activationEvents: string[]) {
if (!Array.isArray(activationEvents) || !activationEvents.length) {
return;
}
const startUpActivationEvents = ['*', 'onStartupFinished'];
const _activationEvents = activationEvents.filter((event) => event !== '*');
const shouldFireEvents = Array.from(this.activationEventService.activatedEventSet)
.map((event) => JSON.parse(event))
.filter(({ topic, data }) => _activationEvents.find((_event) => _event === `${topic}:${data}`));
for (const event of startUpActivationEvents) {
if (activationEvents.includes(event)) {
this.logger.verbose(`Fire activation event ${event}`);
this.activationEventService.fireEvent(event);
}
}
for (const event of shouldFireEvents) {
const { topic, data } = event;
this.logger.verbose(`Fire activation event ${topic}:${data}`);
this.activationEventService.fireEvent(topic, data);
}
await this.activateByWorkspaceContains(activationEvents);
}
private async activateByWorkspaceContains(activationEvents: string[]) {
if (!Array.isArray(activationEvents) || !activationEvents.length) {
return;
}
const paths: string[] = [];
const includePatterns: string[] = [];
for (const activationEvent of activationEvents) {
if (/^workspaceContains:/.test(activationEvent)) {
const fileNameOrGlob = activationEvent.substr('workspaceContains:'.length);
if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0) {
includePatterns.push(fileNameOrGlob);
} else {
paths.push(fileNameOrGlob);
}
}
}
const promises: Promise<boolean>[] = [];
if (paths.length) {
promises.push(this.workspaceService.containsSome(paths));
}
if (includePatterns.length) {
promises.push(
(async () => {
try {
const result = await this.fileSearchService.find('', {
rootUris: this.workspaceService.tryGetRoots().map((r) => r.uri),
includePatterns,
limit: 1,
});
return result.length > 0;
} catch (e) {
this.logger.error(e);
return false;
}
})(),
);
}
if (promises.length && (await Promise.all(promises).then((exists) => exists.some((v) => v)))) {
this.activationEventService.fireEvent('workspaceContains', [...paths, ...includePatterns][0]);
}
}
/**
* 将插件的目录位置和文件位置,通过后端读取并缓存
* 返回所有插件的 meta data
*/
private async getExtensionsMetaData(
extensionScanDir: string[],
extensionCandidatePath: string[],
): Promise<IExtensionMetaData[]> {
if (!this.extensionMetaDataArr) {
const extensions = await this.extensionNodeClient.getAllExtensions(
extensionScanDir,
extensionCandidatePath,
getPreferenceLanguageId(),
ExtensionServiceImpl.extraMetadata,
);
this.extensionMetaDataArr = extensions;
}
return this.extensionMetaDataArr;
}
/**
* 激活插件的 Contributes
*/
private async runExtensionContributes() {
const extensions = Array.from(this.extensionInstanceManageService.getExtensionInstances() as Extension[]);
const languagePackExtensions: Extension[] = [];
const normalExtensions: Extension[] = [];
for (const extension of extensions) {
if (isLanguagePackExtension(extension.packageJSON)) {
languagePackExtensions.push(extension);
} else {
normalExtensions.push(extension);
}
}
// 优先执行 languagePack 的 contribute
await Promise.all(languagePackExtensions.map((languagePack) => languagePack.contributeIfEnabled()));
await Promise.all(normalExtensions.map((extension) => extension.contributeIfEnabled()));
// try fire workspaceContains activateEvent ,这里不要 await
Promise.all(
extensions.map((extension) => this.activateByWorkspaceContains(extension.packageJSON.activationEvents)),
).catch((error) => this.logger.error(error));
this.commandRegistry.beforeExecuteCommand(async (command, args) => {
await this.activationEventService.fireEvent('onCommand', command);
return args;
});
this.eventBus.fire(new ExtensionDidContributes());
}
/**
* 判断是否是 web 插件
* 这里会多增加一个判断:是否启动了 node-ext-host
* https://code.visualstudio.com/api/extension-guides/web-extensions#web-extension-enablement
*/
private whetherWebExtension({ packageJSON }: Extension): boolean {
const { browser, main } = packageJSON || {};
const noExtHost = Boolean(this.appConfig.noExtHost);
// 如果只包含 browser 入口
if (browser && !main) {
return true;
}
// 如果同时包含两个入口,那么判断是否启动了node插件进程
if (browser && main) {
return noExtHost;
}
// 只包含 main 入
if (!browser && main) {
return false;
}
/**
* 都不包含的情况下:
* 如果contributes中含有'debuggers', 'terminal', 'typescriptServerPlugins'三个之一,那么不作为web插件启动
* 如果不包含,那么判断是否启动了node插件进程
*/
if (typeof packageJSON.contributes !== 'undefined') {
for (const id of ['debuggers', 'terminal', 'typescriptServerPlugins']) {
if (packageJSON.contributes.hasOwnProperty(id)) {
return false;
}
}
}
return noExtHost;
}
/**
* 给 Extension 使用 | 激活插件
*/
public async activeExtension(extension: Extension) {
const isWebExtension = this.whetherWebExtension(extension);
if (isWebExtension && !this.appConfig.extWorkerHost) {
this.logger.error('[extension.service]: has no ext worker host');
}
// 优先激活 Node 和 Worker 进程中的插件
// 这个时序下,不允许存在 Node/Worker 互相依赖的情况
// 插件 Browser 中可以依赖 Node/Worker
await Promise.all([
this.nodeExtensionService.activeExtension(extension, isWebExtension),
this.workerExtensionService.activeExtension(extension, isWebExtension),
]);
await this.viewExtensionService.activeExtension(extension, this.nodeExtensionService.protocol);
}
private resetExtensionInstances() {
this.extensionInstanceManageService.resetExtensionInstances();
this.nodeExtensionService.disposeApiFactory();
this.workerExtensionService.disposeApiFactory();
}
/**
* 每次激活 sumi 插件的时候,都会尝试去激活 sumiContributes 中的 browserView,会导致 browserView 重复注册
* 因此重启场景下需要先将这部分被激活的插件 dispose 掉
*/
private disposeSumiViewExtension() {
const paths = Array.from(this.viewExtensionService.activatedViewExtensionMap.keys());
this.extensionInstanceManageService.disposeExtensionInstancesByPath(paths);
}
private async rerunSumiViewExtensionContributes() {
const { activatedViewExtensionMap } = this.viewExtensionService;
const extensionPaths = Array.from(activatedViewExtensionMap.keys());
await Promise.all(
extensionPaths.map((path) =>
this.extensionInstanceManageService.getExtensionInstanceByPath(path)?.contributeIfEnabled(),
),
);
activatedViewExtensionMap.clear();
}
async disposeExtProcess() {
await this.nodeExtensionService.disposeProcess();
await this.workerExtensionService.disposeProcess();
}
public async disposeExtensions() {
// 重置掉插件实例
this.extensionInstanceManageService.disposeExtensionInstances();
}
// 给 contributes#command 注册 command executor 使用
public async executeExtensionCommand(command: string, args: any[]): Promise<void> {
const targetEnv = this.extensionCommandManager.getExtensionCommandEnv(command);
if (!targetEnv) {
throw new Error('No Command with id "' + command + '" is declared by extensions');
}
// 需要等待对应插件进程启动完成再执行指令
await this.ready.get(targetEnv)?.promise;
// 这里相比之前有个变化,之前是先找 command 存不存在,然后等 ready 再执行
// 现在是先等 ready 再去找 command 再去执行
return this.extensionCommandManager.executeExtensionCommand(targetEnv, command, args);
}
// 暴露给后端调用前端时使用,用来处理插件进程不存在和 crash/restart 时的弹窗
private get invalidReloadStrategy() {
// 获取corePreferences配置判断是否弹出确认框
return this.corePreferences['application.invalidExthostReload'];
}
// RPC call from node
public async $restartExtProcess() {
await this.restartExtProcess();
}
public async $processNotExist() {
const okText = localize('extension.invalidExthostReload.confirm.ok');
const options = [okText];
const ifRequiredReload = this.invalidReloadStrategy === 'ifRequired';
if (ifRequiredReload) {
options.unshift(localize('extension.invalidExthostReload.confirm.cancel'));
}
const msg = await this.dialogService.info(
localize('extension.invalidExthostReload.confirm.content'),
options,
!!ifRequiredReload,
);
if (msg === okText) {
this.clientApp.fireOnReload();
}
}
public async $processCrashRestart() {
const okText = localize('common.yes');
const options = [okText];
const ifRequiredReload = this.invalidReloadStrategy === 'ifRequired';
if (ifRequiredReload) {
options.unshift(localize('common.no'));
}
const msg = await this.messageService.info(
localize('extension.crashedExthostReload.confirm'),
options,
!!ifRequiredReload,
);
if (msg === okText) {
await this.restartExtProcess();
}
}
} | the_stack |
import {
fragment,
logging,
normalize,
Path,
PathFragment,
schema,
tags,
virtualFs,
workspaces,
} from '@angular-devkit/core';
import * as chalk from 'chalk';
import { createConsoleLogger, NodeJsSyncHost } from '@angular-devkit/core/node';
import { Stats } from 'fs';
import { detectPackageManager } from '../shared/package-manager';
import { GenerateOptions } from './generate';
import { FileChange, Tree } from '../shared/tree';
import {
ProjectConfiguration,
RawWorkspaceJsonConfiguration,
toNewFormat,
toNewFormatOrNull,
toOldFormatOrNull,
workspaceConfigName,
WorkspaceJsonConfiguration,
} from '../shared/workspace';
import { dirname, extname, resolve, join, basename } from 'path';
import { FileBuffer } from '@angular-devkit/core/src/virtual-fs/host/interface';
import { EMPTY, Observable, of, concat, combineLatest } from 'rxjs';
import { catchError, map, switchMap, tap, toArray } from 'rxjs/operators';
import { NX_ERROR, NX_PREFIX } from '../shared/logger';
import { readJsonFile } from '../utils/fileutils';
import { parseJson, serializeJson } from '../utils/json';
import { NxJsonConfiguration } from '../shared/nx';
export async function scheduleTarget(
root: string,
opts: {
project: string;
target: string;
configuration: string;
runOptions: any;
executor: string;
},
verbose: boolean
): Promise<Observable<import('@angular-devkit/architect').BuilderOutput>> {
const { Architect } = require('@angular-devkit/architect');
const {
WorkspaceNodeModulesArchitectHost,
} = require('@angular-devkit/architect/node');
const logger = getTargetLogger(opts.executor, verbose);
const fsHost = new NxScopedHost(normalize(root));
const { workspace } = await workspaces.readWorkspace(
workspaceConfigName(root),
workspaces.createWorkspaceHost(fsHost)
);
const registry = new schema.CoreSchemaRegistry();
registry.addPostTransform(schema.transforms.addUndefinedDefaults);
const architectHost = new WorkspaceNodeModulesArchitectHost(workspace, root);
const architect = new Architect(architectHost, registry);
const run = await architect.scheduleTarget(
{
project: opts.project,
target: opts.target,
configuration: opts.configuration,
},
opts.runOptions,
{ logger }
);
return run.output;
}
function createWorkflow(
fsHost: virtualFs.Host<Stats>,
root: string,
opts: any
) {
const NodeWorkflow = require('@angular-devkit/schematics/tools').NodeWorkflow;
const workflow = new NodeWorkflow(fsHost, {
force: opts.force,
dryRun: opts.dryRun,
packageManager: detectPackageManager(),
root: normalize(root),
registry: new schema.CoreSchemaRegistry(
require('@angular-devkit/schematics').formats.standardFormats
),
resolvePaths: [process.cwd(), root],
});
workflow.registry.addPostTransform(schema.transforms.addUndefinedDefaults);
workflow.engineHost.registerOptionsTransform(
require('@angular-devkit/schematics/tools').validateOptionsWithSchema(
workflow.registry
)
);
if (opts.interactive) {
workflow.registry.usePromptProvider(createPromptProvider());
}
return workflow;
}
function getCollection(workflow: any, name: string) {
const collection = workflow.engine.createCollection(name);
if (!collection) throw new Error(`Cannot find collection '${name}'`);
return collection;
}
async function createRecorder(
host: NxScopedHost,
record: {
loggingQueue: string[];
error: boolean;
},
logger: logging.Logger
) {
const actualConfigName = await host.workspaceConfigName();
return (event: import('@angular-devkit/schematics').DryRunEvent) => {
let eventPath = event.path.startsWith('/')
? event.path.substr(1)
: event.path;
if (eventPath === 'workspace.json' || eventPath === 'angular.json') {
eventPath = actualConfigName;
}
if (event.kind === 'error') {
record.error = true;
logger.warn(
`ERROR! ${eventPath} ${
event.description == 'alreadyExist'
? 'already exists'
: 'does not exist.'
}.`
);
} else if (event.kind === 'update') {
record.loggingQueue.push(
tags.oneLine`${chalk.white('UPDATE')} ${eventPath}`
);
} else if (event.kind === 'create') {
record.loggingQueue.push(
tags.oneLine`${chalk.green('CREATE')} ${eventPath}`
);
} else if (event.kind === 'delete') {
record.loggingQueue.push(`${chalk.yellow('DELETE')} ${eventPath}`);
} else if (event.kind === 'rename') {
record.loggingQueue.push(
`${chalk.blue('RENAME')} ${eventPath} => ${event.to}`
);
}
};
}
async function runSchematic(
host: NxScopedHost,
root: string,
workflow: import('@angular-devkit/schematics/tools').NodeWorkflow,
logger: logging.Logger,
opts: GenerateOptions,
schematic: import('@angular-devkit/schematics').Schematic<
import('@angular-devkit/schematics/tools').FileSystemCollectionDescription,
import('@angular-devkit/schematics/tools').FileSystemSchematicDescription
>,
printDryRunMessage = true,
recorder: any = null
): Promise<{ status: number; loggingQueue: string[] }> {
const record = { loggingQueue: [] as string[], error: false };
workflow.reporter.subscribe(
recorder || (await createRecorder(host, record, logger))
);
try {
await workflow
.execute({
collection: opts.collectionName,
schematic: opts.generatorName,
options: opts.generatorOptions,
debug: opts.debug,
logger,
})
.toPromise();
} catch (e) {
console.log(e);
throw e;
}
if (!record.error) {
record.loggingQueue.forEach((log) => logger.info(log));
}
if (opts.dryRun && printDryRunMessage) {
logger.warn(`\nNOTE: The "dryRun" flag means no changes were made.`);
}
return { status: 0, loggingQueue: record.loggingQueue };
}
type AngularJsonConfiguration = WorkspaceJsonConfiguration &
Pick<NxJsonConfiguration, 'cli' | 'defaultProject' | 'generators'> & {
schematics?: NxJsonConfiguration['generators'];
};
export class NxScopedHost extends virtualFs.ScopedHost<any> {
constructor(root: Path) {
super(new NodeJsSyncHost(), root);
}
protected __readWorkspaceConfiguration = (
configFileName: ('workspace.json' | 'angular.json') & Path,
overrides?: {
workspace?: Observable<FileBuffer>;
nx?: Observable<FileBuffer>;
}
): Observable<FileBuffer> => {
return super.exists('nx.json' as Path).pipe(
switchMap((nxJsonExists) =>
(!nxJsonExists // if no nxJson, let it be undefined
? (overrides?.workspace || super.read(configFileName)).pipe(
map((x) => [x])
)
: combineLatest([
// read both values
overrides?.workspace || super.read(configFileName),
overrides?.nx || super.read('nx.json' as Path),
])
).pipe(
switchMap(([w, n]) => {
try {
// parse both from json, nxJson may be null
const workspaceJson: AngularJsonConfiguration = parseJson(
Buffer.from(w).toString()
);
const nxJson: NxJsonConfiguration | null = n
? parseJson(Buffer.from(n).toString())
: null;
// assign props ng cli expects from nx json, if it exists
workspaceJson.cli ??= nxJson?.cli;
workspaceJson.generators ??= nxJson?.generators;
workspaceJson.defaultProject ??= nxJson?.defaultProject;
// resolve inline configurations and downlevel format
return this.resolveInlineProjectConfigurations(
workspaceJson
).pipe(
map((x) => {
if (workspaceJson.version === 2) {
const formatted = toOldFormatOrNull(workspaceJson);
return formatted
? Buffer.from(serializeJson(formatted))
: Buffer.from(serializeJson(x));
}
return Buffer.from(serializeJson(x));
})
);
} catch {
return of(w);
}
})
)
)
);
};
read(path: Path): Observable<FileBuffer> {
return this.context(path).pipe(
switchMap((r) => {
if (r.isWorkspaceConfig) {
return this.__readWorkspaceConfiguration(r.actualConfigFileName);
} else {
return super.read(path);
}
})
);
}
write(path: Path, content: FileBuffer): Observable<void> {
return this.context(path).pipe(
switchMap((r) => {
if (r.isWorkspaceConfig) {
return this.writeWorkspaceConfiguration(r, content);
} else {
return super.write(path, content);
}
})
);
}
isFile(path: Path): Observable<boolean> {
return this.context(path).pipe(
switchMap((r) => {
if (r.isWorkspaceConfig) {
return super.isFile(r.actualConfigFileName);
} else {
return super.isFile(path);
}
})
);
}
exists(path: Path): Observable<boolean> {
return this.context(path).pipe(
switchMap((r) => {
if (r.isWorkspaceConfig) {
return super.exists(r.actualConfigFileName);
} else {
return super.exists(path);
}
})
);
}
workspaceConfigName(): Promise<string> {
return super
.exists('/angular.json' as any)
.pipe(
map((hasAngularJson) =>
hasAngularJson ? 'angular.json' : 'workspace.json'
)
)
.toPromise();
}
protected context(path: string): Observable<ChangeContext> {
if (isWorkspaceConfigPath(path)) {
return super.exists('/angular.json' as any).pipe(
switchMap((isAngularJson) => {
const actualConfigFileName = isAngularJson
? '/angular.json'
: '/workspace.json';
return super.read(actualConfigFileName as any).pipe(
map((r) => {
try {
const w = parseJson(Buffer.from(r).toString());
return {
isWorkspaceConfig: true,
actualConfigFileName,
isNewFormat: w.version === 2,
};
} catch {
return {
isWorkspaceConfig: true,
actualConfigFileName,
isNewFormat: false,
};
}
})
);
})
);
} else {
return of({
isWorkspaceConfig: false,
actualConfigFileName: null,
isNewFormat: false,
});
}
}
private writeWorkspaceConfiguration(
context: ChangeContext,
content
): Observable<void> {
const config = parseJson(Buffer.from(content).toString());
if (context.isNewFormat) {
try {
const w = parseJson(Buffer.from(content).toString());
const formatted: AngularJsonConfiguration = toNewFormatOrNull(w);
if (formatted) {
const { cli, generators, defaultProject, ...workspaceJson } =
formatted;
return concat(
this.writeWorkspaceConfigFiles(context, workspaceJson),
cli || generators || defaultProject
? this.__saveNxJsonProps({ cli, generators, defaultProject })
: of(null)
);
} else {
const {
cli,
schematics,
generators,
defaultProject,
...angularJson
} = w;
return concat(
this.writeWorkspaceConfigFiles(
context.actualConfigFileName,
angularJson
),
cli || schematics
? this.__saveNxJsonProps({
cli,
defaultProject,
generators: schematics || generators,
})
: of(null)
);
}
} catch (e) {}
}
const { cli, schematics, generators, defaultProject, ...angularJson } =
config;
return concat(
this.writeWorkspaceConfigFiles(context, angularJson),
this.__saveNxJsonProps({
cli,
defaultProject,
generators: schematics || generators,
})
);
}
private __saveNxJsonProps(
props: Partial<NxJsonConfiguration>
): Observable<void> {
const nxJsonPath = 'nx.json' as Path;
return super.read(nxJsonPath).pipe(
switchMap((buf) => {
const nxJson = parseJson(Buffer.from(buf).toString());
Object.assign(nxJson, props);
return super.write(nxJsonPath, Buffer.from(serializeJson(nxJson)));
})
);
}
private writeWorkspaceConfigFiles(
{ actualConfigFileName: workspaceFileName, isNewFormat }: ChangeContext,
config
) {
// copy to avoid removing inlined config files.
let writeObservable: Observable<void>;
const configToWrite = {
...config,
projects: { ...config.projects },
};
const projects: [string, any][] = Object.entries(configToWrite.projects);
for (const [project, projectConfig] of projects) {
if (projectConfig.configFilePath) {
if (!isNewFormat) {
throw new Error(
'Attempted to write standalone project configuration into a v1 workspace'
);
}
// project was read from a project.json file
const configPath = projectConfig.configFilePath;
const fileConfigObject = { ...projectConfig };
delete fileConfigObject.configFilePath; // remove the configFilePath before writing
const projectJsonWrite = super.write(
configPath,
Buffer.from(serializeJson(fileConfigObject))
); // write back to the project.json file
writeObservable = writeObservable
? concat(writeObservable, projectJsonWrite)
: projectJsonWrite;
configToWrite.projects[project] = normalize(dirname(configPath)); // update the config object to point to the written file.
}
}
const workspaceJsonWrite = super.write(
workspaceFileName,
Buffer.from(serializeJson(configToWrite))
);
return writeObservable
? concat(writeObservable, workspaceJsonWrite)
: workspaceJsonWrite;
}
protected resolveInlineProjectConfigurations(
config: RawWorkspaceJsonConfiguration
): Observable<WorkspaceJsonConfiguration> {
// Creates an observable where each emission is a project configuration
// that is not listed inside workspace.json. Each time it encounters a
// standalone config, observable is updated by concatenating the new
// config read operation.
let observable: Observable<any> = EMPTY;
Object.entries((config.projects as Record<string, any>) ?? {}).forEach(
([project, projectConfig]) => {
if (typeof projectConfig === 'string') {
// configFilePath is not written to files, but is stored on the config object
// so that we know where to save the project's configuration if it was updated
// by another angular schematic.
const configFilePath = join(projectConfig, 'project.json');
const next = this.read(configFilePath as Path).pipe(
map((x) => ({
project,
projectConfig: {
...parseJson(Buffer.from(x).toString()),
configFilePath,
},
}))
);
observable = observable ? concat(observable, next) : next;
}
}
);
return observable.pipe(
// Collect all values from the project.json read operations
toArray(),
// Use these collected values to update the inline configurations
map((x: any[]) => {
x.forEach(({ project, projectConfig }) => {
config.projects[project] = projectConfig;
});
return config as WorkspaceJsonConfiguration;
})
);
}
}
type ChangeContext = {
isWorkspaceConfig: boolean;
actualConfigFileName: any;
isNewFormat: boolean;
};
/**
* This host contains the workaround needed to run Angular migrations
*/
export class NxScopedHostForMigrations extends NxScopedHost {
constructor(root: Path) {
super(root);
}
read(path: Path): Observable<FileBuffer> {
if (isWorkspaceConfigPath(path)) {
return super.read(path).pipe(map(processConfigWhenReading));
} else {
return super.read(path);
}
}
write(path: Path, content: FileBuffer) {
if (isWorkspaceConfigPath(path)) {
return super.write(path, processConfigWhenWriting(content));
} else {
return super.write(path, content);
}
}
}
export class NxScopeHostUsedForWrappedSchematics extends NxScopedHost {
constructor(root: Path, private readonly host: Tree) {
super(root);
}
read(path: Path): Observable<FileBuffer> {
if (isWorkspaceConfigPath(path)) {
const match = findWorkspaceConfigFileChange(this.host);
const nxJsonChange = findMatchingFileChange(this.host, 'nx.json' as Path);
// no match, default to existing behavior
if (!match) {
return super.read(path);
}
// we try to format it, if it changes, return it, otherwise return the original change
try {
return this.__readWorkspaceConfiguration(match.path, {
workspace: of(match.content),
nx: nxJsonChange ? of(nxJsonChange.content) : null,
});
} catch (e) {
return super.read(path);
}
} else {
const match = findMatchingFileChange(this.host, path);
if (match) {
// found a matching change in the host
return of(Buffer.from(match.content));
} else if (
// found a change to workspace config, and reading a project config file
basename(path) === 'project.json' &&
findWorkspaceConfigFileChange(this.host)
) {
return of(this.host.read(path));
} else {
// found neither, use default read method
return super.read(path);
}
}
}
exists(path: Path): Observable<boolean> {
if (isWorkspaceConfigPath(path)) {
return findWorkspaceConfigFileChange(this.host)
? of(true)
: super.exists(path);
} else {
return findMatchingFileChange(this.host, path)
? of(true)
: super.exists(path);
}
}
isDirectory(path: Path): Observable<boolean> {
return super.isDirectory(path).pipe(
catchError(() => of(false)),
switchMap((isDirectory) =>
isDirectory
? of(true)
: of(this.host.exists(path) && !this.host.isFile(path))
)
);
}
isFile(path: Path): Observable<boolean> {
if (isWorkspaceConfigPath(path)) {
return findWorkspaceConfigFileChange(this.host)
? of(true)
: super.isFile(path);
} else {
return findMatchingFileChange(this.host, path)
? of(true)
: super.isFile(path);
}
}
list(path: Path): Observable<PathFragment[]> {
const fragments = this.host.children(path).map((child) => fragment(child));
return of(fragments);
}
}
type WorkspaceConfigFileChange = FileChange & {
path: ('workspace.json' | 'angular.json') & Path;
};
function findWorkspaceConfigFileChange(host: Tree): WorkspaceConfigFileChange {
return host
.listChanges()
.find(
(f) => f.path == 'workspace.json' || f.path == 'angular.json'
) as WorkspaceConfigFileChange;
}
function findMatchingFileChange(host: Tree, path: Path) {
const targetPath = path.startsWith('/') ? path.substring(1) : path.toString;
return host
.listChanges()
.find((f) => f.path == targetPath.toString() && f.type !== 'DELETE');
}
function isWorkspaceConfigPath(p: Path | string) {
return (
p === 'angular.json' ||
p === '/angular.json' ||
p === 'workspace.json' ||
p === '/workspace.json'
);
}
function processConfigWhenReading(content: ArrayBuffer) {
try {
const json = parseJson(Buffer.from(content).toString());
Object.values(json.projects).forEach((p: any) => {
try {
Object.values(p.architect || p.targets).forEach((e: any) => {
if (
(e.builder === '@nrwl/jest:jest' ||
e.executor === '@nrwl/jest:jest') &&
!e.options.tsConfig
) {
e.options.tsConfig = `${p.root}/tsconfig.spec.json`;
}
});
} catch (e) {}
});
return Buffer.from(serializeJson(json));
} catch (e) {
return content;
}
}
function processConfigWhenWriting(content: ArrayBuffer) {
try {
const json = parseJson(Buffer.from(content).toString());
Object.values(json.projects).forEach((p: any) => {
try {
Object.values(p.architect || p.targets).forEach((e: any) => {
if (
(e.builder === '@nrwl/jest:jest' ||
e.executor === '@nrwl/jest:jest') &&
e.options.tsConfig
) {
delete e.options.tsConfig;
}
});
} catch (e) {}
});
return Buffer.from(serializeJson(json));
} catch (e) {
return content;
}
}
export async function generate(
root: string,
opts: GenerateOptions,
verbose: boolean
) {
const logger = getLogger(verbose);
const fsHost = new NxScopedHost(normalize(root));
const workflow = createWorkflow(fsHost, root, opts);
const collection = getCollection(workflow, opts.collectionName);
const schematic = collection.createSchematic(opts.generatorName, true);
return (
await runSchematic(
fsHost,
root,
workflow,
logger as any,
{ ...opts, generatorName: schematic.description.name },
schematic
)
).status;
}
function createPromptProvider() {
interface Prompt {
name: string;
type: 'input' | 'select' | 'multiselect' | 'confirm' | 'numeral';
message: string;
initial?: any;
choices?: (string | { name: string; message: string })[];
validate?: (value: string) => boolean | string;
}
return (definitions: Array<any>) => {
const questions: Prompt[] = definitions.map((definition) => {
const question: Prompt = {
name: definition.id,
message: definition.message,
} as any;
if (definition.default) {
question.initial = definition.default;
}
const validator = definition.validator;
if (validator) {
question.validate = (input) => validator(input);
}
switch (definition.type) {
case 'string':
case 'input':
return { ...question, type: 'input' };
case 'boolean':
case 'confirmation':
case 'confirm':
return { ...question, type: 'confirm' };
case 'number':
case 'numeral':
return { ...question, type: 'numeral' };
case 'list':
return {
...question,
type: !!definition.multiselect ? 'multiselect' : 'select',
choices:
definition.items &&
definition.items.map((item) => {
if (typeof item == 'string') {
return item;
} else {
return {
message: item.label,
name: item.value,
};
}
}),
};
default:
return { ...question, type: definition.type };
}
});
return require('enquirer').prompt(questions);
};
}
export async function runMigration(
root: string,
packageName: string,
migrationName: string,
isVerbose: boolean
) {
const logger = getLogger(isVerbose);
const fsHost = new NxScopedHost(normalize(root));
const workflow = createWorkflow(fsHost, root, {});
const collection = resolveMigrationsCollection(packageName);
return workflow
.execute({
collection,
schematic: migrationName,
options: {},
debug: false,
logger: logger as any,
})
.toPromise();
}
function resolveMigrationsCollection(name: string): string {
let collectionPath: string | undefined = undefined;
if (name.startsWith('.') || name.startsWith('/')) {
name = resolve(name);
}
if (extname(name)) {
collectionPath = require.resolve(name);
} else {
let packageJsonPath;
try {
packageJsonPath = require.resolve(join(name, 'package.json'), {
paths: [process.cwd()],
});
} catch (e) {
// workaround for a bug in node 12
packageJsonPath = require.resolve(
join(process.cwd(), name, 'package.json')
);
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJson = require(packageJsonPath);
let pkgJsonSchematics =
packageJson['nx-migrations'] ?? packageJson['ng-update'];
if (!pkgJsonSchematics) {
throw new Error(`Could not find migrations in package: "${name}"`);
}
if (typeof pkgJsonSchematics != 'string') {
pkgJsonSchematics = pkgJsonSchematics.migrations;
}
collectionPath = require.resolve(pkgJsonSchematics, {
paths: [dirname(packageJsonPath)],
});
}
try {
if (collectionPath) {
readJsonFile(collectionPath);
return collectionPath;
}
} catch {
throw new Error(`Invalid migration file in package: "${name}"`);
}
throw new Error(`Collection cannot be resolved: "${name}"`);
}
function convertEventTypeToHandleMultipleConfigNames(
host: Tree,
eventPath: string,
content: Buffer | never
) {
const actualConfigName = host.exists('/angular.json')
? 'angular.json'
: 'workspace.json';
const isWorkspaceConfig =
eventPath === 'angular.json' || eventPath === 'workspace.json';
if (isWorkspaceConfig) {
let isNewFormat = true;
try {
isNewFormat =
parseJson(host.read(actualConfigName, 'utf-8')).version === 2;
} catch (e) {}
if (content && isNewFormat) {
const formatted = toNewFormat(parseJson(content.toString()));
if (formatted) {
return {
eventPath: actualConfigName,
content: Buffer.from(serializeJson(formatted)),
};
} else {
return { eventPath: actualConfigName, content };
}
} else {
return { eventPath: actualConfigName, content };
}
} else {
return { eventPath, content };
}
}
let collectionResolutionOverrides = null;
let mockedSchematics = null;
/**
* By default, Angular Devkit schematic collections will be resolved using the Node resolution.
* This doesn't work if you are testing schematics that refer to other schematics in the
* same repo.
*
* This function can can be used to override the resolution behaviour.
*
* Example:
*
* ```typescript
* overrideCollectionResolutionForTesting({
* '@nrwl/workspace': path.join(__dirname, '../../../../workspace/generators.json'),
* '@nrwl/angular': path.join(__dirname, '../../../../angular/generators.json'),
* '@nrwl/linter': path.join(__dirname, '../../../../linter/generators.json')
* });
*
* ```
*/
export function overrideCollectionResolutionForTesting(collections: {
[name: string]: string;
}) {
collectionResolutionOverrides = collections;
}
/**
* If you have an Nx Devkit generator invoking the wrapped Angular Devkit schematic,
* and you don't want the Angular Devkit schematic to run, you can mock it up using this function.
*
* Unfortunately, there are some edge cases in the Nx-Angular devkit integration that
* can be seen in the unit tests context. This function is useful for handling that as well.
*
* In this case, you can mock it up.
*
* Example:
*
* ```typescript
* mockSchematicsForTesting({
* 'mycollection:myschematic': (tree, params) => {
* tree.write('README.md');
* }
* });
*
* ```
*/
export function mockSchematicsForTesting(schematics: {
[name: string]: (
host: Tree,
generatorOptions: { [k: string]: any }
) => Promise<void>;
}) {
mockedSchematics = schematics;
}
export function wrapAngularDevkitSchematic(
collectionName: string,
generatorName: string
) {
return async (host: Tree, generatorOptions: { [k: string]: any }) => {
if (
mockedSchematics &&
mockedSchematics[`${collectionName}:${generatorName}`]
) {
return await mockedSchematics[`${collectionName}:${generatorName}`](
host,
generatorOptions
);
}
const emptyLogger = {
log: (e) => {},
info: (e) => {},
warn: (e) => {},
debug: () => {},
error: (e) => {},
fatal: (e) => {},
} as any;
emptyLogger.createChild = () => emptyLogger;
const recorder = (
event: import('@angular-devkit/schematics').DryRunEvent
) => {
let eventPath = event.path.startsWith('/')
? event.path.substr(1)
: event.path;
const r = convertEventTypeToHandleMultipleConfigNames(
host,
eventPath,
(event as any).content
);
if (event.kind === 'error') {
} else if (event.kind === 'update') {
if (
r.eventPath === 'angular.json' ||
r.eventPath === 'workspace.json'
) {
saveWorkspaceConfigurationInWrappedSchematic(host, r);
}
host.write(r.eventPath, r.content);
} else if (event.kind === 'create') {
host.write(r.eventPath, r.content);
} else if (event.kind === 'delete') {
host.delete(r.eventPath);
} else if (event.kind === 'rename') {
host.rename(r.eventPath, event.to);
}
};
const fsHost = new NxScopeHostUsedForWrappedSchematics(
normalize(host.root),
host
);
const options = {
generatorOptions,
dryRun: true,
interactive: false,
help: false,
debug: false,
collectionName,
generatorName,
force: false,
defaults: false,
};
const workflow = createWorkflow(fsHost, host.root, options);
// used for testing
if (collectionResolutionOverrides) {
const r = workflow.engineHost.resolve;
workflow.engineHost.resolve = (collection, b, c) => {
if (collectionResolutionOverrides[collection]) {
return collectionResolutionOverrides[collection];
} else {
return r.apply(workflow.engineHost, [collection, b, c]);
}
};
}
const collection = getCollection(workflow, collectionName);
const schematic = collection.createSchematic(generatorName, true);
const res = await runSchematic(
fsHost,
host.root,
workflow,
emptyLogger,
options,
schematic,
false,
recorder
);
if (res.status !== 0) {
throw new Error(res.loggingQueue.join('\n'));
}
};
}
export async function invokeNew(
root: string,
opts: GenerateOptions,
verbose: boolean
) {
const logger = getLogger(verbose);
const fsHost = new NxScopedHost(normalize(root));
const workflow = createWorkflow(fsHost, root, opts);
const collection = getCollection(workflow, opts.collectionName);
const schematic = collection.createSchematic('new', true);
return (
await runSchematic(
fsHost,
root,
workflow,
logger as any,
{ ...opts, generatorName: schematic.description.name },
schematic
)
).status;
}
let logger: logging.Logger;
const loggerColors: Partial<Record<logging.LogLevel, (s: string) => string>> = {
warn: (s) => chalk.bold(chalk.yellow(s)),
error: (s) => {
if (s.startsWith('NX ')) {
return `\n${NX_ERROR} ${chalk.bold(chalk.red(s.substr(3)))}\n`;
}
return chalk.bold(chalk.red(s));
},
info: (s) => {
if (s.startsWith('NX ')) {
return `\n${NX_PREFIX} ${chalk.bold(s.substr(3))}\n`;
}
return chalk.white(s);
},
};
export const getLogger = (isVerbose = false): logging.Logger => {
if (!logger) {
logger = createConsoleLogger(
isVerbose,
process.stdout,
process.stderr,
loggerColors
);
}
return logger;
};
const getTargetLogger = (
executor: string,
isVerbose = false
): logging.Logger => {
if (executor !== '@angular-devkit/build-angular:tslint') {
return getLogger(isVerbose);
}
const tslintExecutorLogger = createConsoleLogger(
isVerbose,
process.stdout,
process.stderr,
{
...loggerColors,
warn: (s) => {
if (
s.startsWith(
`TSLint's support is discontinued and we're deprecating its support in Angular CLI.`
)
) {
s =
`TSLint's support is discontinued and the @angular-devkit/build-angular:tslint executor is deprecated.\n` +
'To start using a modern linter tool, please consider replacing TSLint with ESLint. ' +
'You can use the "@nrwl/angular:convert-tslint-to-eslint" generator to automatically convert your projects.\n' +
'For more info, visit https://nx.dev/latest/angular/angular/convert-tslint-to-eslint.';
}
return chalk.bold(chalk.yellow(s));
},
}
);
return tslintExecutorLogger;
};
function saveWorkspaceConfigurationInWrappedSchematic(
host: Tree,
r: { eventPath: string; content: Buffer }
) {
const workspace: Omit<AngularJsonConfiguration, 'projects'> & {
projects: { [key: string]: string | { configFilePath?: string } };
} = parseJson(r.content.toString());
for (const [project, config] of Object.entries(workspace.projects)) {
if (typeof config === 'object' && config.configFilePath) {
const path = config.configFilePath;
workspace.projects[project] = normalize(dirname(path));
delete config.configFilePath;
host.write(path, serializeJson(config));
}
}
const nxJson: NxJsonConfiguration = parseJson(
host.read('nx.json').toString()
);
nxJson.generators = workspace.generators || workspace.schematics;
nxJson.cli = workspace.cli || nxJson.cli;
nxJson.defaultProject = workspace.defaultProject;
delete workspace.cli;
delete workspace.generators;
delete workspace.schematics;
r.content = Buffer.from(serializeJson(workspace));
} | the_stack |
import { XIdentity, XIdentityProperty, XBoolean, XIsEmpty, XNumber, XInputNumber, XWithConfig } from '@ng-nest/ui/core';
import { Input, Component, TemplateRef } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { XInputOption, XInputComponent } from '@ng-nest/ui/input';
import { XSelectOption, XSelectComponent } from '@ng-nest/ui/select';
import { XCascadeOption, XCascadeComponent } from '@ng-nest/ui/cascade';
import { XCheckboxOption, XCheckboxComponent } from '@ng-nest/ui/checkbox';
import { XColorPickerOption, XColorPickerComponent } from '@ng-nest/ui/color-picker';
import { XDatePickerOption, XDatePickerComponent } from '@ng-nest/ui/date-picker';
import { XInputNumberOption, XInputNumberComponent } from '@ng-nest/ui/input-number';
import { XRadioOption, XRadioComponent } from '@ng-nest/ui/radio';
import { XRateOption, XRateComponent } from '@ng-nest/ui/rate';
import { XSliderSelectOption, XSliderSelectComponent } from '@ng-nest/ui/slider-select';
import { XSwitchOption, XSwitchComponent } from '@ng-nest/ui/switch';
import { XTimePickerOption, XTimePickerComponent } from '@ng-nest/ui/time-picker';
import { XTextareaOption, XTextareaComponent } from '@ng-nest/ui/textarea';
import { XFindOption, XFindComponent } from '@ng-nest/ui/find';
import { XFormOption, XFormProp } from '@ng-nest/ui/base-form';
import { XAutoCompleteOption, XAutoCompleteComponent } from '@ng-nest/ui/auto-complete';
/**
* Form
* @selector x-form
* @decorator component
*/
export const XFormPrefix = 'x-form';
const X_CONFIG_NAME = 'form';
/**
* @zh_CN 模板
* @en_US Template
*/
export type XFormTemplate = { [property: string]: TemplateRef<any> };
/**
* Form Property
*/
@Component({ template: '' })
export class XFormProperty extends XFormProp {
/**
* @zh_CN 表单 FormGroup
* @en_US Form FormGroup
*/
@Input() formGroup: FormGroup = new FormGroup({});
/**
* @zh_CN 表单名称
* @en_US Form name
*/
@Input() title?: string;
/**
* @zh_CN 控件间距,单位rem
* @en_US Control spacing, unit rem
*/
@Input() @XWithConfig<XNumber>(X_CONFIG_NAME, 1) @XInputNumber() space?: XNumber;
/**
* @zh_CN 控件宽度,24栅格
* @en_US Control width, 24 grid
*/
@Input() @XInputNumber() span?: XNumber;
/**
* @zh_CN 标签后缀
* @en_US Label suffix
*/
@Input() @XWithConfig<XNumber>(X_CONFIG_NAME, '') labelSuffix?: string;
/**
* @zh_CN 表单控件
* @en_US Form control
*/
@Input() controls: XFormControlOption[] | XFormRow[] = [];
/**
* @zh_CN 表单宽度
* @en_US Form width
*/
@Input() @XWithConfig<string>(X_CONFIG_NAME, '100%') width: string = '100%';
/**
* @zh_CN 自定义模板
* @en_US Custom template
*/
@Input() controlTpl: XFormTemplate = {};
}
/**
* @zh_CN 控件对象
* @en_US Control object
*/
export interface XControlOption extends XIdentityProperty {
/**
* @zh_CN 值
* @en_US Value
*/
value?: any;
/**
* @zh_CN 控件类型
* @en_US Control type
*/
control?: XControlType;
/**
* @zh_CN 禁用
* @en_US Disabled
*/
disabled?: XBoolean;
/**
* @zh_CN 只读
* @en_US Read only
*/
readonly?: XBoolean;
/**
* @zh_CN 必填
* @en_US Required
*/
required?: XBoolean;
/**
* @zh_CN 隐藏
* @en_US Hide
*/
hidden?: XBoolean;
/**
* @zh_CN 列宽
* @en_US Column width
*/
span?: number;
/**
* @zh_CN 正则验证规则
* @en_US Regular validation rules
*/
pattern?: RegExp | RegExp[];
/**
* @zh_CN 验证不通过提示文字
* @en_US Verification failed prompt text
*/
message?: string | string[];
/**
* @zh_CN 外部改变事件
* @en_US External change event
*/
change?: () => void;
/**
* @zh_CN 自定义属性
* @en_US Custom attributes
*/
[property: string]: any;
}
/**
* @zh_CN 控件对象
* @en_US Control object
*/
export class XControl extends XIdentity implements XControlOption {
/**
* @zh_CN 值
* @en_US Value
*/
value?: any;
/**
* @zh_CN 控件类型
* @en_US Control type
*/
control?: XControlType;
/**
* @zh_CN 禁用
* @en_US Disabled
*/
disabled?: XBoolean;
/**
* @zh_CN 只读
* @en_US Read only
*/
readonly?: XBoolean;
/**
* @zh_CN 必填
* @en_US Required
*/
required?: XBoolean;
/**
* @zh_CN 隐藏
* @en_US Hide
*/
hidden?: XBoolean;
/**
* @zh_CN 列宽
* @en_US Column width
*/
span?: number;
/**
* @zh_CN 正则验证规则
* @en_US Regular validation rules
*/
pattern?: RegExp | RegExp[];
/**
* @zh_CN 验证不通过提示文字
* @en_US Verification failed prompt text
*/
message?: string | string[];
/**
* @zh_CN 外部改变事件
* @en_US External change event
*/
change?: () => void;
/**
* @zh_CN 设置验证
* @en_US Set verification
*/
setValidators?: () => void;
/**
* @zh_CN 自定义属性
* @en_US Custom attributes
*/
[property: string]: any;
constructor(option: XControlOption = {}) {
super();
if (XIsEmpty(this.value)) this.value = '';
Object.assign(this, option);
}
}
/**
* @zh_CN 表单行对象
* @en_US Form row object
*/
export interface XFormRow {
/**
* @zh_CN 行标题
* @en_US Row header
*/
title?: string;
/**
* @zh_CN 行图标
* @en_US Row icon
*/
icon?: string;
/**
* @zh_CN 行中的控件
* @en_US Control in row
*/
controls: XFormControlOption[];
/**
* @zh_CN 隐藏
* @en_US Hidden
*/
hidden?: XBoolean;
}
/**
* Control
* @selector x-control
* @decorator component
*/
export const XControlPrefix = 'x-control';
/**
* Control Property
*/
@Component({ template: '' })
export class XControlProperty {
/**
* @zh_CN 控件对象
* @en_US Control object
*/
@Input() option?: XControlOption;
}
export class XFormControl extends FormControl {
/**
* @zh_CN 提示信息
* @en_US Prompt information
*/
messages?: string[] = [];
}
export type XFormControlOption =
| XInputControlOption
| XSelectControlOption
| XCascadeControlOption
| XCheckboxControlOption
| XColorPickerControlOption
| XDatePickerControlOption
| XInputNumberControlOption
| XRadioControlOption
| XRateControlOption
| XSliderSelectControlOption
| XSwitchControlOption
| XTimePickerControlOption
| XFindControlOption
| XTemplateControlOption;
export type XFormControlComponent =
| XInputComponent
| XSelectComponent
| XCascadeComponent
| XCheckboxComponent
| XColorPickerComponent
| XDatePickerComponent
| XInputNumberComponent
| XRadioComponent
| XRateComponent
| XSliderSelectComponent
| XSwitchComponent
| XTimePickerComponent
| XTextareaComponent
| XFindComponent
| XAutoCompleteComponent;
export type XFormControlType =
| XInputControl
| XSelectControl
| XCascadeControl
| XCheckboxControl
| XColorPickerControl
| XDatePickerControl
| XInputNumberControl
| XRadioControl
| XRateControl
| XSliderSelectControl
| XSwitchControl
| XTimePickerControl
| XTextareaControl
| XFindControl
| XAutoCompleteControl;
export type XControlType =
| 'input'
| 'select'
| 'cascade'
| 'checkbox'
| 'color-picker'
| 'date-picker'
| 'input-number'
| 'radio'
| 'rate'
| 'slider-select'
| 'switch'
| 'time-picker'
| 'textarea'
| 'find'
| 'auto-complete'
| 'template';
/**
* Input Control
*/
export interface XInputControlOption extends XControlOption, XInputOption {}
export class XInputControl extends XControl {
constructor(option: XInputControlOption = {}) {
super(option);
}
}
/**
* Select Control
*/
export interface XSelectControlOption extends XControlOption, XSelectOption {}
export class XSelectControl extends XControl {
constructor(option: XSelectControlOption = {}) {
super(option);
}
}
/**
* Cascade Control
*/
export interface XCascadeControlOption extends XControlOption, XCascadeOption {}
export class XCascadeControl extends XControl {
constructor(option: XCascadeControlOption = {}) {
super(option);
}
}
/**
* Checkbox Control
*/
export interface XCheckboxControlOption extends XControlOption, XCheckboxOption {}
export class XCheckboxControl extends XControl {
constructor(option: XCheckboxControlOption = {}) {
super(option);
}
}
/**
* ColorPicker Control
*/
export interface XColorPickerControlOption extends XControlOption, XColorPickerOption {}
export class XColorPickerControl extends XControl {
constructor(option: XColorPickerControlOption = {}) {
super(option);
}
}
/**
* DatePicker Control
*/
export interface XDatePickerControlOption extends XControlOption, XDatePickerOption {}
export class XDatePickerControl extends XControl {
constructor(option: XDatePickerControlOption = {}) {
super(option);
}
}
/**
* InputNumber Control
*/
export interface XInputNumberControlOption extends XControlOption, XInputNumberOption {}
export class XInputNumberControl extends XControl {
constructor(option: XInputNumberControlOption = {}) {
super(option);
}
}
/**
* Radio Control
*/
export interface XRadioControlOption extends XControlOption, XRadioOption {}
export class XRadioControl extends XControl {
constructor(option: XRadioControlOption = {}) {
super(option);
}
}
/**
* Rate Control
*/
export interface XRateControlOption extends XControlOption, XRateOption {}
export class XRateControl extends XControl {
constructor(option: XRateControlOption = {}) {
super(option);
}
}
/**
* SliderSelect Control
*/
export interface XSliderSelectControlOption extends XControlOption, XSliderSelectOption {}
export class XSliderSelectControl extends XControl {
constructor(option: XSliderSelectControlOption = {}) {
super(option);
}
}
/**
* Switch Control
*/
export interface XSwitchControlOption extends XControlOption, XSwitchOption {}
export class XSwitchControl extends XControl {
constructor(option: XSwitchControlOption = {}) {
super(option);
}
}
/**
* TimePicker Control
*/
export interface XTimePickerControlOption extends XControlOption, XTimePickerOption {}
export class XTimePickerControl extends XControl {
constructor(option: XTimePickerControlOption = {}) {
super(option);
}
}
/**
* Textarea Control
*/
export interface XTextareaControlOption extends XControlOption, XTextareaOption {}
export class XTextareaControl extends XControl {
constructor(option: XTextareaControlOption = {}) {
super(option);
}
}
/**
* Find Control
*/
export interface XFindControlOption extends XControlOption, XFindOption {}
export class XFindControl extends XControl {
constructor(option: XFindControlOption = {}) {
super(option);
}
}
/**
* AutoComplete Control
*/
export interface XAutoCompleteControlOption extends XControlOption, XAutoCompleteOption {}
export class XAutoCompleteControl extends XControl {
constructor(option: XAutoCompleteControlOption = {}) {
super(option);
}
}
/**
* Template Control
*/
export interface XTemplateControlOption extends XControlOption, XFormOption {} | the_stack |
import React from 'react'
import { createMutator, updateMutator } from "../mutators";
import passport from 'passport'
import bcrypt from 'bcrypt'
import { createHash, randomBytes } from "crypto";
import GraphQLLocalStrategy from "./graphQLLocalStrategy";
import sha1 from 'crypto-js/sha1';
import { addGraphQLMutation, addGraphQLSchema, addGraphQLResolvers, } from "../../../lib/vulcan-lib";
import { getForwardedWhitelist } from "../../forwarded_whitelist";
import { LWEvents } from "../../../lib/collections/lwevents";
import Users from "../../../lib/vulcan-users";
import { hashLoginToken, userIsBanned } from "../../loginTokens";
import { LegacyData } from '../../../lib/collections/legacyData/collection';
import { AuthenticationError } from 'apollo-server'
import { EmailTokenType } from "../../emails/emailTokens";
import { wrapAndSendEmail } from '../../emails/renderEmail';
import SimpleSchema from 'simpl-schema';
import { userEmailAddressIsVerified } from '../../../lib/collections/users/helpers';
import { clearCookie } from '../../utils/httpUtil';
import { DatabaseServerSetting } from "../../databaseSettings";
import request from 'request';
import { forumTitleSetting } from '../../../lib/instanceSettings';
import { mongoFindOne } from '../../../lib/mongoQueries';
import { userFindByEmail } from '../../../lib/vulcan-users/helpers';
// Meteor hashed its passwords twice, once on the client
// and once again on the server. To preserve backwards compatibility
// with Meteor passwords, we do the same, but do it both on the server-side
function createMeteorClientSideHash(password: string) {
return createHash('sha256').update(password).digest('hex')
}
async function createPasswordHash(password: string) {
const meteorClientSideHash = createMeteorClientSideHash(password)
return await bcrypt.hash(meteorClientSideHash, 10)
}
async function comparePasswords(password: string, hash: string) {
return await bcrypt.compare(createMeteorClientSideHash(password), hash)
}
const passwordAuthStrategy = new GraphQLLocalStrategy(async function getUserPassport(username, password, done) {
const user = await Users.findOne({$or: [{'emails.address': username}, {username: username}]});
if (!user) return done(null, false, { message: 'Incorrect username.' });
// Load legacyData, if applicable. Needed because imported users had their
// passwords hashed differently.
// @ts-ignore -- legacyData isn't really handled right in our schemas.
const legacyData = user.legacyData ? user.legacyData : await LegacyData.findOne({ objectId: user._id })?.legacyData;
if (legacyData?.password && legacyData.password===password) {
// For legacy accounts, the bcrypt-hashed password stored in user.services.password.bcrypt
// is a hash of the LW1-hash of their password. Don't accept an LW1-hash as a password.
// (If passwords from the DB were ever leaked, this prevents logging into legacy accounts
// that never changed their password.)
return done(null, false, { message: 'Incorrect password.' });
}
const match = !!user.services.password.bcrypt && await comparePasswords(password, user.services.password?.bcrypt);
// If no immediate match, we check whether we have a match with their legacy password
if (!match) {
if (legacyData?.password) {
const salt = legacyData.password.substring(0,3)
const toHash = (`${salt}${user.username} ${password}`)
const lw1PW = salt + sha1(toHash).toString();
const lw1PWMatch = await comparePasswords(lw1PW, user.services.password.bcrypt);
if (lw1PWMatch) return done(null, user)
}
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user)
})
passport.use(passwordAuthStrategy)
function validatePassword(password:string): {validPassword: true} | {validPassword: false, reason: string} {
if (password.length < 6) return { validPassword: false, reason: "Your password needs to be at least 6 characters long"}
return { validPassword: true }
}
const loginData = `type LoginReturnData {
token: String
}`
addGraphQLSchema(loginData);
function promisifiedAuthenticate(req, res, name, options, callback) {
return new Promise((resolve, reject) => {
try {
passport.authenticate(name, options, async (err, user, info) => {
try {
const callbackResult = await callback(err, user, info);
resolve(callbackResult)
} catch(err) {
reject(err)
}
})(req, res)
} catch(err) {
reject(err)
}
})
}
export async function createAndSetToken(req, res, user) {
const token = randomBytes(32).toString('hex');
(res as any).setHeader("Set-Cookie", `loginToken=${token}; Max-Age=315360000; Path=/`);
const hashedToken = hashLoginToken(token)
await insertHashedLoginToken(user._id, hashedToken)
registerLoginEvent(user, req)
return token
}
const VerifyEmailToken = new EmailTokenType({
name: "verifyEmail",
onUseAction: async (user) => {
if (userEmailAddressIsVerified(user)) return {message: "Your email address is already verified"}
await updateMutator({
collection: Users,
documentId: user._id,
set: {
'emails.0.verified': true,
} as any,
unset: {},
validate: false,
});
return {message: "Your email has been verified" };
},
resultComponentName: "EmailTokenResult"
});
export async function sendVerificationEmail(user: DbUser) {
const verifyEmailLink = await VerifyEmailToken.generateLink(user._id);
await wrapAndSendEmail({
user,
subject: `Verify your ${forumTitleSetting.get()} email`,
body: <div>
<p>
Click here to verify your {forumTitleSetting.get()} email
</p>
<p>
<a href={verifyEmailLink}>
{verifyEmailLink}
</a>
</p>
</div>
})
}
const ResetPasswordToken = new EmailTokenType({
name: "resetPassword",
onUseAction: async (user, params, args) => {
if (!args) throw Error("Using a reset-password token requires providing a new password")
const { password } = args
const validatePasswordResponse = validatePassword(password)
if (!validatePasswordResponse.validPassword) throw Error(validatePasswordResponse.reason)
await updateMutator({
collection: Users,
documentId: user._id,
set: {
'services.password.bcrypt': await createPasswordHash(password),
'services.resume.loginTokens': []
} as any,
unset: {},
validate: false,
});
return {message: "Your new password has been set. Try logging in again." };
},
resultComponentName: "EmailTokenResult",
path: "resetPassword" // Defined in routes.ts
});
const authenticationResolvers = {
Mutation: {
async login(root: void, { username, password }: {username: string, password: string}, { req, res }: ResolverContext) {
let token:string | null = null
await promisifiedAuthenticate(req, res, 'graphql-local', { username, password }, (err, user, info) => {
return new Promise((resolve, reject) => {
if (err) throw Error(err)
if (!user) throw new AuthenticationError("Invalid username/password")
if (userIsBanned(user)) throw new AuthenticationError("This user is banned")
req!.logIn(user, async err => {
if (err) throw new AuthenticationError(err)
token = await createAndSetToken(req, res, user)
resolve(token)
})
})
})
return { token }
},
async logout(root: void, args: {}, { req, res }: ResolverContext) {
req!.logOut()
clearCookie(req, res, "loginToken");
clearCookie(req, res, "meteor_login_token");
return {
token: null
}
},
async signup(root: void, args, context: ResolverContext) {
const { email, username, password, subscribeToCurated, reCaptchaToken, abTestKey } = args;
if (!email || !username || !password) throw Error("Email, Username and Password are all required for signup")
if (!SimpleSchema.RegEx.Email.test(email)) throw Error("Invalid email address")
const validatePasswordResponse = validatePassword(password)
if (!validatePasswordResponse.validPassword) throw Error(validatePasswordResponse.reason)
if (await userFindByEmail(email)) {
throw Error("Email address is already taken");
}
if (await mongoFindOne("Users", { username })) {
throw Error("Username is already taken");
}
const reCaptchaResponse = await getCaptchaRating(reCaptchaToken)
const reCaptchaData = JSON.parse(reCaptchaResponse)
let recaptchaScore : number | undefined = undefined
if (reCaptchaData.success && reCaptchaData.action == "login/signup") {
recaptchaScore = reCaptchaData.score
} else {
// eslint-disable-next-line no-console
console.log("reCaptcha check failed:", reCaptchaData)
}
const { req, res } = context
const { data: user } = await createMutator({
collection: Users,
document: {
email,
services: {
password: {
bcrypt: await createPasswordHash(password)
},
resume: {
loginTokens: []
}
},
emails: [{
address: email, verified: false
}],
username: username,
emailSubscribedToCurated: subscribeToCurated,
signUpReCaptchaRating: recaptchaScore,
abTestKey,
},
validate: false,
currentUser: null,
context
})
const token = await createAndSetToken(req, res, user)
return {
token
}
},
async resetPassword(root: void, { email }: {email: string}, context: ResolverContext) {
if (!email) throw Error("Email is required for resetting passwords")
const user = await Users.findOne({'emails.address': email})
if (!user) throw Error("Can't find user with given email address")
const tokenLink = await ResetPasswordToken.generateLink(user._id)
const emailSucceeded = await wrapAndSendEmail({
user,
subject: "Password Reset Request",
body: <div>
<p>
You requested a password reset. Follow the following link to reset your password:
</p>
<p>
<a href={tokenLink}>{tokenLink}</a>
</p>
</div>
});
if (emailSucceeded)
return `Successfully sent password reset email to ${email}`; //FIXME: Is this revealing user emails that would otherwise be hidden?
else
return `Failed to send password reset email. The account might not have a valid email address configured.`;
},
async verifyEmail(root: void, { userId }: {userId: string}, context: ResolverContext) {
if (!userId) throw Error("User ID is required for validating your email")
const user = await Users.findOne({_id: userId})
if (!user) throw Error("Can't find user with given ID")
await sendVerificationEmail(user)
return `Successfully sent verification email to ${user.displayName}`
}
}
};
addGraphQLResolvers(authenticationResolvers);
addGraphQLMutation('login(username: String, password: String): LoginReturnData');
addGraphQLMutation('signup(username: String, email: String, password: String, subscribeToCurated: Boolean, reCaptchaToken: String, abTestKey: String): LoginReturnData');
addGraphQLMutation('logout: LoginReturnData');
addGraphQLMutation('resetPassword(email: String): String');
addGraphQLMutation('verifyEmail(userId: String): String');
async function insertHashedLoginToken(userId: string, hashedToken: string) {
const tokenWithMetadata = {
when: new Date(),
hashedToken
}
await Users.rawUpdateOne({_id: userId}, {
$addToSet: {
"services.resume.loginTokens": tokenWithMetadata
}
});
};
function registerLoginEvent(user, req) {
const document = {
name: 'login',
important: false,
userId: user._id,
properties: {
type: 'passport-login',
ip: getForwardedWhitelist().getClientIP(req),
userAgent: req.headers['user-agent'],
referrer: req.headers['referer']
}
}
void createMutator({
collection: LWEvents,
document: document,
currentUser: user,
validate: false,
})
}
const reCaptchaSecretSetting = new DatabaseServerSetting<string | null>('reCaptcha.secret', null) // ReCaptcha Secret
export const getCaptchaRating = async (token: string): Promise<string> => {
// Make an HTTP POST request to get reply text
return new Promise((resolve, reject) => {
request.post({url: 'https://www.google.com/recaptcha/api/siteverify',
form: {
secret: reCaptchaSecretSetting.get(),
response: token
}
},
function(err, httpResponse, body) {
if (err) reject(err);
return resolve(body);
}
);
});
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Manages a Log Analytics Storage Insights resource.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAnalyticsWorkspace = new azure.operationalinsights.AnalyticsWorkspace("exampleAnalyticsWorkspace", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* sku: "PerGB2018",
* retentionInDays: 30,
* });
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const exampleStorageInsights = new azure.loganalytics.StorageInsights("exampleStorageInsights", {
* resourceGroupName: exampleResourceGroup.name,
* workspaceId: exampleAnalyticsWorkspace.id,
* storageAccountId: exampleAccount.id,
* storageAccountKey: exampleAccount.primaryAccessKey,
* });
* ```
*
* ## Import
*
* Log Analytics Storage Insight Configs can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:loganalytics/storageInsights:StorageInsights example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.OperationalInsights/workspaces/workspace1/storageInsightConfigs/storageInsight1
* ```
*/
export class StorageInsights extends pulumi.CustomResource {
/**
* Get an existing StorageInsights resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: StorageInsightsState, opts?: pulumi.CustomResourceOptions): StorageInsights {
return new StorageInsights(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:loganalytics/storageInsights:StorageInsights';
/**
* Returns true if the given object is an instance of StorageInsights. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is StorageInsights {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === StorageInsights.__pulumiType;
}
/**
* The names of the blob containers that the workspace should read.
*/
public readonly blobContainerNames!: pulumi.Output<string[] | undefined>;
/**
* The name which should be used for this Log Analytics Storage Insights. Changing this forces a new Log Analytics Storage Insights to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* The name of the Resource Group where the Log Analytics Storage Insights should exist. Changing this forces a new Log Analytics Storage Insights to be created.
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* The ID of the Storage Account used by this Log Analytics Storage Insights.
*/
public readonly storageAccountId!: pulumi.Output<string>;
/**
* The storage access key to be used to connect to the storage account.
*/
public readonly storageAccountKey!: pulumi.Output<string>;
/**
* The names of the Azure tables that the workspace should read.
*/
public readonly tableNames!: pulumi.Output<string[] | undefined>;
/**
* A mapping of tags which should be assigned to the Log Analytics Storage Insights.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The ID of the Log Analytics Workspace within which the Storage Insights should exist. Changing this forces a new Log Analytics Storage Insights to be created.
*/
public readonly workspaceId!: pulumi.Output<string>;
/**
* Create a StorageInsights resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: StorageInsightsArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: StorageInsightsArgs | StorageInsightsState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as StorageInsightsState | undefined;
inputs["blobContainerNames"] = state ? state.blobContainerNames : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["storageAccountId"] = state ? state.storageAccountId : undefined;
inputs["storageAccountKey"] = state ? state.storageAccountKey : undefined;
inputs["tableNames"] = state ? state.tableNames : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["workspaceId"] = state ? state.workspaceId : undefined;
} else {
const args = argsOrState as StorageInsightsArgs | undefined;
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
if ((!args || args.storageAccountId === undefined) && !opts.urn) {
throw new Error("Missing required property 'storageAccountId'");
}
if ((!args || args.storageAccountKey === undefined) && !opts.urn) {
throw new Error("Missing required property 'storageAccountKey'");
}
if ((!args || args.workspaceId === undefined) && !opts.urn) {
throw new Error("Missing required property 'workspaceId'");
}
inputs["blobContainerNames"] = args ? args.blobContainerNames : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["storageAccountId"] = args ? args.storageAccountId : undefined;
inputs["storageAccountKey"] = args ? args.storageAccountKey : undefined;
inputs["tableNames"] = args ? args.tableNames : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["workspaceId"] = args ? args.workspaceId : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(StorageInsights.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering StorageInsights resources.
*/
export interface StorageInsightsState {
/**
* The names of the blob containers that the workspace should read.
*/
blobContainerNames?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The name which should be used for this Log Analytics Storage Insights. Changing this forces a new Log Analytics Storage Insights to be created.
*/
name?: pulumi.Input<string>;
/**
* The name of the Resource Group where the Log Analytics Storage Insights should exist. Changing this forces a new Log Analytics Storage Insights to be created.
*/
resourceGroupName?: pulumi.Input<string>;
/**
* The ID of the Storage Account used by this Log Analytics Storage Insights.
*/
storageAccountId?: pulumi.Input<string>;
/**
* The storage access key to be used to connect to the storage account.
*/
storageAccountKey?: pulumi.Input<string>;
/**
* The names of the Azure tables that the workspace should read.
*/
tableNames?: pulumi.Input<pulumi.Input<string>[]>;
/**
* A mapping of tags which should be assigned to the Log Analytics Storage Insights.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The ID of the Log Analytics Workspace within which the Storage Insights should exist. Changing this forces a new Log Analytics Storage Insights to be created.
*/
workspaceId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a StorageInsights resource.
*/
export interface StorageInsightsArgs {
/**
* The names of the blob containers that the workspace should read.
*/
blobContainerNames?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The name which should be used for this Log Analytics Storage Insights. Changing this forces a new Log Analytics Storage Insights to be created.
*/
name?: pulumi.Input<string>;
/**
* The name of the Resource Group where the Log Analytics Storage Insights should exist. Changing this forces a new Log Analytics Storage Insights to be created.
*/
resourceGroupName: pulumi.Input<string>;
/**
* The ID of the Storage Account used by this Log Analytics Storage Insights.
*/
storageAccountId: pulumi.Input<string>;
/**
* The storage access key to be used to connect to the storage account.
*/
storageAccountKey: pulumi.Input<string>;
/**
* The names of the Azure tables that the workspace should read.
*/
tableNames?: pulumi.Input<pulumi.Input<string>[]>;
/**
* A mapping of tags which should be assigned to the Log Analytics Storage Insights.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The ID of the Log Analytics Workspace within which the Storage Insights should exist. Changing this forces a new Log Analytics Storage Insights to be created.
*/
workspaceId: pulumi.Input<string>;
} | the_stack |
import {Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {AbstractComponent} from '@common/component/abstract.component';
import {CatalogService} from '../../catalog/service/catalog.service';
import {Alert} from '@common/util/alert.util';
import {Modal} from '@common/domain/modal';
import {DeleteModalComponent} from '@common/component/modal/delete/delete.component';
import {MetadataService} from '../service/metadata.service';
import {MetadataModelService} from '../service/metadata.model.service';
import {isUndefined} from 'util';
import * as _ from 'lodash';
@Component({
selector: 'app-select-catalog',
templateUrl: './select-catalog.component.html',
})
export class SelectCatalogComponent extends AbstractComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@ViewChild(DeleteModalComponent)
public deleteModalComponent: DeleteModalComponent;
// screen show/hide
public showFlag: boolean = false;
public catalogs: any;
public metadatas: any;
// selected cataglog
public selectedCatalog: Catalog;
public isCreateCatalog: boolean = false;
public isEditCatalogName: boolean = false;
// current root
public currentRoot: any = {name: 'Root', id: 'ROOT'};
// save path to go back
public catalogPath: any = [{name: 'Root', id: 'ROOT'}];
public selectedContentSort: Order = new Order();
public inProcess: boolean = false;
@ViewChild('catalogInput')
private catalogInput: ElementRef;
@ViewChild('newCatalogName')
private newCatalogName: ElementRef;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
constructor(
protected element: ElementRef,
protected catalogService: CatalogService,
protected metadataService: MetadataService,
protected metadataModelService: MetadataModelService,
protected injector: Injector) {
super(element, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// Init
public ngOnInit() {
// Init
super.ngOnInit();
}
// Destory
public ngOnDestroy() {
// Destory
super.ngOnDestroy();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* initialize popup
* @param isClose: close or open popup flag
*/
public init(isClose?: boolean) {
if (!isClose) {
this.showFlag = true;
this.currentRoot = {name: 'Root', id: 'ROOT'};
this.catalogPath = [{name: 'Root', id: 'ROOT'}];
// 정렬 초기화
this.selectedContentSort = new Order();
// page 초기화
this.selectedContentSort.key = 'createdTime';
this.selectedContentSort.sort = 'desc';
}
this.isCreateCatalog = false;
this.isEditCatalogName = false;
this.selectedCatalog = new Catalog();
this.catalogs = [];
this.metadatas = [];
this.getCatalogList();
}
/**
* Check if create new catalog is possible (upto 3 depth is possible)
*/
public isCreateAllowed() {
if (this.isCreateCatalog) {
return true;
} else return this.catalogPath.length === 4;
}
/**
* if new catalog button clicked, show input box to make new catalog
*/
public createCatalog() {
if (this.catalogPath.length === 4) {
return;
}
this.isCreateCatalog = true;
}
/**
* Call api to make new catalog
*/
public createCatalogDone() {
if (!isUndefined(this.newCatalogName.nativeElement.value) && this.newCatalogName.nativeElement.value.trim() !==
'') {
const params = {name: this.newCatalogName.nativeElement.value};
this.currentRoot.id !== 'ROOT' ? params['parentId'] = this.currentRoot.id : null;
if (this.inProcess === false) {
this.inProcess = true;
this.catalogService.createCatalog(params).then(() => {
this.init(true);
this.inProcess = false;
}).catch((error) => {
this.inProcess = false;
Alert.warning(error);
});
}
} else {
Alert.warning('Check catalog name');
}
}
public createCatalogByKeypress(event) {
if (event.keyCode === 13) {
this.createCatalogDone();
}
}
/**
* Check if root folder
*/
public isRoot() {
if (this.isCreateCatalog) {
return true;
} else {
return this.catalogPath.length !== 1;
}
}
/**
* When back button is clicked
*/
public goBack() {
this.isCreateCatalog ? this.isCreateCatalog = false : null;
if (this.catalogPath.length > 1) {
const ids = this.catalogPath.map((item) => {
return item.id;
});
const currentRootId = ids.indexOf(this.currentRoot.id);
this.currentRoot = this.catalogPath[currentRootId - 1];
this.catalogPath.splice(currentRootId, 1);
this.getCatalogList();
}
}
/**
* Rename catalog
* @param catalog
* @param index
*/
public updateCatalog(catalog, index) {
if (!isUndefined(this.catalogInput.nativeElement.value) && this.catalogInput.nativeElement.value.trim() !== '') {
const idx = this.catalogs.map((catalogItem, catalogIdx) => {
if (catalogIdx !== index) {
return catalogItem.name;
}
}).indexOf(this.catalogInput.nativeElement.value);
if (idx === -1) {
this.catalogService.updateCatalog(catalog.id, this.catalogInput.nativeElement.value).then(() => {
this.init(true);
this.getMetadataDetail();
}).catch((error) => {
Alert.error(error);
});
} else {
Alert.warning('Catalog already exists');
return;
}
} else {
catalog.editing = false;
}
} // function - updateCatalog
/**
* Cancel editing
* @param catalog
*/
public cancelEditing(catalog) {
if (catalog.editing) {
catalog.editing = false;
this.selectedCatalog = new Catalog();
}
} // function - cancelEditing
/**
* When catalog add button is clicked
*/
public addCatalog() {
if (isUndefined(this.selectedCatalog.name)) {
return;
} else {
const metadata = this.metadataModelService.getMetadata();
const idx = metadata.catalogs.map((item) => {
return item.id;
}).indexOf(this.selectedCatalog.id);
if (idx === -1) {
this.catalogPath.push({name: this.selectedCatalog.name, id: this.selectedCatalog.id});
this.metadataService.linkMetadataWithCatalog(metadata.id, this.selectedCatalog.id).then(() => {
this.showFlag = false;
Alert.success(this.translateService.instant('msg.comm.alert.save.success'));
this.getMetadataDetail();
this.init(true);
}).catch((error) => {
Alert.error(error);
});
} else {
this.showFlag = false;
Alert.success(this.translateService.instant('msg.comm.alert.save.success'));
this.init(true);
}
}
}
/**
* Metadata reload
*/
public getMetadataDetail() {
this.loadingShow();
this.metadataService.getDetailMetaData(this.metadataModelService.getMetadata().id).then((result) => {
this.loadingHide();
if (result) {
this.metadataModelService.setMetadata(result);
}
}).catch((error) => {
Alert.error(error);
this.loadingHide();
});
} // function - getMetadataDetail
/**
* Select Catalog
* @param catalog
*/
public selectCatalog(catalog) {
if (!catalog.editing) {
this.selectedCatalog = _.cloneDeep(catalog);
}
}
/**
* When '>' clicked load child metadata
* @param catalog
*/
public catalogDetail(catalog) {
this.currentRoot = {name: catalog.name, id: catalog.id};
this.catalogPath.push(this.currentRoot);
this.getCatalogList();
}
public getMetadataInCatalog(): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.catalogService.getMetadataInCatalog(this.selectedCatalog.id, this._getMetadataParams()).then((result) => {
this.pageResult.number === 0 && (this.metadatas = []);
// page 객체
this.pageResult = result.page;
// 컬럼 사전 리스트
this.metadatas = result['_embedded'] ? this.metadatas.concat(result['_embedded']['metadatas']) : [];
this.metadatas = this.metadatas.map((item) => {
return item.name;
});
resolve(this.metadatas);
}).catch((error) => {
reject(error);
});
});
}
/**
* Load Metadata List
*/
public getCatalogList() {
this.loadingShow();
this.catalogService.getTreeCatalogs(this.currentRoot.id).then((result) => {
this.loadingHide();
this.selectedCatalog = new Catalog();
this.catalogs = result;
if (this.currentRoot.id === 'ROOT') {
this.metadatas = [];
}
// this.getMetadataInCatalog();
}).catch((error) => {
Alert.error(error);
this.loadingHide();
});
}
/**
* Load child metadata
* @param catalogId
*/
public showChildren(catalogId: string) {
this.catalogService.getTreeCatalogs(catalogId).then((result) => {
console.log('하위 --> ', result);
}).catch((error) => {
Alert.error(error);
});
}
/**
* When edit metadata's name button clicked
* @param catalog
*/
public editCatalog(catalog) {
catalog.editing = true;
this.selectedCatalog = new Catalog();
this.isEditCatalogName = true;
}
/**
* Show delete metadata modal
*/
public confirmDelete(catalog) {
this.selectedCatalog = _.cloneDeep(catalog);
this.getMetadataInCatalog().then((result) => {
const modal = new Modal();
modal.name = `${this.translateService.instant('msg.metadata.catalog.delete.header',
{catalogName: catalog.name})}`;
if (result.length > 0) {
modal.name += ' ' + this.translateService.instant('msg.metadata.catalog.delete.header-plural');
}
// if data count is 1 ~ 3
if (result.length > 1 && result.length < 4) {
this.metadatas = `${result.join(', ')}`;
}
// if data count is more than 3
else if (result.length > 3) {
this.metadatas = `${result.splice(0, 3).join(', ')} ...`;
}
modal.btnName = this.translateService.instant('msg.comm.ui.del');
modal.description = `${this.metadatas}`;
this.deleteModalComponent.init(modal);
});
} // function - confirmDelete
/**
* Delete metadata complete ( when confirm button clicked in modal )
*/
public deleteCatalog() {
this.loadingShow();
const deletedName = this.selectedCatalog.name;
this.catalogService.deleteCatalog(this.selectedCatalog.id).then(() => {
Alert.success(`‘${deletedName}' is deleted.`);
this.loadingHide();
this.init();
this.getMetadataDetail();
}).catch((error) => {
this.loadingHide();
Alert.error(error);
});
}
public closeDelete() {
this.metadatas = [];
this.selectedCatalog = new Catalog();
}
/**
* get params for meta data list
* @returns object
* @private
*/
private _getMetadataParams(): object {
return {
size: 15,
page: 0,
sort: 'createdTime,desc',
};
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method - getter
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
}
class Catalog {
name: string;
id: string;
}
class Order {
key: string = 'logicalName';
sort: string = 'asc';
} | the_stack |
// *** WARNING: this file was generated by the pulumigen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi";
import * as path from "../../path";
import { getVersion } from "../../utilities";
import * as yaml from "../../yaml/index";
/**
* Chart is a component representing a collection of resources described by an arbitrary Helm
* Chart. The Chart can be fetched from any source that is accessible to the `helm` command
* line. Values in the `values.yml` file can be overridden using `ChartOpts.values` (equivalent
* to `--set` or having multiple `values.yml` files). Objects can be transformed arbitrarily by
* supplying callbacks to `ChartOpts.transformations`.
*
* `Chart` does not use Tiller. The Chart specified is copied and expanded locally; the semantics
* are equivalent to running `helm template` and then using Pulumi to manage the resulting YAML
* manifests. Any values that would be retrieved in-cluster are assigned fake values, and
* none of Tiller's server-side validity testing is executed.
*
* ## Example Usage
* ### Local Chart Directory
*
* ```typescript
* import * as k8s from "@pulumi/kubernetes";
*
* const nginxIngress = new k8s.helm.v3.Chart("nginx-ingress", {
* path: "./nginx-ingress",
* });
* ```
* ### Remote Chart
*
* ```typescript
* import * as k8s from "@pulumi/kubernetes";
*
* const nginxIngress = new k8s.helm.v3.Chart("nginx-ingress", {
* chart: "nginx-ingress",
* version: "1.24.4",
* fetchOpts:{
* repo: "https://charts.helm.sh/stable",
* },
* });
* ```
* ### Set Chart values
*
* ```typescript
* import * as k8s from "@pulumi/kubernetes";
*
* const nginxIngress = new k8s.helm.v3.Chart("nginx-ingress", {
* chart: "nginx-ingress",
* version: "1.24.4",
* fetchOpts:{
* repo: "https://charts.helm.sh/stable",
* },
* values: {
* controller: {
* metrics: {
* enabled: true,
* }
* }
* },
* });
* ```
* ### Deploy Chart into Namespace
*
* ```typescript
* import * as k8s from "@pulumi/kubernetes";
*
* const nginxIngress = new k8s.helm.v3.Chart("nginx-ingress", {
* chart: "nginx-ingress",
* version: "1.24.4",
* namespace: "test-namespace",
* fetchOpts:{
* repo: "https://charts.helm.sh/stable",
* },
* });
* ```
* ### Chart with Transformations
*
* ```typescript
* import * as k8s from "@pulumi/kubernetes";
*
* const nginxIngress = new k8s.helm.v3.Chart("nginx-ingress", {
* chart: "nginx-ingress",
* version: "1.24.4",
* fetchOpts:{
* repo: "https://charts.helm.sh/stable",
* },
* transformations: [
* // Make every service private to the cluster, i.e., turn all services into ClusterIP instead of LoadBalancer.
* (obj: any, opts: pulumi.CustomResourceOptions) => {
* if (obj.kind === "Service" && obj.apiVersion === "v1") {
* if (obj.spec && obj.spec.type && obj.spec.type === "LoadBalancer") {
* obj.spec.type = "ClusterIP";
* }
* }
* },
*
* // Set a resource alias for a previous name.
* (obj: any, opts: pulumi.CustomResourceOptions) => {
* if (obj.kind === "Deployment") {
* opts.aliases = [{ name: "oldName" }]
* },
*
* // Omit a resource from the Chart by transforming the specified resource definition to an empty List.
* (obj: any, opts: pulumi.CustomResourceOptions) => {
* if (obj.kind === "Pod" && obj.metadata.name === "test") {
* obj.apiVersion = "v1"
* obj.kind = "List"
* },
* ],
* });
* ```
*/
export class Chart extends yaml.CollectionComponentResource {
/**
* Create an instance of the specified Helm chart.
* @param releaseName Name of the Chart (e.g., nginx-ingress).
* @param config Configuration options for the Chart.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(
releaseName: string,
config: ChartOpts | LocalChartOpts,
opts?: pulumi.ComponentResourceOptions
) {
if (config.resourcePrefix !== undefined) {
releaseName = `${config.resourcePrefix}-${releaseName}`
}
const aliasOpts: pulumi.ComponentResourceOptions = {...opts, aliases: [{type:"kubernetes:helm.sh/v2:Chart"}]}
super("kubernetes:helm.sh/v3:Chart", releaseName, config, aliasOpts);
const allConfig = pulumi.output(config);
(<any>allConfig).isKnown.then((isKnown: boolean) => {
if (!isKnown) {
// Note that this can only happen during a preview.
pulumi.log.info("[Can't preview] all chart values must be known ahead of time to generate an " +
"accurate preview.", this);
}
});
this.resources = allConfig.apply(cfg => {
return this.parseChart(cfg, releaseName)
});
this.ready = this.resources.apply(m => Object.values(m));
}
parseChart(config: ChartOpts | LocalChartOpts, releaseName: string) {
const blob = {
...config,
releaseName,
toJSON() {
let obj: any = {};
for (const [key, value] of Object.entries(this)) {
if (value) {
switch(key) {
case "apiVersions": {
obj["api_versions"] = value;
break;
}
case "caFile": {
obj["ca_file"] = value;
break;
}
case "certFile": {
obj["cert_file"] = value;
break;
}
case "fetchOpts": {
obj["fetch_opts"] = value;
break;
}
case "includeTestHookResources": {
obj["include_test_hook_resources"] = value;
break;
}
case "skipCRDRendering": {
obj["skip_crd_rendering"] = value;
break;
}
case "releaseName": {
obj["release_name"] = value;
break;
}
case "resourcePrefix": {
obj["resource_prefix"] = value;
break;
}
case "untardir": {
obj["untar_dir"] = value;
break;
}
default: {
obj[key] = value;
}
}
}
}
return obj
}
}
const jsonOpts = JSON.stringify(blob)
const transformations: ((o: any, opts: pulumi.CustomResourceOptions) => void)[] = config.transformations ?? [];
if (config?.skipAwait) {
transformations.push(yaml.skipAwait);
}
// Rather than using the default provider for the following invoke call, use the version specified
// in package.json.
let invokeOpts: pulumi.InvokeOptions = { async: true, version: getVersion() };
const promise = pulumi.runtime.invoke("kubernetes:helm:template", {jsonOpts}, invokeOpts);
return pulumi.output(promise).apply<{[key: string]: pulumi.CustomResource}>(p => yaml.parse(
{
resourcePrefix: config.resourcePrefix,
objs: p.result,
transformations,
},
{ parent: this }
));
}
}
interface BaseChartOpts {
/**
* The optional kubernetes api versions used for Capabilities.APIVersions.
*/
apiVersions?: pulumi.Input<pulumi.Input<string>[]>;
/**
* By default, Helm resources with the `test`, `test-success`, and `test-failure` hooks are not installed. Set
* this flag to true to include these resources.
*/
includeTestHookResources?: boolean;
/**
* By default, CRDs are rendered along with Helm chart templates. Setting this to true will skip CRD rendering.
*/
skipCRDRendering?: boolean;
/**
* The optional namespace to install chart resources into.
*/
namespace?: pulumi.Input<string>;
/**
* Overrides for chart values.
*/
values?: pulumi.Inputs;
/**
* A set of transformations to apply to Kubernetes resource definitions before registering
* with engine.
*/
transformations?: ((o: any, opts: pulumi.CustomResourceOptions) => void)[];
/**
* An optional prefix for the auto-generated resource names.
* Example: A resource created with resourcePrefix="foo" would produce a resource named "foo-resourceName".
*/
resourcePrefix?: string
/**
* Skip await logic for all resources in this Chart. Resources will be marked ready as soon as they are created.
* Warning: This option should not be used if you have resources depending on Outputs from the Chart.
*/
skipAwait?: pulumi.Input<boolean>;
}
/**
* The set of arguments for constructing a Chart resource from a remote source.
*/
export interface ChartOpts extends BaseChartOpts {
/**
* The repository name of the chart to deploy.
* Example: "stable"
*/
repo?: pulumi.Input<string>;
/**
* The name of the chart to deploy. If [repo] is provided, this chart name will be prefixed by the repo name.
* Example: repo: "stable", chart: "nginx-ingress" -> "stable/nginx-ingress"
* Example: chart: "stable/nginx-ingress" -> "stable/nginx-ingress"
*/
chart: pulumi.Input<string>;
/**
* The version of the chart to deploy. If not provided, the latest version will be deployed.
*/
version?: pulumi.Input<string>;
/**
* Additional options to customize the fetching of the Helm chart.
*/
fetchOpts?: pulumi.Input<FetchOpts>;
}
function isChartOpts(o: any): o is ChartOpts {
return "chart" in o;
}
/**
* The set of arguments for constructing a Chart resource from a local source.
*/
export interface LocalChartOpts extends BaseChartOpts {
/**
* The path to the chart directory which contains the `Chart.yaml` file.
*/
path: string;
}
function isLocalChartOpts(o: any): o is LocalChartOpts {
return "path" in o;
}
/**
* Additional options to customize the fetching of the Helm chart.
*/
export interface FetchOpts {
/** Specific version of a chart. Without this, the latest version is fetched. */
version?: pulumi.Input<string>;
/** Verify certificates of HTTPS-enabled servers using this CA bundle. */
caFile?: pulumi.Input<string>;
/** Identify HTTPS client using this SSL certificate file. */
certFile?: pulumi.Input<string>;
/** Identify HTTPS client using this SSL key file. */
keyFile?: pulumi.Input<string>;
/**
* Location to write the chart. If this and tardir are specified, tardir is appended to this
* (default ".").
*/
destination?: pulumi.Input<string>;
/** Keyring containing public keys (default "/Users/alex/.gnupg/pubring.gpg"). */
keyring?: pulumi.Input<string>;
/** Chart repository password. */
password?: pulumi.Input<string>;
/** Chart repository url where to locate the requested chart. */
repo?: pulumi.Input<string>;
/**
* If untar is specified, this flag specifies the name of the directory into which the chart is
* expanded (default ".").
*/
untardir?: pulumi.Input<string>;
/** Chart repository username. */
username?: pulumi.Input<string>;
/** Location of your Helm config. Overrides $HELM_HOME (default "/Users/alex/.helm"). */
home?: pulumi.Input<string>;
/**
* Use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is
* ignored.
*/
devel?: pulumi.Input<boolean>;
/** Fetch the provenance file, but don't perform verification. */
prov?: pulumi.Input<boolean>;
/** If set to false, will leave the chart as a tarball after downloading. */
untar?: pulumi.Input<boolean>;
/** Verify the package against its signature. */
verify?: pulumi.Input<boolean>;
} | the_stack |
import { IDataSet } from '../../src/base/engine';
import { pivot_dataset } from '../base/datasource.spec';
import { PivotView } from '../../src/pivotview/base/pivotview';
import { createElement, remove, EmitType } from '@syncfusion/ej2-base';
import { GroupingBar } from '../../src/common/grouping-bar/grouping-bar';
import { FieldList } from '../../src/common/actions/field-list';
import { CalculatedField } from '../../src/common/calculatedfield/calculated-field';
import { ExcelExport, PDFExport } from '../../src/pivotview/actions';
import { ConditionalFormatting } from '../../src/common/conditionalformatting/conditional-formatting';
import { Toolbar } from '../../src/common/popups/toolbar';
import { PivotChart } from '../../src/pivotchart/index';
import * as util from '../utils.spec';
import { profile, inMB, getMemoryProfile } from '../common.spec';
describe('Pivot Grid Toolbar', () => {
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(' - Initial Rendering and Basic Operations', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:500px; width:100%' });
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
beforeAll((done: Function) => {
if (!document.getElementById(elem.id)) {
document.body.appendChild(elem);
}
let dataBound: EmitType<Object> = () => { done(); };
PivotView.Inject(FieldList, CalculatedField, Toolbar, ConditionalFormatting, PivotChart);
pivotGridObj = new PivotView({
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: true,
allowLabelFilter: true,
allowValueFilter: true,
rows: [{ name: 'product', caption: 'Items' }, { name: 'eyeColor' }],
columns: [{ name: 'gender', caption: 'Population' }, { name: 'isActive' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
filters: [],
},
displayOption: {
view: 'Both'
},
dataBound: dataBound,
saveReport: util.saveReport.bind(this),
fetchReport: util.fetchReport.bind(this),
loadReport: util.loadReport.bind(this),
removeReport: util.removeReport.bind(this),
renameReport: util.renameReport.bind(this),
newReport: util.newReport.bind(this),
toolbarRender: util.beforeToolbarRender.bind(this),
toolbar: ['New', 'Save', 'SaveAs', 'Rename', 'Remove', 'Load', 'ConditionalFormatting',
'Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'FieldList'],
allowExcelExport: true,
allowConditionalFormatting: true,
allowPdfExport: true,
showToolbar: true,
allowCalculatedField: true,
showFieldList: true
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('Toolbar initial render check', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelector('.e-pivot-toolbar') !== undefined).toBeTruthy();
(pivotGridObj.element.querySelector('.e-pivot-toolbar .e-save-report') as HTMLElement).click();
done();
}, 1000);
});
it('Save Report Dialog-check', () => {
expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display === 'none').toBeTruthy();
(document.querySelector('.e-pivot-toolbar .e-remove-report') as HTMLElement).click();
});
it('Remove Report Dialog - Cancel', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(window.getComputedStyle(document.querySelector('.e-pivot-error-dialog')).display !== 'none').toBeTruthy();
(document.querySelectorAll('.e-pivot-error-dialog .e-btn')[1] as HTMLElement).click();
done();
}, 1000);
});
// it('Save Report Dialog', (done: Function) => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display === 'none').toBeTruthy();
// (pivotGridObj.element.querySelector('.e-pivot-toolbar .e-save-report') as HTMLElement).click();
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[2] as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Save Report Dialog - Cancel', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display === 'none').toBeTruthy();
// (document.querySelector('.e-pivot-toolbar .e-save-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Save Report Dialog - OK', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[1] as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Save Report', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelector('.e-pivotview-report-input') as HTMLInputElement).value = "Report1";
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[1] as HTMLElement).click();
// (document.querySelector('.e-pivot-toolbar .e-save-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Save Report', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display === 'none').toBeTruthy();
// (document.querySelector('.e-pivot-toolbar .e-saveas-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Save As Report Dialog', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[2] as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Save As Report Dialog - Cancel', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display === 'none').toBeTruthy();
// (document.querySelector('.e-pivot-toolbar .e-saveas-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Save As Report Dialog - OK', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[1] as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Save As Report', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelector('.e-pivotview-report-input') as HTMLInputElement).value = "Report2";
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[1] as HTMLElement).click();
// (pivotGridObj.toolbarModule as any).action = 'Load';
// (document.querySelector('.e-pivot-toolbar .e-rename-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Rename Report Dialog', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[2] as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Rename Report Dialog - Cancel', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display === 'none').toBeTruthy();
// (document.querySelector('.e-pivot-toolbar .e-rename-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Rename Report Dialog - OK', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelector('.e-pivotview-report-input') as HTMLInputElement).value = "";
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[1] as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Rename Report', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivotview-report-dialog')).display !== 'none').toBeTruthy();
// (document.querySelector('.e-pivotview-report-input') as HTMLInputElement).value = "ReportRenamed";
// (document.querySelectorAll('.e-pivotview-report-dialog .e-btn')[1] as HTMLElement).click();
// (document.querySelector('.e-pivot-toolbar .e-remove-report') as HTMLElement).click();
// done();
// }, 2000);
// });
// it('Remove Report Dialog', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivot-error-dialog')).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivot-error-dialog .e-btn')[2] as HTMLElement).click();
// done();
// }, 2000);
// });
// it('Remove Report Dialog', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// (document.querySelector('.e-pivot-toolbar .e-remove-report') as HTMLElement).click();
// done();
// }, 2000);
// });
// it('Remove Report Dialog - Cancel', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivot-error-dialog')).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivot-error-dialog .e-btn')[1] as HTMLElement).click();
// done();
// }, 2000);
// });
// it('Remove Report Dialog - Cancel', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// (document.querySelector('.e-pivot-toolbar .e-toolbar-fieldlist') as HTMLElement).click();
// done();
// }, 2000);
// });
// it('Fieldlist', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// //expect(window.getComputedStyle(document.querySelector('.e-pivotfieldlist-container')).display !== 'none').toBeTruthy();
// (document.querySelector('.e-pivotfieldlist-container .e-cancel-btn') as HTMLElement).click();
// (document.querySelector('.e-pivot-toolbar .e-toolbar-formatting') as HTMLElement).click();
// done();
// }, 2000);
// });
// it('Conditional Formatting', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivot-formatting-dialog')).display !== 'none').toBeTruthy();
// (document.querySelector('.e-collapse') as HTMLElement).click();
// (document.querySelector('.e-pivot-formatting-dialog .e-format-cancel-button') as HTMLElement).click();
// (document.querySelector('.e-pivot-toolbar .e-new-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('New Report', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// expect(window.getComputedStyle(document.querySelector('.e-pivot-error-dialog')).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivot-error-dialog .e-btn')[2] as HTMLElement).click();
// done();
// }, 1000);
// });
// it('New Report', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// //expect(window.getComputedStyle(document.querySelector('.e-pivot-error-dialog')).display === 'none').toBeTruthy();
// (document.querySelector('.e-pivot-toolbar .e-remove-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Remove - Empty Report', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// //expect(window.getComputedStyle(document.querySelectorAll('.e-pivot-error-dialog')[1]).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivot-error-dialog .e-btn')[4] as HTMLElement).click();
// (document.querySelector('.e-pivot-toolbar .e-rename-report') as HTMLElement).click();
// done();
// }, 1000);
// });
// it('Remove - Rename Report', (done: Function) => {
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// setTimeout(() => {
// //expect(window.getComputedStyle(document.querySelectorAll('.e-pivot-error-dialog')[1]).display !== 'none').toBeTruthy();
// (document.querySelectorAll('.e-pivot-error-dialog .e-btn')[4] as HTMLElement).click();
// done();
// }, 1000);
// });
it('Export', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let li: HTMLElement = document.getElementById('PivotGridexport_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('PDF Export', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[0] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridexport_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Excel Export', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[1] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridexport_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('CSV Export', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[2] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridexport_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
done();
}, 1000);
});
it('Export', (done: Function) => {
PivotView.Inject(PDFExport, ExcelExport);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let li: HTMLElement = document.getElementById('PivotGridexport_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('PDF Export', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[0] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridexport_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Excel Export', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[1] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridexport_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('CSV Export', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[2] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridexport_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
done();
}, 1000);
});
it('Sub Total', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let li: HTMLElement = document.getElementById('PivotGridsubtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Sub Total - True', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[0] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridsubtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Sub Total - False', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[1] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridsubtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Sub Total - Row', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[2] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridsubtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Sub Total - Column', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[3] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridsubtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
done();
}, 1000);
});
it('Grand Total', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let li: HTMLElement = document.getElementById('PivotGridgrandtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Grand Total - True', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[0] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridgrandtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Grand Total - False', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[1] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridgrandtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Grand Total - Row', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[2] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridgrandtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Grand Total - Column', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
(document.querySelectorAll('.e-menu-popup li')[3] as HTMLElement).click();
let li: HTMLElement = document.getElementById('PivotGridgrandtotal_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
// pivotGridObj.toolbarModule.refreshToolbar();
done();
}, 1000);
});
});
describe(' - Chart and Grid with grouping bar', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:500px; width:100%' });
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
beforeAll((done: Function) => {
if (!document.getElementById(elem.id)) {
document.body.appendChild(elem);
}
let dataBound: EmitType<Object> = () => { done(); };
PivotView.Inject(Toolbar, PivotChart, GroupingBar, FieldList, CalculatedField);
pivotGridObj = new PivotView({
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: true,
allowLabelFilter: true,
allowValueFilter: true,
rows: [{ name: 'product', caption: 'Items' }, { name: 'eyeColor' }],
columns: [{ name: 'gender', caption: 'Population' }, { name: 'isActive' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
filters: [],
},
dataBound: dataBound,
saveReport: util.saveReport.bind(this),
fetchReport: util.fetchReport.bind(this),
loadReport: util.loadReport.bind(this),
removeReport: util.removeReport.bind(this),
renameReport: util.renameReport.bind(this),
newReport: util.newReport.bind(this),
toolbarRender: util.beforeToolbarRender.bind(this),
toolbar: ['New', 'Save', 'SaveAs', 'Rename', 'Remove', 'Load',
'Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'FieldList'],
allowExcelExport: true,
allowPdfExport: true,
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
showGroupingBar: true,
displayOption: { view: 'Both' }
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('Mouseover on chart icon', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelector('.e-pivot-toolbar') !== undefined).toBeTruthy();
expect((pivotGridObj.element.querySelector('.e-chart-grouping-bar') as HTMLElement).style.display === 'none').toBeTruthy();
let li: HTMLElement = document.getElementById('PivotGridchart_menu').children[0] as HTMLElement;
expect(li.classList.contains('e-menu-caret-icon')).toBeTruthy();
util.triggerEvent(li, 'mouseover');
done();
}, 1000);
});
it('Click Column Chart with chart grouping bar', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
(document.querySelectorAll('.e-menu-popup li')[0] as HTMLElement).click();
setTimeout(() => {
expect((document.querySelector('.e-grid') as HTMLElement).style.display).toBe('none');
expect((document.querySelector('.e-pivotchart') as HTMLElement).style.display === 'none').toBeFalsy();
expect(pivotGridObj.element.querySelector('.e-chart-grouping-bar')).toBeTruthy();
done();
}, 1000);
});
it('Switch to Grid with grouping bar', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
(document.querySelector('.e-pivot-toolbar .e-toolbar-grid') as HTMLElement).click();
setTimeout(() => {
//expect((document.querySelector('.e-pivotchart') as HTMLElement).style.display).toBe('none');
expect((document.querySelector('.e-grid') as HTMLElement).style.display === 'none').toBeFalsy();
expect(pivotGridObj.element.querySelector('.e-grouping-bar')).toBeTruthy();
pivotGridObj.displayOption.primary = 'Chart';
done();
}, 1000);
});
});
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 |
'use strict';
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs-extra';
import { IBlockchainQuickPickItem, UserInputUtil } from './UserInputUtil';
import { FabricGatewayConnectionManager } from '../fabric/FabricGatewayConnectionManager';
import { TransactionTreeItem } from '../explorer/model/TransactionTreeItem';
import { Reporter } from '../util/Reporter';
import { VSCodeBlockchainOutputAdapter } from '../logging/VSCodeBlockchainOutputAdapter';
import { ExtensionCommands } from '../../ExtensionCommands';
import { VSCodeBlockchainDockerOutputAdapter } from '../logging/VSCodeBlockchainDockerOutputAdapter';
import { InstantiatedTreeItem } from '../explorer/model/InstantiatedTreeItem';
import { IFabricGatewayConnection, LogType, FabricGatewayRegistryEntry, FabricEnvironmentRegistryEntry, FabricEnvironmentRegistry, EnvironmentType } from 'ibm-blockchain-platform-common';
import { FabricDebugConfigurationProvider } from '../debug/FabricDebugConfigurationProvider';
import { GlobalState, ExtensionData } from '../util/GlobalState';
interface ITransactionData {
transactionName: string;
transactionLabel?: string;
arguments: string[];
transientData: any;
}
function validateTxnDataObject(txnDataObject: ITransactionData): ITransactionData {
let args: Array<string>;
let transientData: { [key: string]: Buffer };
if (txnDataObject.arguments) {
args = txnDataObject.arguments.map((arg: any) => typeof arg !== 'string' ? JSON.stringify(arg) : arg);
} else {
args = [];
}
transientData = txnDataObject.transientData || {};
const keys: Array<string> = Array.from(Object.keys(transientData));
if (keys.length > 0) {
keys.forEach((key: string) => {
transientData[key] = Buffer.from(transientData[key]);
});
}
return { ...txnDataObject, arguments: args, transientData };
}
async function createArgs(transactionObject: any): Promise<Array<string>> {
let argsString: string;
if (transactionObject && transactionObject.args) {
if (Array.isArray(transactionObject.args)) {
return transactionObject.args;
}
argsString = transactionObject.args;
} else {
argsString = await UserInputUtil.showInputBox('optional: What are the arguments to the transaction, (e.g. ["arg1", "arg2"])', '[]');
}
if (argsString === undefined) {
throw new Error('transaction cancelled');
} else if (argsString === '') {
return [];
} else {
argsString = argsString.trim();
if (!argsString.startsWith('[') || !argsString.endsWith(']')) {
throw new Error('transaction arguments should be in the format ["arg1", {"arg2key" : "arg2value"}]');
}
const args: Array<string> = JSON.parse(argsString);
args.forEach((arg: any, index: number) => {
if ((typeof arg !== 'string')) {
args[index] = JSON.stringify(arg);
}
});
return args;
}
}
export async function submitTransaction(evaluate: boolean, treeItem?: InstantiatedTreeItem | TransactionTreeItem, channelName?: string, smartContract?: string, transactionObject?: any): Promise<void | string> {
const outputAdapter: VSCodeBlockchainOutputAdapter = VSCodeBlockchainOutputAdapter.instance();
let action: string;
let actioning: string;
let actioned: string;
if (evaluate) {
action = 'evaluate';
actioning = 'evaluating';
actioned = 'evaluated';
} else {
action = 'submit';
actioning = 'submitting';
actioned = 'submitted';
}
outputAdapter.log(LogType.INFO, undefined, `${action}Transaction`);
let transactionName: string;
let namespace: string;
let args: Array<string>;
let transientData: { [key: string]: Buffer };
let peerTargetNames: string[] = [];
let peerTargetMessage: string = '';
let gatewayRegistryEntry: FabricGatewayRegistryEntry;
let errorMessage: string;
let connection: IFabricGatewayConnection;
if (transactionObject) {
channelName = transactionObject.channelName;
smartContract = transactionObject.smartContract;
transactionName = transactionObject.transactionName;
namespace = transactionObject.namespace;
} else if (treeItem instanceof TransactionTreeItem) {
smartContract = treeItem.chaincodeName;
transactionName = treeItem.name;
channelName = treeItem.channelName;
namespace = treeItem.contractName;
} else {
if (!treeItem && !channelName && !smartContract) {
if (!FabricGatewayConnectionManager.instance().getConnection()) {
await vscode.commands.executeCommand(ExtensionCommands.CONNECT_TO_GATEWAY);
if (!FabricGatewayConnectionManager.instance().getConnection()) {
// either the user cancelled or there was an error so don't carry on
return;
}
}
const chosenChannel: IBlockchainQuickPickItem<Array<string>> = await UserInputUtil.showChannelFromGatewayQuickPickBox(`Choose a channel to select a smart contract from`);
if (!chosenChannel) {
return;
}
channelName = chosenChannel.label;
const chosenSmartContract: IBlockchainQuickPickItem<{ name: string, channel: string, version: string }> = await UserInputUtil.showClientInstantiatedSmartContractsQuickPick(`Choose a smart contract to ${action} a transaction from`, channelName);
if (!chosenSmartContract) {
return;
}
smartContract = chosenSmartContract.data.name;
} else if (treeItem instanceof InstantiatedTreeItem) {
channelName = treeItem.channels[0].label;
smartContract = treeItem.name;
}
const chosenTransaction: IBlockchainQuickPickItem<{ name: string, contract: string }> = await UserInputUtil.showTransactionQuickPick(`Choose a transaction to ${action}`, smartContract, channelName);
if (!chosenTransaction) {
return;
} else {
transactionName = chosenTransaction.data.name;
namespace = chosenTransaction.data.contract;
}
}
const debugSession: vscode.DebugSession = vscode.debug.activeDebugSession;
if (debugSession && debugSession.configuration.debugEvent === FabricDebugConfigurationProvider.debugEvent) {
// This will catch when the user is debugging 2-orgs, select 'Org2' to debug for, disconnect from the gateway, connect to 'Org1' and then try to submit from tree / command (but not debugList)
// Connect to the gateway for the org that was selected when debug was started.
const connected: boolean = await FabricDebugConfigurationProvider.connectToGateway();
if (!connected) {
return;
}
// If the user decides to disconnect later in the flow - then that means they've manually disconnected, and it'll be too late to connect to the correct gateway.
}
gatewayRegistryEntry = await FabricGatewayConnectionManager.instance().getGatewayRegistryEntry();
let associatedTestData: {chaincodeName: string, transactionDataPath: string};
if (gatewayRegistryEntry.transactionDataDirectories) {
associatedTestData = gatewayRegistryEntry.transactionDataDirectories.find((item: {chaincodeName: string, channelName: string, transactionDataPath: string}) => {
return item.chaincodeName === smartContract && item.channelName === channelName;
});
}
if (associatedTestData) {
if (transactionObject) {
// if no txDataFile is given then the Transaction View has made a request using manual inputted data
if (transactionObject.txDataFile) {
// If txDataFile is sent, the transaction was read from file - it should've been sent with args and transient data
const validatedTxnDataObject: ITransactionData = validateTxnDataObject({ transactionName, arguments: transactionObject.args, transientData: transactionObject.transientData });
args = validatedTxnDataObject.arguments;
transientData = validatedTxnDataObject.transientData;
}
} else {
const testDataDirPath: string = associatedTestData.transactionDataPath;
const quickPickItems: IBlockchainQuickPickItem<ITransactionData>[] = [];
const allFiles: string[] = await fs.readdir(testDataDirPath);
const txDataFiles: string[] = allFiles.filter((file: string) => file.endsWith('.txdata'));
if (txDataFiles.length > 0) {
for (const file of txDataFiles) {
try {
const fileJson: ITransactionData[] = await fs.readJSON(path.join(testDataDirPath, file));
fileJson.forEach((txn: ITransactionData) => {
if (txn.transactionName === transactionName) {
quickPickItems.push({
label: file,
description: txn.transactionLabel || '',
data: txn
});
}
});
} catch (error) {
errorMessage = `Error with transaction file ${file}: ${error.message}`;
outputAdapter.log(LogType.ERROR, errorMessage);
}
}
// shouldn't show quickpick if there is no valid transaction data to submit
if (quickPickItems.length > 0) {
quickPickItems.push({
label: 'No (manual entry)',
description: '',
data: undefined
});
const chosenTransaction: IBlockchainQuickPickItem = await UserInputUtil.showQuickPickItem('Do you want to provide a file of transaction data for this transaction?', quickPickItems, false) as IBlockchainQuickPickItem;
if (!chosenTransaction ) {
return;
} else if (chosenTransaction.label !== 'No (manual entry)') {
const txnDataObject: ITransactionData = validateTxnDataObject(chosenTransaction.data);
args = txnDataObject.arguments;
transientData = txnDataObject.transientData;
}
}
}
}
}
if (args === undefined) {
try {
args = await createArgs(transactionObject);
} catch (error) {
errorMessage = `Error with transaction arguments: ${error.message}`;
outputAdapter.log(LogType.ERROR, errorMessage);
return transactionObject ? errorMessage : undefined;
}
}
if (!transientData) {
try {
let transientDataString: string;
if (transactionObject) {
transientDataString = transactionObject.transientData;
} else {
transientDataString = await UserInputUtil.showInputBox('optional: What is the transient data for the transaction, e.g. {"key": "value"}', '{}');
}
if (transientDataString === undefined) {
return;
} else if (transientDataString !== '' && transientDataString !== '{}') {
transientDataString = transientDataString.trim();
if (!transientDataString.startsWith('{') || !transientDataString.endsWith('}')) {
throw new Error('transient data should be in the format {"key": "value"}');
}
transientData = JSON.parse(transientDataString);
const keys: Array<string> = Array.from(Object.keys(transientData));
keys.forEach((key: string) => {
transientData[key] = Buffer.from(transientData[key]);
});
}
} catch (error) {
errorMessage = `Error with transaction transient data: ${error.message}`;
outputAdapter.log(LogType.ERROR, errorMessage);
return transactionObject ? errorMessage : undefined;
}
}
connection = FabricGatewayConnectionManager.instance().getConnection();
const channelPeerInfo: {name: string, mspID: string}[] = await connection.getChannelPeersInfo(channelName);
let selectPeers: string;
if (transactionObject) {
peerTargetNames = transactionObject.peerTargetNames;
peerTargetMessage = peerTargetNames.length ? ` to peers ${peerTargetNames}` : '';
} else {
if (channelPeerInfo.length === 0) {
outputAdapter.log(LogType.ERROR, `No channel peers available to target`);
return;
} else if (channelPeerInfo.length === 1) {
selectPeers = UserInputUtil.DEFAULT;
peerTargetNames.push(channelPeerInfo[0].name);
} else {
selectPeers = await UserInputUtil.showQuickPick('Select a peer-targeting policy for this transaction', [UserInputUtil.DEFAULT, UserInputUtil.CUSTOM]) as string;
}
if (!selectPeers) {
return;
} else if (selectPeers === UserInputUtil.CUSTOM) {
const peerTargets: Array<IBlockchainQuickPickItem<string>> = await UserInputUtil.showChannelPeersQuickPick(channelPeerInfo);
if (!peerTargets || peerTargets.length === 0) {
return;
} else {
peerTargetNames = peerTargets.map((peer: IBlockchainQuickPickItem<string>) => {
return peer.data;
});
peerTargetMessage = ` to peers ${peerTargetNames}`;
}
}
}
return await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'IBM Blockchain Platform Extension',
cancellable: false
}, async (progress: vscode.Progress<{ message: string }>) => {
try {
progress.report({ message: `${actioning} transaction ${transactionName}` });
if (args.length === 0) {
outputAdapter.log(LogType.INFO, undefined, `${actioning} transaction ${transactionName} with no args on channel ${channelName}${peerTargetMessage}`);
} else {
outputAdapter.log(LogType.INFO, undefined, `${actioning} transaction ${transactionName} with args ${args} on channel ${channelName}${peerTargetMessage}`);
}
if (gatewayRegistryEntry.fromEnvironment) {
const environmentEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(gatewayRegistryEntry.fromEnvironment);
if (environmentEntry.environmentType === EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT) {
VSCodeBlockchainDockerOutputAdapter.instance(environmentEntry.name).show();
}
}
let result: string | undefined;
if (evaluate) {
result = await connection.submitTransaction(smartContract, transactionName, channelName, args, namespace, transientData, true, peerTargetNames);
} else {
result = await connection.submitTransaction(smartContract, transactionName, channelName, args, namespace, transientData, false, peerTargetNames);
}
Reporter.instance().sendTelemetryEvent(`${action} transaction`);
let message: string;
if (result === undefined) {
message = `No value returned from ${transactionName}`;
} else {
message = `Returned value from ${transactionName}: ${result}`;
}
outputAdapter.log(LogType.SUCCESS, `Successfully ${actioned} transaction`, message);
outputAdapter.show(); // Bring the 'Blockchain' output channel into focus.
const extensionData: ExtensionData = GlobalState.get();
// On the user's first transaction submit, show a link to a survey
if (!evaluate && !extensionData.shownFirstSubmissionSurveyURL) {
// Show review box when we know that it has been successful
const surveyMessage: string = 'Congratulations on submitting your first transaction! We appreciate your feedback to help improve the extension';
const surveyCallToAction: string = 'Open survey';
const surveyURL: string = 'https://www.surveygizmo.com/s3/5561397/VSCodeExt-Popup-Link';
await GlobalState.update({ ...extensionData, shownFirstSubmissionSurveyURL: true });
// Don't use async/await here so that the parent function can return
// tslint:disable-next-line: no-floating-promises
UserInputUtil.showExternalLinkButton(surveyMessage, surveyCallToAction, surveyURL);
}
if (transactionObject) {
return message;
}
} catch (error) {
errorMessage = `Error ${actioning} transaction: ${error.message}`;
outputAdapter.log(LogType.ERROR, errorMessage);
if (error.endorsements) {
for (const endorsement of error.endorsements) {
const endorsementError: string = `Endorsement failed with: ${endorsement.message}`;
outputAdapter.log(LogType.ERROR, endorsementError);
errorMessage += `\n${endorsementError}`;
}
}
outputAdapter.show();
if (transactionObject) {
return errorMessage;
}
}
});
} | the_stack |
import * as BaseView from 'app/client/components/BaseView';
import {GristDoc} from 'app/client/components/GristDoc';
import {sortByXValues, splitValuesByIndex, uniqXValues} from 'app/client/lib/chartUtil';
import {Delay} from 'app/client/lib/Delay';
import {Disposable} from 'app/client/lib/dispose';
import {fromKoSave} from 'app/client/lib/fromKoSave';
import {loadPlotly, PlotlyType} from 'app/client/lib/imports';
import * as DataTableModel from 'app/client/models/DataTableModel';
import {ViewFieldRec, ViewSectionRec} from 'app/client/models/DocModel';
import {reportError} from 'app/client/models/errors';
import {KoSaveableObservable, ObjObservable} from 'app/client/models/modelUtil';
import {SortedRowSet} from 'app/client/models/rowset';
import {cssLabel, cssRow, cssSeparator} from 'app/client/ui/RightPanel';
import {cssFieldEntry, cssFieldLabel, IField, VisibleFieldsConfig } from 'app/client/ui/VisibleFieldsConfig';
import {squareCheckbox} from 'app/client/ui2018/checkbox';
import {colors, vars} from 'app/client/ui2018/cssVars';
import {cssDragger} from 'app/client/ui2018/draggableList';
import {icon} from 'app/client/ui2018/icons';
import {linkSelect, menu, menuItem, select} from 'app/client/ui2018/menus';
import {nativeCompare} from 'app/common/gutil';
import {decodeObject} from 'app/plugin/objtypes';
import {Events as BackboneEvents} from 'backbone';
import {Computed, dom, DomElementArg, fromKo, Disposable as GrainJSDisposable, IOption,
makeTestId, Observable, styled} from 'grainjs';
import * as ko from 'knockout';
import debounce = require('lodash/debounce');
import defaults = require('lodash/defaults');
import defaultsDeep = require('lodash/defaultsDeep');
import {Config, Data, Datum, ErrorBar, Layout, LayoutAxis, Margin} from 'plotly.js';
let Plotly: PlotlyType;
// When charting multiple series based on user data, limit the number of series given to plotly.
const MAX_SERIES_IN_CHART = 100;
const testId = makeTestId('test-chart-');
interface ChartOptions {
multiseries?: boolean;
lineConnectGaps?: boolean;
lineMarkers?: boolean;
invertYAxis?: boolean;
logYAxis?: boolean;
// If "symmetric", one series after each Y series gives the length of the error bars around it. If
// "separate", two series after each Y series give the length of the error bars above and below it.
errorBars?: 'symmetric' | 'separate';
}
// tslint:disable:no-console
// We use plotly's Datum to describe the type of values in cells. Cells may not match this
// perfectly, but it's helpful for type-checking anyway.
type RowPropGetter = (rowId: number) => Datum;
// We convert Grist data to a list of Series first, from which we then construct Plotly traces.
interface Series {
label: string; // Corresponds to the column name.
group?: Datum; // The group value, when grouped.
values: Datum[];
}
function getSeriesName(series: Series, haveMultiple: boolean) {
if (!series.group) {
return series.label;
} else if (haveMultiple) {
return `${series.group} \u2022 ${series.label}`; // the unicode character is "black circle"
} else {
return String(series.group);
}
}
// The output of a ChartFunc. Normally it just returns one or more Data[] series, but sometimes it
// includes layout information: e.g. a "Scatter Plot" returns a Layout with axis labels.
interface PlotData {
data: Data[];
layout?: Partial<Layout>;
config?: Partial<Config>;
}
// Data options to pass to chart functions.
interface DataOptions {
// Allows to set the pie sort option (see: https://plotly.com/javascript/reference/pie/#pie-sort).
// Supports pie charts only.
sort?: boolean;
}
// Convert a list of Series into a set of Plotly traces.
type ChartFunc = (series: Series[], options: ChartOptions, dataOptions?: DataOptions) => PlotData;
// Helper for converting numeric Date/DateTime values (seconds since Epoch) to JS Date objects for
// use with plotly.
function dateGetter(getter: RowPropGetter): RowPropGetter {
return (r: number) => {
// 0's will turn into nulls, and non-numbers will turn into NaNs and then nulls. This prevents
// Plotly from including 1970-01-01 onto X axis, which usually makes the plot useless.
const val = (getter(r) as number) * 1000;
// Plotly recommends using strings for dates rather than Date objects or timestamps. They are
// interpreted more consistently. See https://github.com/plotly/plotly.js/issues/1532#issuecomment-290420534.
return val ? new Date(val).toISOString() : null;
};
}
// List of column types whose values are encoded has list, ie: ['L', 'foo', ...]. Such values
// require special treatment to show correctly in charts.
const LIST_TYPES = ['ChoiceList', 'RefList'];
/**
* ChartView component displays created charts.
*/
export class ChartView extends Disposable {
public viewPane: Element;
// These elements are defined in BaseView, from which we inherit with some hackery.
protected viewSection: ViewSectionRec;
protected sortedRows: SortedRowSet;
protected tableModel: DataTableModel;
private _chartType: ko.Observable<string>;
private _options: ObjObservable<any>;
private _chartDom: HTMLElement;
private _update: () => void;
private _resize: () => void;
public create(gristDoc: GristDoc, viewSectionModel: ViewSectionRec) {
BaseView.call(this as any, gristDoc, viewSectionModel);
this._chartDom = this.autoDispose(this.buildDom());
this._resize = this.autoDispose(Delay.untilAnimationFrame(this._resizeChart, this));
// Note that .viewPane is used by ViewLayout to insert the actual DOM into the document.
this.viewPane = this._chartDom;
this._chartType = this.viewSection.chartTypeDef;
this._options = this.viewSection.optionsObj;
this._update = debounce(() => this._updateView(), 0);
this.autoDispose(this._chartType.subscribe(this._update));
this.autoDispose(this._options.subscribe(this._update));
this.autoDispose(this.viewSection.viewFields().subscribe(this._update));
this.listenTo(this.sortedRows, 'rowNotify', this._update);
this.autoDispose(this.sortedRows.getKoArray().subscribe(this._update));
}
public prepareToPrint(onOff: boolean) {
Plotly.relayout(this._chartDom, {}).catch(reportError);
}
protected onTableLoaded() {
(BaseView.prototype as any).onTableLoaded.call(this);
this._update();
}
protected onResize() {
this._resize();
}
protected buildDom() {
return dom('div.chart_container', testId('container'));
}
private listenTo(...args: any[]): void { /* replaced by Backbone */ }
private async _updateView() {
if (this.isDisposed()) { return; }
const chartFunc = chartTypes[this._chartType()];
if (typeof chartFunc !== 'function') {
console.warn("Unknown trace type %s", this._chartType());
return;
}
const fields: ViewFieldRec[] = this.viewSection.viewFields().all();
const rowIds: number[] = this.sortedRows.getKoArray().peek() as number[];
let series: Series[] = fields.map((field) => {
// Use the colId of the displayCol, which may be different in case of Reference columns.
const colId: string = field.displayColModel.peek().colId.peek();
const getter = this.tableModel.tableData.getRowPropFunc(colId) as RowPropGetter;
const pureType = field.displayColModel().pureType();
const fullGetter = (pureType === 'Date' || pureType === 'DateTime') ? dateGetter(getter) : getter;
return {
label: field.label(),
values: rowIds.map(fullGetter),
};
});
const startIndexForYAxis = this._options.prop('multiseries') ? 2 : 1;
for (let i = 0; i < series.length; ++i) {
if (i < fields.length && LIST_TYPES.includes(fields[i].column.peek().pureType.peek())) {
if (i < startIndexForYAxis) {
// For x-axis and group column data, split series we should split records.
series = splitValuesByIndex(series, i);
} else {
// For all y-axis, it's not sure what would be a sensible representation for choice list,
// simply stringify choice list values seems reasonable.
series[i].values = series[i].values.map((v) => String(decodeObject(v as any)));
}
}
}
const dataOptions: DataOptions = {};
const options: ChartOptions = this._options.peek() || {};
let plotData: PlotData = {data: []};
const sortSpec = this.viewSection.activeSortSpec.peek();
if (this._chartType.peek() === 'pie' && sortSpec?.length) {
dataOptions.sort = false;
}
if (!options.multiseries) {
plotData = chartFunc(series, options, dataOptions);
} else if (series.length > 1) {
// We need to group all series by the first column.
const nseries = groupSeries(series[0].values, series.slice(1));
// This will be in the order in which nseries Map was created; concat() flattens the arrays.
for (const gSeries of nseries.values()) {
const part = chartFunc(gSeries, options, dataOptions);
part.data = plotData.data.concat(part.data);
plotData = part;
}
}
Plotly = Plotly || await loadPlotly();
// Loading plotly is asynchronous and it may happen that the chart view had been disposed in the
// meantime and cause error later. So let's check again.
if (this.isDisposed()) { return; }
const layout: Partial<Layout> = defaultsDeep(plotData.layout, getPlotlyLayout(options));
const config: Partial<Config> = {...plotData.config, displayModeBar: false};
// react() can be used in place of newPlot(), and is faster when updating an existing plot.
await Plotly.react(this._chartDom, plotData.data, layout, config);
this._resizeChart();
}
private _resizeChart() {
if (this.isDisposed() || !Plotly || !this._chartDom.parentNode) { return; }
Plotly.Plots.resize(this._chartDom);
}
}
/**
* Group the given array of series by a column of group values. The groupColumn and each of the
* series should be arrays of the same length.
*
* For example, if groupColumn has CompanyID, and valueSeries contains [Date, Employees, Revenues]
* (each an array of values), then returns a map mapping each CompanyID to the array [Date,
* Employees, Revenue], each value of which is itself an array of values for that CompanyID.
*/
function groupSeries<T extends Datum>(groupColumn: T[], valueSeries: Series[]): Map<T, Series[]> {
const nseries = new Map<T, Series[]>();
// Limit the number if group values so as to limit the total number of series we pass into
// Plotly. Too many series are impossible to make sense of anyway, and can hang the browser.
// TODO: When not all data is shown, we should probably show some indicator, similar to when
// OnDemand data is truncated.
const maxGroups = Math.floor(MAX_SERIES_IN_CHART / valueSeries.length);
const groupValues: T[] = [...new Set(groupColumn)].sort().slice(0, maxGroups);
// Set up empty lists for each group.
for (const group of groupValues) {
nseries.set(group, valueSeries.map((s: Series) => ({
label: s.label,
group,
values: []
})));
}
// Now fill up the lists.
for (let row = 0; row < groupColumn.length; row++) {
const group = groupColumn[row];
const series: Series[]|undefined = nseries.get(group);
if (series) {
for (let i = 0; i < valueSeries.length; i++) {
series[i].values.push(valueSeries[i].values[row]);
}
}
}
return nseries;
}
// If errorBars are requested, removes error bar series from the 'series' list, adding instead a
// mapping from each main Y series to the corresponding plotly ErrorBar object.
function extractErrorBars(series: Series[], options: ChartOptions): Map<Series, ErrorBar> {
const result = new Map<Series, ErrorBar>();
if (options.errorBars) {
// We assume that series is of the form [X, Y1, Y1-bar, Y2, Y2-bar, ...] (if "symmetric") or
// [X, Y1, Y1-below, Y1-above, Y2, Y2-below, Y2-above, ...] (if "separate").
for (let i = 1; i < series.length; i++) {
result.set(series[i], {
type: 'data',
symmetric: (options.errorBars === 'symmetric'),
array: series[i + 1] && series[i + 1].values,
arrayminus: (options.errorBars === 'separate' ? series[i + 2] && series[i + 2].values : undefined),
thickness: 1,
width: 3,
});
series.splice(i + 1, (options.errorBars === 'symmetric' ? 1 : 2));
}
}
return result;
}
// Getting an ES6 class to work with old-style multiple base classes takes a little hacking.
defaults(ChartView.prototype, BaseView.prototype);
Object.assign(ChartView.prototype, BackboneEvents);
function getPlotlyLayout(options: ChartOptions): Partial<Layout> {
// Note that each call to getPlotlyLayout() creates a new layout object. We are intentionally
// avoiding reuse because Plotly caches too many layout calculations when the object is reused.
const yaxis: Partial<LayoutAxis> = {};
if (options.logYAxis) { yaxis.type = 'log'; }
if (options.invertYAxis) { yaxis.autorange = 'reversed'; }
return {
// Margins include labels, titles, legend, and may get auto-expanded beyond this.
margin: {
l: 50,
r: 50,
b: 40, // Space below chart which includes x-axis labels
t: 30, // Space above the chart (doesn't include any text)
pad: 4
} as Margin,
legend: {
// Translucent background, so chart data is still visible if legend overlaps it.
bgcolor: "#FFFFFF80",
},
yaxis,
};
}
/**
* The grainjs component for side-pane configuration options for a Chart section.
*/
export class ChartConfig extends GrainJSDisposable {
// helper to build the draggable field list
private _configFieldsHelper = VisibleFieldsConfig.create(this, this._gristDoc, this._section, true);
// The index for the x-axis in the list visible fields. Could be eigther 0 or 1 depending on
// whether multiseries is set.
private _xAxisFieldIndex = Computed.create(
this, fromKo(this._optionsObj.prop('multiseries')), (_use, multiseries) => (
multiseries ? 1 : 0
)
);
// The column id of the grouping column, or -1 if multiseries is disabled.
private _groupDataColId: Computed<number> = Computed.create(this, (use) => {
const multiseries = use(this._optionsObj.prop('multiseries'));
const viewFields = use(use(this._section.viewFields).getObservable());
if (!multiseries) { return -1; }
return use(viewFields[0].column).getRowId();
})
.onWrite((colId) => this._setGroupDataColumn(colId));
// Updating the group data column involves several changes of the list of view fields which could
// leave the x-axis field index momentarily point to the wrong column. The freeze x axis
// observable is part of a hack to fix this issue.
private _freezeXAxis = Observable.create(this, false);
private _freezeYAxis = Observable.create(this, false);
// The column is of the x-axis.
private _xAxis: Computed<number> = Computed.create(
this, this._xAxisFieldIndex, this._freezeXAxis, (use, i, freeze) => {
if (freeze) { return this._xAxis.get(); }
const viewFields = use(use(this._section.viewFields).getObservable());
if (i < viewFields.length) {
return use(viewFields[i].column).getRowId();
}
return -1;
})
.onWrite((colId) => this._setXAxis(colId));
// The list of available columns for the group data picker. Picking the actual x-axis is not
// permitted.
private _groupDataOptions = Computed.create<Array<IOption<number>>>(this, (use) => [
{value: -1, label: 'Pick a column'},
...this._section.table().columns().peek()
// filter out hidden column (ie: manualsort ...) and the one selected for x axis
.filter((col) => !col.isHiddenCol.peek() && (col.getRowId() !== use(this._xAxis)))
.map((col) => ({
value: col.getRowId(), label: col.label.peek(), icon: 'FieldColumn',
}))
]);
// Force checking/unchecking of the group data checkbox option.
private _groupDataForce = Observable.create(null, false);
// State for the group data option checkbox. True, if a group data column is set or if the user
// forced it. False otherwise.
private _groupData = Computed.create(
this, this._groupDataColId, this._groupDataForce, (_use, col, force) => {
if (col > -1) { return true; }
return force;
}).onWrite((val) => {
if (val === false) {
this._groupDataColId.set(-1);
}
this._groupDataForce.set(val);
});
// The label to show for the first field in the axis configurator.
private _firstFieldLabel = Computed.create(this, fromKo(this._section.chartTypeDef), (
(_use, chartType) => chartType === 'pie' ? 'LABEL' : 'X-AXIS'
));
// A computed that returns `this._section.chartTypeDef` and that takes care of removing the group
// data option when type is switched to 'pie'.
private _chartType = Computed.create(this, (use) => use(this._section.chartTypeDef))
.onWrite((val) => {
return this._gristDoc.docData.bundleActions('switched chart type', async () => {
await this._section.chartTypeDef.saveOnly(val);
// When switching chart type to 'pie' makes sure to remove the group data option.
if (val === 'pie') {
await this._setGroupDataColumn(-1);
this._groupDataForce.set(false);
}
});
});
constructor(private _gristDoc: GristDoc, private _section: ViewSectionRec) {
super();
}
private get _optionsObj() { return this._section.optionsObj; }
public buildDom() {
if (this._section.parentKey() !== 'chart') { return null; }
return [
cssRow(
select(this._chartType, [
{value: 'bar', label: 'Bar Chart', icon: 'ChartBar' },
{value: 'pie', label: 'Pie Chart', icon: 'ChartPie' },
{value: 'area', label: 'Area Chart', icon: 'ChartArea' },
{value: 'line', label: 'Line Chart', icon: 'ChartLine' },
{value: 'scatter', label: 'Scatter Plot', icon: 'ChartLine' },
{value: 'kaplan_meier', label: 'Kaplan-Meier Plot', icon: 'ChartKaplan'},
]),
testId("type"),
),
dom.maybe((use) => use(this._section.chartTypeDef) !== 'pie', () => [
// These options don't make much sense for a pie chart.
cssCheckboxRowObs('Group data', this._groupData),
cssCheckboxRow('Invert Y-axis', this._optionsObj.prop('invertYAxis')),
cssCheckboxRow('Log scale Y-axis', this._optionsObj.prop('logYAxis')),
]),
dom.maybe((use) => use(this._section.chartTypeDef) === 'line', () => [
cssCheckboxRow('Connect gaps', this._optionsObj.prop('lineConnectGaps')),
cssCheckboxRow('Show markers', this._optionsObj.prop('lineMarkers')),
]),
dom.maybe((use) => ['line', 'bar'].includes(use(this._section.chartTypeDef)), () => [
cssRow(
cssRowLabel('Error bars'),
dom('div', linkSelect(fromKoSave(this._optionsObj.prop('errorBars')), [
{value: '', label: 'None'},
{value: 'symmetric', label: 'Symmetric'},
{value: 'separate', label: 'Above+Below'},
], {defaultLabel: 'None'})),
testId('error-bars'),
),
dom.domComputed(this._optionsObj.prop('errorBars'), (value: ChartOptions["errorBars"]) =>
value === 'symmetric' ? cssRowHelp('Each Y series is followed by a series for the length of error bars.') :
value === 'separate' ? cssRowHelp('Each Y series is followed by two series, for top and bottom error bars.') :
null
),
]),
cssSeparator(),
dom.maybe(this._groupData, () => [
cssLabel('Group data'),
cssRow(
select(this._groupDataColId, this._groupDataOptions),
testId('group-by-column'),
),
cssHintRow('Create separate series for each value of the selected column.'),
]),
// TODO: user should select x axis before widget reach page
cssLabel(dom.text(this._firstFieldLabel), testId('first-field-label')),
cssRow(
select(
this._xAxis, this._section.table().columns().peek()
.filter((col) => !col.isHiddenCol.peek())
.map((col) => ({
value: col.getRowId(), label: col.label.peek(), icon: 'FieldColumn',
}))
),
testId('x-axis'),
),
cssLabel('SERIES'),
this._buildYAxis(),
cssRow(
cssAddYAxis(
cssAddIcon('Plus'), 'Add Series',
menu(() => this._section.hiddenColumns.peek().map((col) => (
menuItem(() => this._configFieldsHelper.addField(col), col.label.peek())
))),
testId('add-y-axis'),
)
),
];
}
private async _setXAxis(colId: number) {
const optionsObj = this._section.optionsObj;
const col = this._gristDoc.docModel.columns.getRowModel(colId);
const viewFields = this._section.viewFields.peek();
await this._gristDoc.docData.bundleActions('selected new x-axis', async () => {
this._freezeYAxis.set(true);
try {
// first remove the current field
if (this._xAxisFieldIndex.get() < viewFields.peek().length) {
await this._configFieldsHelper.removeField(viewFields.peek()[this._xAxisFieldIndex.get()]);
}
// if new field was used to group by column series, disable multiseries
const fieldIndex = viewFields.peek().findIndex((f) => f.column.peek().getRowId() === colId);
if (fieldIndex === 0 && optionsObj.prop('multiseries').peek()) {
await optionsObj.prop('multiseries').setAndSave(false);
return;
}
// if new field is already visible, moves the fields to the first place else add the field to the first
// place
const xAxisField = viewFields.peek()[this._xAxisFieldIndex.get()];
if (fieldIndex > -1) {
await this._configFieldsHelper.changeFieldPosition(viewFields.peek()[fieldIndex], xAxisField);
} else {
await this._configFieldsHelper.addField(col, xAxisField);
}
} finally {
this._freezeYAxis.set(false);
}
});
}
private async _setGroupDataColumn(colId: number) {
const viewFields = this._section.viewFields.peek().peek();
await this._gristDoc.docData.bundleActions('selected new x-axis', async () => {
this._freezeXAxis.set(true);
this._freezeYAxis.set(true);
try {
// if grouping was already set, first remove the current field
if (this._groupDataColId.get() > -1) {
await this._configFieldsHelper.removeField(viewFields[0]);
}
if (colId > -1) {
const col = this._gristDoc.docModel.columns.getRowModel(colId);
const field = viewFields.find((f) => f.column.peek().getRowId() === colId);
// if new field is already visible, moves the fields to the first place else add the field to the first
// place
if (field) {
await this._configFieldsHelper.changeFieldPosition(field, viewFields[0]);
} else {
await this._configFieldsHelper.addField(col, viewFields[0]);
}
}
await this._optionsObj.prop('multiseries').setAndSave(colId > -1);
} finally {
this._freezeXAxis.set(false);
this._freezeYAxis.set(false);
}
}, {nestInActiveBundle: true});
}
private _buildField(col: IField) {
return cssFieldEntry(
cssFieldLabel(dom.text(col.label)),
cssRemoveIcon(
'Remove',
dom.on('click', () => this._configFieldsHelper.removeField(col)),
testId('ref-select-remove'),
),
testId('y-axis'),
);
}
private _buildYAxis() {
// The y-axis are all visible fields that comes after the x-axis and maybe the group data
// column. Hence the draggable list of y-axis needs to skip either one or two visible fields.
const skipFirst = Computed.create(this, fromKo(this._optionsObj.prop('multiseries')), (_use, multiseries) => (
multiseries ? 2 : 1
));
return this._configFieldsHelper.buildVisibleFieldsConfigHelper({
itemCreateFunc: (field) => this._buildField(field),
draggableOptions: {
removeButton: false,
drag_indicator: cssDragger,
}, skipFirst, freeze: this._freezeYAxis
});
}
}
function cssCheckboxRow(label: string, value: KoSaveableObservable<unknown>, ...args: DomElementArg[]) {
return cssCheckboxRowObs(label, fromKoSave(value), ...args);
}
function cssCheckboxRowObs(label: string, value: Observable<boolean>, ...args: DomElementArg[]) {
return dom('label', cssRow.cls(''),
cssRowLabel(label),
squareCheckbox(value, ...args),
);
}
function basicPlot(series: Series[], options: ChartOptions, dataOptions: Partial<Data>): PlotData {
trimNonNumericData(series);
const errorBars = extractErrorBars(series, options);
if (dataOptions.type === 'bar') {
// Plotly has weirdness when redundant values shows up on the x-axis: the values that shows
// up on hover is different than the value on the y-axis. It seems that one is the sum of all
// values with same x-axis value, while the other is the last of them. To fix this, we force
// unique values for the x-axis.
series = uniqXValues(series);
}
return {
data: series.slice(1).map((line: Series): Data => ({
name: getSeriesName(line, series.length > 2),
x: series[0].values,
y: line.values,
error_y: errorBars.get(line),
...dataOptions,
})),
layout: {
xaxis: series.length > 0 ? {title: series[0].label} : {},
// Include yaxis title for a single y-value series only (2 series total);
// If there are fewer than 2 total series, there is no y-series to display.
// If there are multiple y-series, a legend will be included instead, and the yaxis title
// is less meaningful, so omit it.
yaxis: series.length === 2 ? {title: series[1].label} : {},
},
};
}
// Most chart types take a list of series and then use the first series for the X-axis, and each
// subsequent series for their Y-axis values, allowing for multiple lines on the same plot.
// Each series should have the form {label, values}.
export const chartTypes: {[name: string]: ChartFunc} = {
// TODO There is a lot of code duplication across chart types. Some refactoring is in order.
bar(series: Series[], options: ChartOptions): PlotData {
return basicPlot(series, options, {type: 'bar'});
},
line(series: Series[], options: ChartOptions): PlotData {
sortByXValues(series);
return basicPlot(series, options, {
type: 'scatter',
connectgaps: options.lineConnectGaps,
mode: options.lineMarkers ? 'lines+markers' : 'lines',
});
},
area(series: Series[], options: ChartOptions): PlotData {
sortByXValues(series);
return basicPlot(series, options, {
type: 'scatter',
fill: 'tozeroy',
line: {shape: 'spline'},
});
},
scatter(series: Series[], options: ChartOptions): PlotData {
return basicPlot(series.slice(1), options, {
type: 'scatter',
mode: 'text+markers',
text: series[0].values as string[],
textposition: "bottom center",
});
},
pie(series: Series[], _options: ChartOptions, dataOptions: DataOptions = {}): PlotData {
let line: Series;
if (series.length === 0) {
return {data: []};
}
if (series.length > 1) {
trimNonNumericData(series);
line = series[1];
} else {
// When there is only one series of labels, simply count their occurrences.
line = {label: 'Count', values: series[0].values.map(() => 1)};
}
return {
data: [{
type: 'pie',
name: getSeriesName(line, false),
// nulls cause JS errors when pie charts resize, so replace with blanks.
// (a falsy value would cause plotly to show its index, like "2" which is more confusing).
labels: series[0].values.map(v => (v == null || v === "") ? "-" : v),
values: line.values,
...dataOptions,
}]
};
},
kaplan_meier(series: Series[]): PlotData {
// For this plot, the first series names the category of each point, and the second the
// survival time for that point. We turn that into as many series as there are categories.
if (series.length < 2) { return {data: []}; }
const newSeries = groupIntoSeries(series[0].values, series[1].values);
return {
data: newSeries.map((line: Series): Data => {
const points = kaplanMeierPlot(line.values as number[]);
return {
type: 'scatter',
mode: 'lines',
line: {shape: 'hv'},
name: getSeriesName(line, false),
x: points.map(p => p.x),
y: points.map(p => p.y),
} as Data;
})
};
},
};
/**
* Assumes a list of series of the form [xValues, yValues1, yValues2, ...]. Remove from all series
* those points for which all of the y-values are non-numeric (e.g. null or a string).
*/
function trimNonNumericData(series: Series[]): void {
const values = series.slice(1).map((s) => s.values);
for (const s of series) {
s.values = s.values.filter((_, i) => values.some(v => typeof v[i] === 'number'));
}
}
// Given two parallel arrays, returns an array of series of the form
// {label: category, values: array-of-values}
function groupIntoSeries(categoryList: Datum[], valueList: Datum[]): Series[] {
const groups = new Map();
for (const [i, cat] of categoryList.entries()) {
if (!groups.has(cat)) { groups.set(cat, []); }
groups.get(cat).push(valueList[i]);
}
return Array.from(groups, ([label, values]) => ({label, values}));
}
// Given a list of survivalValues, returns a list of {x, y} pairs for the kaplanMeier plot.
function kaplanMeierPlot(survivalValues: number[]): Array<{x: number, y: number}> {
// First get a distribution of survivalValue -> count.
const dist = new Map<number, number>();
for (const v of survivalValues) {
dist.set(v, (dist.get(v) || 0) + 1);
}
// Sort the distinct values.
const distinctValues = Array.from(dist.keys());
distinctValues.sort(nativeCompare);
// Now generate plot values, with 'x' for survivalValue and 'y' the number of surviving points.
let y = survivalValues.length;
const points = [{x: 0, y}];
for (const x of distinctValues) {
y -= dist.get(x)!;
points.push({x, y});
}
return points;
}
const cssRowLabel = styled('div', `
flex: 1 0 0px;
margin-right: 8px;
font-weight: initial; /* negate bootstrap */
color: ${colors.dark};
overflow: hidden;
text-overflow: ellipsis;
user-select: none;
`);
const cssRowHelp = styled(cssRow, `
font-size: ${vars.smallFontSize};
color: ${colors.slate};
`);
const cssAddIcon = styled(icon, `
margin-right: 4px;
`);
const cssAddYAxis = styled('div', `
display: flex;
cursor: pointer;
color: ${colors.lightGreen};
--icon-color: ${colors.lightGreen};
&:not(:first-child) {
margin-top: 8px;
}
&:hover, &:focus, &:active {
color: ${colors.darkGreen};
--icon-color: ${colors.darkGreen};
}
`);
const cssRemoveIcon = styled(icon, `
display: none;
cursor: pointer;
flex: none;
margin-left: 8px;
.${cssFieldEntry.className}:hover & {
display: block;
}
`);
const cssHintRow = styled('div', `
margin: -4px 16px 8px 16px;
color: ${colors.slate};
`); | the_stack |
import { ethers, Transaction } from 'ethers'
import {
fromHexString,
remove0x,
toHexString,
toRpcHexString,
} from '@eth-optimism/core-utils'
import { getContractInterface, predeploys } from '@eth-optimism/contracts'
import * as rlp from 'rlp'
import { MerkleTree } from 'merkletreejs'
// Number of blocks added to the L2 chain before the first L2 transaction. Genesis are added to the
// chain to initialize the system. However, they create a discrepancy between the L2 block number
// the index of the transaction that corresponds to that block number. For example, if there's 1
// genesis block, then the transaction with an index of 0 corresponds to the block with index 1.
const NUM_L2_GENESIS_BLOCKS = 1
interface StateRootBatchHeader {
batchIndex: ethers.BigNumber
batchRoot: string
batchSize: ethers.BigNumber
prevTotalElements: ethers.BigNumber
extraData: string
}
interface StateRootBatch {
header: StateRootBatchHeader
stateRoots: string[]
}
interface CrossDomainMessage {
target: string
sender: string
message: string
messageNonce: number
}
interface CrossDomainMessageProof {
stateRoot: string
stateRootBatchHeader: StateRootBatchHeader
stateRootProof: {
index: number
siblings: string[]
}
stateTrieWitness: string
storageTrieWitness: string
}
interface CrossDomainMessagePair {
message: CrossDomainMessage
proof: CrossDomainMessageProof
}
interface StateTrieProof {
accountProof: string
storageProof: string
}
/**
* Finds all L2 => L1 messages triggered by a given L2 transaction, if the message exists.
*
* @param l2RpcProvider L2 RPC provider.
* @param l2CrossDomainMessengerAddress Address of the L2CrossDomainMessenger.
* @param l2TransactionHash Hash of the L2 transaction to find a message for.
* @returns Messages associated with the transaction.
*/
export const getMessagesByTransactionHash = async (
l2RpcProvider: ethers.providers.JsonRpcProvider,
l2CrossDomainMessengerAddress: string,
l2TransactionHash: string
): Promise<CrossDomainMessage[]> => {
// Complain if we can't find the given transaction.
const transaction = await l2RpcProvider.getTransaction(l2TransactionHash)
if (transaction === null) {
throw new Error(`unable to find tx with hash: ${l2TransactionHash}`)
}
const l2CrossDomainMessenger = new ethers.Contract(
l2CrossDomainMessengerAddress,
getContractInterface('L2CrossDomainMessenger'),
l2RpcProvider
)
// Find all SentMessage events created in the same block as the given transaction. This is
// reliable because we should only have one transaction per block.
const sentMessageEvents = await l2CrossDomainMessenger.queryFilter(
l2CrossDomainMessenger.filters.SentMessage(),
transaction.blockNumber,
transaction.blockNumber
)
// Decode the messages and turn them into a nicer struct.
const sentMessages = sentMessageEvents.map((sentMessageEvent) => {
return {
target: sentMessageEvent.args.target,
sender: sentMessageEvent.args.sender,
message: sentMessageEvent.args.message, // decoded message
messageNonce: sentMessageEvent.args.messageNonce.toNumber(),
}
})
return sentMessages
}
/**
* Encodes a cross domain message.
*
* @param message Message to encode.
* @returns Encoded message.
*/
const encodeCrossDomainMessage = (message: CrossDomainMessage): string => {
return getContractInterface('L2CrossDomainMessenger').encodeFunctionData(
'relayMessage',
[message.target, message.sender, message.message, message.messageNonce]
)
}
/**
* Finds the StateBatchAppended event associated with a given L2 transaction.
*
* @param l1RpcProvider L1 RPC provider.
* @param l1StateCommitmentChainAddress Address of the L1StateCommitmentChain.
* @param l2TransactionIndex Index of the L2 transaction to find a StateBatchAppended event for.
* @returns StateBatchAppended event for the given transaction or null if no such event exists.
*/
export const getStateBatchAppendedEventByTransactionIndex = async (
l1RpcProvider: ethers.providers.JsonRpcProvider,
l1StateCommitmentChainAddress: string,
l2TransactionIndex: number
): Promise<ethers.Event | null> => {
const l1StateCommitmentChain = new ethers.Contract(
l1StateCommitmentChainAddress,
getContractInterface('StateCommitmentChain'),
l1RpcProvider
)
const getStateBatchAppendedEventByBatchIndex = async (
index: number
): Promise<ethers.Event | null> => {
const eventQueryResult = await l1StateCommitmentChain.queryFilter(
l1StateCommitmentChain.filters.StateBatchAppended(index)
)
if (eventQueryResult.length === 0) {
return null
} else {
return eventQueryResult[0]
}
}
const isEventHi = (event: ethers.Event, index: number) => {
const prevTotalElements = event.args._prevTotalElements.toNumber()
return index < prevTotalElements
}
const isEventLo = (event: ethers.Event, index: number) => {
const prevTotalElements = event.args._prevTotalElements.toNumber()
const batchSize = event.args._batchSize.toNumber()
return index >= prevTotalElements + batchSize
}
const totalBatches: ethers.BigNumber =
await l1StateCommitmentChain.getTotalBatches()
if (totalBatches.eq(0)) {
return null
}
let lowerBound = 0
let upperBound = totalBatches.toNumber() - 1
let batchEvent: ethers.Event | null =
await getStateBatchAppendedEventByBatchIndex(upperBound)
if (isEventLo(batchEvent, l2TransactionIndex)) {
// Upper bound is too low, means this transaction doesn't have a corresponding state batch yet.
return null
} else if (!isEventHi(batchEvent, l2TransactionIndex)) {
// Upper bound is not too low and also not too high. This means the upper bound event is the
// one we're looking for! Return it.
return batchEvent
}
// Binary search to find the right event. The above checks will guarantee that the event does
// exist and that we'll find it during this search.
while (lowerBound < upperBound) {
const middleOfBounds = Math.floor((lowerBound + upperBound) / 2)
batchEvent = await getStateBatchAppendedEventByBatchIndex(middleOfBounds)
if (isEventHi(batchEvent, l2TransactionIndex)) {
upperBound = middleOfBounds
} else if (isEventLo(batchEvent, l2TransactionIndex)) {
lowerBound = middleOfBounds
} else {
break
}
}
return batchEvent
}
/**
* Finds the full state root batch associated with a given transaction index.
*
* @param l1RpcProvider L1 RPC provider.
* @param l1StateCommitmentChainAddress Address of the L1StateCommitmentChain.
* @param l2TransactionIndex Index of the L2 transaction to find a state root batch for.
* @returns State root batch associated with the given transaction index or null if no state root
* batch exists.
*/
export const getStateRootBatchByTransactionIndex = async (
l1RpcProvider: ethers.providers.JsonRpcProvider,
l1StateCommitmentChainAddress: string,
l2TransactionIndex: number
): Promise<StateRootBatch | null> => {
const l1StateCommitmentChain = new ethers.Contract(
l1StateCommitmentChainAddress,
getContractInterface('StateCommitmentChain'),
l1RpcProvider
)
const stateBatchAppendedEvent =
await getStateBatchAppendedEventByTransactionIndex(
l1RpcProvider,
l1StateCommitmentChainAddress,
l2TransactionIndex
)
if (stateBatchAppendedEvent === null) {
return null
}
const stateBatchTransaction = await stateBatchAppendedEvent.getTransaction()
const [stateRoots] = l1StateCommitmentChain.interface.decodeFunctionData(
'appendStateBatch',
stateBatchTransaction.data
)
return {
header: {
batchIndex: stateBatchAppendedEvent.args._batchIndex,
batchRoot: stateBatchAppendedEvent.args._batchRoot,
batchSize: stateBatchAppendedEvent.args._batchSize,
prevTotalElements: stateBatchAppendedEvent.args._prevTotalElements,
extraData: stateBatchAppendedEvent.args._extraData,
},
stateRoots,
}
}
/**
* Generates a Merkle proof (using the particular scheme we use within Lib_MerkleTree).
*
* @param leaves Leaves of the merkle tree.
* @param index Index to generate a proof for.
* @returns Merkle proof sibling leaves, as hex strings.
*/
export const getMerkleTreeProof = (
leaves: string[],
index: number
): string[] => {
// Our specific Merkle tree implementation requires that the number of leaves is a power of 2.
// If the number of given leaves is less than a power of 2, we need to round up to the next
// available power of 2. We fill the remaining space with the hash of bytes32(0).
const correctedTreeSize = Math.pow(2, Math.ceil(Math.log2(leaves.length)))
const parsedLeaves = []
for (let i = 0; i < correctedTreeSize; i++) {
if (i < leaves.length) {
parsedLeaves.push(leaves[i])
} else {
parsedLeaves.push(ethers.utils.keccak256('0x' + '00'.repeat(32)))
}
}
// merkletreejs prefers things to be Buffers.
const bufLeaves = parsedLeaves.map(fromHexString)
const tree = new MerkleTree(bufLeaves, (el: Buffer | string): Buffer => {
return fromHexString(ethers.utils.keccak256(el))
})
const proof = tree.getProof(bufLeaves[index], index).map((element: any) => {
return toHexString(element.data)
})
return proof
}
/**
* Generates a Merkle-Patricia trie proof for a given account and storage slot.
*
* @param l2RpcProvider L2 RPC provider.
* @param blockNumber Block number to generate the proof at.
* @param address Address to generate the proof for.
* @param slot Storage slot to generate the proof for.
* @returns Account proof and storage proof.
*/
const getStateTrieProof = async (
l2RpcProvider: ethers.providers.JsonRpcProvider,
blockNumber: number,
address: string,
slot: string
): Promise<StateTrieProof> => {
const proof = await l2RpcProvider.send('eth_getProof', [
address,
[slot],
toRpcHexString(blockNumber),
])
return {
accountProof: toHexString(rlp.encode(proof.accountProof)),
storageProof: toHexString(rlp.encode(proof.storageProof[0].proof)),
}
}
/**
* Finds all L2 => L1 messages sent in a given L2 transaction and generates proofs for each of
* those messages.
*
* @param l1RpcProvider L1 RPC provider.
* @param l2RpcProvider L2 RPC provider.
* @param l1StateCommitmentChainAddress Address of the StateCommitmentChain.
* @param l2CrossDomainMessengerAddress Address of the L2CrossDomainMessenger.
* @param l2TransactionHash L2 transaction hash to generate a relay transaction for.
* @returns An array of messages sent in the transaction and a proof of inclusion for each.
*/
export const getMessagesAndProofsForL2Transaction = async (
l1RpcProvider: ethers.providers.JsonRpcProvider | string,
l2RpcProvider: ethers.providers.JsonRpcProvider | string,
l1StateCommitmentChainAddress: string,
l2CrossDomainMessengerAddress: string,
l2TransactionHash: string
): Promise<CrossDomainMessagePair[]> => {
if (typeof l1RpcProvider === 'string') {
l1RpcProvider = new ethers.providers.JsonRpcProvider(l1RpcProvider)
}
if (typeof l2RpcProvider === 'string') {
l2RpcProvider = new ethers.providers.JsonRpcProvider(l2RpcProvider)
}
const l2Transaction = await l2RpcProvider.getTransaction(l2TransactionHash)
if (l2Transaction === null) {
throw new Error(`unable to find tx with hash: ${l2TransactionHash}`)
}
// Need to find the state batch for the given transaction. If no state batch has been published
// yet then we will not be able to generate a proof.
const batch = await getStateRootBatchByTransactionIndex(
l1RpcProvider,
l1StateCommitmentChainAddress,
l2Transaction.blockNumber - NUM_L2_GENESIS_BLOCKS
)
if (batch === null) {
throw new Error(
`unable to find state root batch for tx with hash: ${l2TransactionHash}`
)
}
// Adjust the transaction index based on the number of L2 genesis block we have. "Index" here
// refers to the position of the transaction within the *Canonical Transaction Chain*.
const l2TransactionIndex = l2Transaction.blockNumber - NUM_L2_GENESIS_BLOCKS
// Here the index refers to the position of the state root that corresponds to this transaction
// within the batch of state roots in which that state root was published.
const txIndexInBatch =
l2TransactionIndex - batch.header.prevTotalElements.toNumber()
// Find every message that was sent during this transaction. We'll then attach a proof for each.
const messages = await getMessagesByTransactionHash(
l2RpcProvider,
l2CrossDomainMessengerAddress,
l2TransactionHash
)
const messagePairs: CrossDomainMessagePair[] = []
for (const message of messages) {
// We need to calculate the specific storage slot that demonstrates that this message was
// actually included in the L2 chain. The following calculation is based on the fact that
// messages are stored in the following mapping on L2:
// https://github.com/ethereum-optimism/optimism/blob/c84d3450225306abbb39b4e7d6d82424341df2be/packages/contracts/contracts/L2/predeploys/OVM_L2ToL1MessagePasser.sol#L23
// You can read more about how Solidity storage slots are computed for mappings here:
// https://docs.soliditylang.org/en/v0.8.4/internals/layout_in_storage.html#mappings-and-dynamic-arrays
const messageSlot = ethers.utils.keccak256(
ethers.utils.keccak256(
encodeCrossDomainMessage(message) +
remove0x(l2CrossDomainMessengerAddress)
) + '00'.repeat(32)
)
// We need a Merkle trie proof for the given storage slot. This allows us to prove to L1 that
// the message was actually sent on L2.
const stateTrieProof = await getStateTrieProof(
l2RpcProvider,
l2Transaction.blockNumber,
predeploys.OVM_L2ToL1MessagePasser,
messageSlot
)
// State roots are published in batches to L1 and correspond 1:1 to transactions. We compute a
// Merkle root for these state roots so that we only need to store the minimum amount of
// information on-chain. So we need to create a Merkle proof for the specific state root that
// corresponds to this transaction.
const stateRootMerkleProof = getMerkleTreeProof(
batch.stateRoots,
txIndexInBatch
)
// We now have enough information to create the message proof.
const proof: CrossDomainMessageProof = {
stateRoot: batch.stateRoots[txIndexInBatch],
stateRootBatchHeader: batch.header,
stateRootProof: {
index: txIndexInBatch,
siblings: stateRootMerkleProof,
},
stateTrieWitness: stateTrieProof.accountProof,
storageTrieWitness: stateTrieProof.storageProof,
}
messagePairs.push({
message,
proof,
})
}
return messagePairs
}
/**
* Allows for proof generation of pre-regenesis L2->L1 messages, by retrieving proofs from
* The genesis state (block 0) of the post-regenesis chain. This is required because the
* history is wiped during regnesis, so old inclusion proofs would no longer work.
*
* @param l1RpcProvider L1 RPC provider.
* @param l2RpcProvider L2 RPC provider of the POST-REGENESIS chain.
* @param legacyL2Transaction A PRE-REGENESIS L2 transaction which sent some L2->L1 messages.
* @param legacyMessages The L2->L1 messages which were sent by the legacy L2 transaction.
* @param l1StateCommitmentChainAddress Address of the POST-REGENESIS StateCommitmentChain.
* @param l2CrossDomainMessengerAddress Address of the L2CrossDomainMessenger.
* @returns An array of messages sent in the transaction and a proof of inclusion for each.
*/
export const getLegacyProofsForL2Transaction = async (
l1RpcProvider: ethers.providers.JsonRpcProvider | string,
l2RpcProvider: ethers.providers.JsonRpcProvider | string,
legacyL2Transaction: Transaction,
legacyMessages: CrossDomainMessage[],
l1StateCommitmentChainAddress: string,
l2CrossDomainMessengerAddress: string
): Promise<CrossDomainMessagePair[]> => {
if (typeof l1RpcProvider === 'string') {
l1RpcProvider = new ethers.providers.JsonRpcProvider(l1RpcProvider)
}
if (typeof l2RpcProvider === 'string') {
l2RpcProvider = new ethers.providers.JsonRpcProvider(l2RpcProvider)
}
// We will use the first ever batch submitted on the new chain
// Because the genesis state already contains all of those state roots, and
// That's the earliest we'll be able to relay the withdrawal.
// This is 1 and not 0 because we don't commit the genesis state.
const postRegenesisBlockToRelayFrom = 1
const batch = await getStateRootBatchByTransactionIndex(
l1RpcProvider,
l1StateCommitmentChainAddress,
postRegenesisBlockToRelayFrom - NUM_L2_GENESIS_BLOCKS
)
if (batch === null) {
throw new Error(
`unable to find first state root batch for legacy withdrawal: ${
legacyL2Transaction?.hash || legacyL2Transaction
}`
)
}
// Here the index refers to the position of the state root that corresponds to this transaction
// within the batch of state roots in which that state root was published.
// Since this is a legacy TX, we get it from 0 always.
// (see comment on `postRegenesisBlockToRelayFrom` above)
const txIndexInBatch = 0
const messagePairs: CrossDomainMessagePair[] = []
for (const message of legacyMessages) {
// We need to calculate the specific storage slot that demonstrates that this message was
// actually included in the L2 chain. The following calculation is based on the fact that
// messages are stored in the following mapping on L2:
// https://github.com/ethereum-optimism/optimism/blob/c84d3450225306abbb39b4e7d6d82424341df2be/packages/contracts/contracts/L2/predeploys/OVM_L2ToL1MessagePasser.sol#L23
// You can read more about how Solidity storage slots are computed for mappings here:
// https://docs.soliditylang.org/en/v0.8.4/internals/layout_in_storage.html#mappings-and-dynamic-arrays
const messageSlot = ethers.utils.keccak256(
ethers.utils.keccak256(
encodeCrossDomainMessage(message) +
remove0x(l2CrossDomainMessengerAddress)
) + '00'.repeat(32)
)
// We need a Merkle trie proof for the given storage slot. This allows us to prove to L1 that
// the message was actually sent on L2.
// Because this is a legacy message, we just get it from index 0.
const stateTrieProof = await getStateTrieProof(
l2RpcProvider,
postRegenesisBlockToRelayFrom,
predeploys.OVM_L2ToL1MessagePasser,
messageSlot
)
// State roots are published in batches to L1 and correspond 1:1 to transactions. We compute a
// Merkle root for these state roots so that we only need to store the minimum amount of
// information on-chain. So we need to create a Merkle proof for the specific state root that
// corresponds to this transaction.
const stateRootMerkleProof = getMerkleTreeProof(
batch.stateRoots,
txIndexInBatch
)
// We now have enough information to create the message proof.
const proof: CrossDomainMessageProof = {
stateRoot: batch.stateRoots[txIndexInBatch],
stateRootBatchHeader: batch.header,
stateRootProof: {
index: txIndexInBatch,
siblings: stateRootMerkleProof,
},
stateTrieWitness: stateTrieProof.accountProof,
storageTrieWitness: stateTrieProof.storageProof,
}
messagePairs.push({
message,
proof,
})
}
return messagePairs
} | the_stack |
import { Injectable } from '@angular/core';
import { Meta, MetaDefinition, Title } from '@angular/platform-browser';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { BehaviorSubject, combineLatest, EMPTY, Observable, of as observableOf } from 'rxjs';
import { expand, filter, map, switchMap, take } from 'rxjs/operators';
import { hasNoValue, hasValue } from '../../shared/empty.util';
import { DSONameService } from '../breadcrumbs/dso-name.service';
import { BitstreamDataService } from '../data/bitstream-data.service';
import { BitstreamFormatDataService } from '../data/bitstream-format-data.service';
import { RemoteData } from '../data/remote-data';
import { BitstreamFormat } from '../shared/bitstream-format.model';
import { Bitstream } from '../shared/bitstream.model';
import { DSpaceObject } from '../shared/dspace-object.model';
import { Item } from '../shared/item.model';
import { getFirstCompletedRemoteData, getFirstSucceededRemoteDataPayload } from '../shared/operators';
import { RootDataService } from '../data/root-data.service';
import { getBitstreamDownloadRoute } from '../../app-routing-paths';
import { BundleDataService } from '../data/bundle-data.service';
import { followLink } from '../../shared/utils/follow-link-config.model';
import { Bundle } from '../shared/bundle.model';
import { PaginatedList } from '../data/paginated-list.model';
import { URLCombiner } from '../url-combiner/url-combiner';
import { HardRedirectService } from '../services/hard-redirect.service';
import { MetaTagState } from './meta-tag.reducer';
import { createSelector, select, Store } from '@ngrx/store';
import { AddMetaTagAction, ClearMetaTagAction } from './meta-tag.actions';
import { coreSelector } from '../core.selectors';
import { CoreState } from '../core.reducers';
/**
* The base selector function to select the metaTag section in the store
*/
const metaTagSelector = createSelector(
coreSelector,
(state: CoreState) => state.metaTag
);
/**
* Selector function to select the tags in use from the MetaTagState
*/
const tagsInUseSelector =
createSelector(
metaTagSelector,
(state: MetaTagState) => state.tagsInUse,
);
@Injectable()
export class MetadataService {
private currentObject: BehaviorSubject<DSpaceObject> = new BehaviorSubject<DSpaceObject>(undefined);
/**
* When generating the citation_pdf_url meta tag for Items with more than one Bitstream (and no primary Bitstream),
* the first Bitstream to match one of the following MIME types is selected.
* See {@linkcode getFirstAllowedFormatBitstreamLink}
* @private
*/
private readonly CITATION_PDF_URL_MIMETYPES = [
'application/pdf', // .pdf
'application/postscript', // .ps
'application/msword', // .doc
'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
'application/rtf', // .rtf
'application/epub+zip', // .epub
];
constructor(
private router: Router,
private translate: TranslateService,
private meta: Meta,
private title: Title,
private dsoNameService: DSONameService,
private bundleDataService: BundleDataService,
private bitstreamDataService: BitstreamDataService,
private bitstreamFormatDataService: BitstreamFormatDataService,
private rootService: RootDataService,
private store: Store<CoreState>,
private hardRedirectService: HardRedirectService,
) {
}
public listenForRouteChange(): void {
// This never changes, set it only once
this.setGenerator();
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.router.routerState.root),
map((route: ActivatedRoute) => {
route = this.getCurrentRoute(route);
return { params: route.params, data: route.data };
})).subscribe((routeInfo: any) => {
this.processRouteChange(routeInfo);
});
}
private processRouteChange(routeInfo: any): void {
this.clearMetaTags();
if (routeInfo.data.value.title) {
const titlePrefix = this.translate.get('repository.title.prefix');
const title = this.translate.get(routeInfo.data.value.title, routeInfo.data.value);
combineLatest([titlePrefix, title]).pipe(take(1)).subscribe(([translatedTitlePrefix, translatedTitle]: [string, string]) => {
this.addMetaTag('title', translatedTitlePrefix + translatedTitle);
this.title.setTitle(translatedTitlePrefix + translatedTitle);
});
}
if (routeInfo.data.value.description) {
this.translate.get(routeInfo.data.value.description).pipe(take(1)).subscribe((translatedDescription: string) => {
this.addMetaTag('description', translatedDescription);
});
}
if (hasValue(routeInfo.data.value.dso) && hasValue(routeInfo.data.value.dso.payload)) {
this.currentObject.next(routeInfo.data.value.dso.payload);
this.setDSOMetaTags();
}
}
private getCurrentRoute(route: ActivatedRoute): ActivatedRoute {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}
private setDSOMetaTags(): void {
this.setTitleTag();
this.setDescriptionTag();
this.setCitationTitleTag();
this.setCitationAuthorTags();
this.setCitationPublicationDateTag();
this.setCitationISSNTag();
this.setCitationISBNTag();
this.setCitationLanguageTag();
this.setCitationKeywordsTag();
this.setCitationAbstractUrlTag();
this.setCitationPdfUrlTag();
this.setCitationPublisherTag();
if (this.isDissertation()) {
this.setCitationDissertationNameTag();
}
// this.setCitationJournalTitleTag();
// this.setCitationVolumeTag();
// this.setCitationIssueTag();
// this.setCitationFirstPageTag();
// this.setCitationLastPageTag();
// this.setCitationDOITag();
// this.setCitationPMIDTag();
// this.setCitationFullTextTag();
// this.setCitationConferenceTag();
// this.setCitationPatentCountryTag();
// this.setCitationPatentNumberTag();
}
/**
* Add <meta name="title" ... > to the <head>
*/
private setTitleTag(): void {
const value = this.dsoNameService.getName(this.currentObject.getValue());
this.addMetaTag('title', value);
this.title.setTitle(value);
}
/**
* Add <meta name="description" ... > to the <head>
*/
private setDescriptionTag(): void {
// TODO: truncate abstract
const value = this.getMetaTagValue('dc.description.abstract');
this.addMetaTag('description', value);
}
/**
* Add <meta name="citation_title" ... > to the <head>
*/
private setCitationTitleTag(): void {
const value = this.getMetaTagValue('dc.title');
this.addMetaTag('citation_title', value);
}
/**
* Add <meta name="citation_author" ... > to the <head>
*/
private setCitationAuthorTags(): void {
const values: string[] = this.getMetaTagValues(['dc.author', 'dc.contributor.author', 'dc.creator']);
this.addMetaTags('citation_author', values);
}
/**
* Add <meta name="citation_publication_date" ... > to the <head>
*/
private setCitationPublicationDateTag(): void {
const value = this.getFirstMetaTagValue(['dc.date.copyright', 'dc.date.issued', 'dc.date.available', 'dc.date.accessioned']);
this.addMetaTag('citation_publication_date', value);
}
/**
* Add <meta name="citation_issn" ... > to the <head>
*/
private setCitationISSNTag(): void {
const value = this.getMetaTagValue('dc.identifier.issn');
this.addMetaTag('citation_issn', value);
}
/**
* Add <meta name="citation_isbn" ... > to the <head>
*/
private setCitationISBNTag(): void {
const value = this.getMetaTagValue('dc.identifier.isbn');
this.addMetaTag('citation_isbn', value);
}
/**
* Add <meta name="citation_language" ... > to the <head>
*/
private setCitationLanguageTag(): void {
const value = this.getFirstMetaTagValue(['dc.language', 'dc.language.iso']);
this.addMetaTag('citation_language', value);
}
/**
* Add <meta name="citation_dissertation_name" ... > to the <head>
*/
private setCitationDissertationNameTag(): void {
const value = this.getMetaTagValue('dc.title');
this.addMetaTag('citation_dissertation_name', value);
}
/**
* Add dc.publisher to the <head>. The tag name depends on the item type.
*/
private setCitationPublisherTag(): void {
const value = this.getMetaTagValue('dc.publisher');
if (this.isDissertation()) {
this.addMetaTag('citation_dissertation_institution', value);
} else if (this.isTechReport()) {
this.addMetaTag('citation_technical_report_institution', value);
} else {
this.addMetaTag('citation_publisher', value);
}
}
/**
* Add <meta name="citation_keywords" ... > to the <head>
*/
private setCitationKeywordsTag(): void {
const value = this.getMetaTagValuesAndCombine('dc.subject');
this.addMetaTag('citation_keywords', value);
}
/**
* Add <meta name="citation_abstract_html_url" ... > to the <head>
*/
private setCitationAbstractUrlTag(): void {
if (this.currentObject.value instanceof Item) {
let url = this.getMetaTagValue('dc.identifier.uri');
if (hasNoValue(url)) {
url = new URLCombiner(this.hardRedirectService.getCurrentOrigin(), this.router.url).toString();
}
this.addMetaTag('citation_abstract_html_url', url);
}
}
/**
* Add <meta name="citation_pdf_url" ... > to the <head>
*/
private setCitationPdfUrlTag(): void {
if (this.currentObject.value instanceof Item) {
const item = this.currentObject.value as Item;
// Retrieve the ORIGINAL bundle for the item
this.bundleDataService.findByItemAndName(
item,
'ORIGINAL',
true,
true,
followLink('primaryBitstream'),
followLink('bitstreams', {}, followLink('format')),
).pipe(
getFirstSucceededRemoteDataPayload(),
switchMap((bundle: Bundle) =>
// First try the primary bitstream
bundle.primaryBitstream.pipe(
getFirstCompletedRemoteData(),
map((rd: RemoteData<Bitstream>) => {
if (hasValue(rd.payload)) {
return rd.payload;
} else {
return null;
}
}),
// return the bundle as well so we can use it again if there's no primary bitstream
map((bitstream: Bitstream) => [bundle, bitstream])
)
),
switchMap(([bundle, primaryBitstream]: [Bundle, Bitstream]) => {
if (hasValue(primaryBitstream)) {
// If there was a primary bitstream, emit its link
return [getBitstreamDownloadRoute(primaryBitstream)];
} else {
// Otherwise consider the regular bitstreams in the bundle
return bundle.bitstreams.pipe(
getFirstCompletedRemoteData(),
switchMap((bitstreamRd: RemoteData<PaginatedList<Bitstream>>) => {
if (hasValue(bitstreamRd.payload) && bitstreamRd.payload.totalElements === 1) {
// If there's only one bitstream in the bundle, emit its link
return [getBitstreamDownloadRoute(bitstreamRd.payload.page[0])];
} else {
// Otherwise check all bitstreams to see if one matches the format whitelist
return this.getFirstAllowedFormatBitstreamLink(bitstreamRd);
}
})
);
}
}),
take(1)
).subscribe((link: string) => {
// Use the found link to set the <meta> tag
this.addMetaTag(
'citation_pdf_url',
new URLCombiner(this.hardRedirectService.getCurrentOrigin(), link).toString()
);
});
}
}
/**
* For Items with more than one Bitstream (and no primary Bitstream), link to the first Bitstream with a MIME type
* included in {@linkcode CITATION_PDF_URL_MIMETYPES}
* @param bitstreamRd
* @private
*/
private getFirstAllowedFormatBitstreamLink(bitstreamRd: RemoteData<PaginatedList<Bitstream>>): Observable<string> {
return observableOf(bitstreamRd.payload).pipe(
// Because there can be more than one page of bitstreams, this expand operator
// will retrieve them in turn. Due to the take(1) at the bottom, it will only
// retrieve pages until a match is found
expand((paginatedList: PaginatedList<Bitstream>) => {
if (hasNoValue(paginatedList.next)) {
// If there's no next page, stop.
return EMPTY;
} else {
// Otherwise retrieve the next page
return this.bitstreamDataService.findAllByHref(
paginatedList.next,
undefined,
true,
true,
followLink('format')
).pipe(
getFirstCompletedRemoteData(),
map((next: RemoteData<PaginatedList<Bitstream>>) => {
if (hasValue(next.payload)) {
return next.payload;
} else {
return EMPTY;
}
})
);
}
}),
// Return the array of bitstreams inside each paginated list
map((paginatedList: PaginatedList<Bitstream>) => paginatedList.page),
// Emit the bitstreams in the list one at a time
switchMap((bitstreams: Bitstream[]) => bitstreams),
// Retrieve the format for each bitstream
switchMap((bitstream: Bitstream) => bitstream.format.pipe(
getFirstSucceededRemoteDataPayload(),
// Keep the original bitstream, because it, not the format, is what we'll need
// for the link at the end
map((format: BitstreamFormat) => [bitstream, format])
)),
// Filter out only pairs with whitelisted formats
filter(([, format]: [Bitstream, BitstreamFormat]) =>
hasValue(format) && this.CITATION_PDF_URL_MIMETYPES.includes(format.mimetype)),
// We only need 1
take(1),
// Emit the link of the match
map(([bitstream, ]: [Bitstream, BitstreamFormat]) => getBitstreamDownloadRoute(bitstream))
);
}
/**
* Add <meta name="Generator" ... > to the <head> containing the current DSpace version
*/
private setGenerator(): void {
this.rootService.findRoot().pipe(getFirstSucceededRemoteDataPayload()).subscribe((root) => {
this.meta.addTag({ name: 'Generator', content: root.dspaceVersion });
});
}
private hasType(value: string): boolean {
return this.currentObject.value.hasMetadata('dc.type', { value: value, ignoreCase: true });
}
/**
* Returns true if this._item is a dissertation
*
* @returns {boolean}
* true if this._item has a dc.type equal to 'Thesis'
*/
private isDissertation(): boolean {
return this.hasType('thesis');
}
/**
* Returns true if this._item is a technical report
*
* @returns {boolean}
* true if this._item has a dc.type equal to 'Technical Report'
*/
private isTechReport(): boolean {
return this.hasType('technical report');
}
private getMetaTagValue(key: string): string {
return this.currentObject.value.firstMetadataValue(key);
}
private getFirstMetaTagValue(keys: string[]): string {
return this.currentObject.value.firstMetadataValue(keys);
}
private getMetaTagValuesAndCombine(key: string): string {
return this.getMetaTagValues([key]).join('; ');
}
private getMetaTagValues(keys: string[]): string[] {
return this.currentObject.value.allMetadataValues(keys);
}
private addMetaTag(name: string, content: string): void {
if (content) {
const tag = { name, content } as MetaDefinition;
this.meta.addTag(tag);
this.storeTag(name);
}
}
private addMetaTags(name: string, content: string[]): void {
for (const value of content) {
this.addMetaTag(name, value);
}
}
private storeTag(key: string): void {
this.store.dispatch(new AddMetaTagAction(key));
}
public clearMetaTags() {
this.store.pipe(
select(tagsInUseSelector),
take(1)
).subscribe((tagsInUse: string[]) => {
for (const name of tagsInUse) {
this.meta.removeTag('name=\'' + name + '\'');
}
this.store.dispatch(new ClearMetaTagAction());
});
}
} | the_stack |
import Output from 'cloudform-types/types/output';
import AppSync from 'cloudform-types/types/appSync';
import IAM from 'cloudform-types/types/iam';
import Template from 'cloudform-types/types/template';
import { Fn, StringParameter, NumberParameter, Lambda, Elasticsearch, Refs } from 'cloudform-types';
import {
ElasticsearchMappingTemplate,
print,
str,
ref,
obj,
set,
iff,
list,
raw,
forEach,
compoundExpression,
qref,
toJson,
ifElse,
int,
Expression,
bool,
methodCall,
} from 'graphql-mapping-template';
import { toUpper, plurality, graphqlName, ResourceConstants, ModelResourceIDs } from 'graphql-transformer-common';
import { MappingParameters } from 'graphql-transformer-core/src/TransformerContext';
export class ResourceFactory {
public makeParams() {
return {
[ResourceConstants.PARAMETERS.ElasticsearchAccessIAMRoleName]: new StringParameter({
Description: 'The name of the IAM role assumed by AppSync for Elasticsearch.',
Default: 'AppSyncElasticsearchRole',
}),
[ResourceConstants.PARAMETERS.ElasticsearchStreamingLambdaHandlerName]: new StringParameter({
Description: 'The name of the lambda handler.',
Default: 'python_streaming_function.lambda_handler',
}),
[ResourceConstants.PARAMETERS.ElasticsearchStreamingLambdaRuntime]: new StringParameter({
Description: `The lambda runtime \
(https://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html#SSS-CreateFunction-request-Runtime)`,
Default: 'python3.6',
}),
[ResourceConstants.PARAMETERS.ElasticsearchStreamingFunctionName]: new StringParameter({
Description: 'The name of the streaming lambda function.',
Default: 'DdbToEsFn',
}),
[ResourceConstants.PARAMETERS.ElasticsearchStreamingIAMRoleName]: new StringParameter({
Description: 'The name of the streaming lambda function IAM role.',
Default: 'SearchableLambdaIAMRole',
}),
[ResourceConstants.PARAMETERS.ElasticsearchDebugStreamingLambda]: new NumberParameter({
Description: 'Enable debug logs for the Dynamo -> ES streaming lambda.',
Default: 1,
AllowedValues: [0, 1],
}),
[ResourceConstants.PARAMETERS.ElasticsearchInstanceCount]: new NumberParameter({
Description: 'The number of instances to launch into the Elasticsearch domain.',
Default: 1,
}),
[ResourceConstants.PARAMETERS.ElasticsearchInstanceType]: new StringParameter({
Description: 'The type of instance to launch into the Elasticsearch domain.',
Default: 't2.small.elasticsearch',
AllowedValues: [
't2.small.elasticsearch',
't2.medium.elasticsearch',
'c4.large.elasticsearch',
'c4.xlarge.elasticsearch',
'c4.2xlarge.elasticsearch',
'c4.4xlarge.elasticsearch',
'c4.8xlarge.elasticsearch',
'm3.medium.elasticsearch',
'm3.large.elasticsearch',
'm3.xlarge.elasticsearch',
'm3.2xlarge.elasticsearch',
'm4.large.elasticsearch',
'm4.xlarge.elasticsearch',
'm4.2xlarge.elasticsearch',
'm4.4xlarge.elasticsearch',
'm4.10xlarge.elasticsearch',
'r3.large.elasticsearch',
'r3.xlarge.elasticsearch',
'r3.2xlarge.elasticsearch',
'r3.4xlarge.elasticsearch',
'r3.8xlarge.elasticsearch',
'r4.large.elasticsearch',
'r4.xlarge.elasticsearch',
'r4.2xlarge.elasticsearch',
'r4.4xlarge.elasticsearch',
'r4.8xlarge.elasticsearch',
'r4.16xlarge.elasticsearch',
'i2.xlarge.elasticsearch',
'i2.2xlarge.elasticsearch',
'i3.large.elasticsearch',
'i3.xlarge.elasticsearch',
'i3.2xlarge.elasticsearch',
'i3.4xlarge.elasticsearch',
'i3.8xlarge.elasticsearch',
'i3.16xlarge.elasticsearch',
'r6gd.12xlarge.elasticsearch',
'ultrawarm1.xlarge.elasticsearch',
'm5.4xlarge.elasticsearch',
't3.xlarge.elasticsearch',
'm6g.xlarge.elasticsearch',
'm6g.12xlarge.elasticsearch',
't2.micro.elasticsearch',
'r6gd.16xlarge.elasticsearch',
'd2.2xlarge.elasticsearch',
't3.micro.elasticsearch',
'm5.large.elasticsearch',
'd2.4xlarge.elasticsearch',
't3.small.elasticsearch',
'c5.2xlarge.elasticsearch',
'c6g.2xlarge.elasticsearch',
'd2.8xlarge.elasticsearch',
'c5.4xlarge.elasticsearch',
't4g.medium.elasticsearch',
'c6g.4xlarge.elasticsearch',
'c6g.xlarge.elasticsearch',
'c6g.12xlarge.elasticsearch',
],
}),
[ResourceConstants.PARAMETERS.ElasticsearchEBSVolumeGB]: new NumberParameter({
Description: 'The size in GB of the EBS volumes that contain our data.',
Default: 10,
}),
};
}
/**
* Creates the barebones template for an application.
*/
public initTemplate(isProjectUsingDataStore: boolean = false): Template {
return {
Parameters: this.makeParams(),
Resources: {
[ResourceConstants.RESOURCES.ElasticsearchAccessIAMRoleLogicalID]: this.makeElasticsearchAccessIAMRole(),
[ResourceConstants.RESOURCES.ElasticsearchDataSourceLogicalID]: this.makeElasticsearchDataSource(),
[ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID]: this.makeElasticsearchDomain(),
[ResourceConstants.RESOURCES.ElasticsearchStreamingLambdaIAMRoleLogicalID]: this.makeStreamingLambdaIAMRole(),
[ResourceConstants.RESOURCES.ElasticsearchStreamingLambdaFunctionLogicalID]:
this.makeDynamoDBStreamingFunction(isProjectUsingDataStore),
},
Mappings: this.getLayerMapping(),
Outputs: {
[ResourceConstants.OUTPUTS.ElasticsearchDomainArn]: this.makeDomainArnOutput(),
[ResourceConstants.OUTPUTS.ElasticsearchDomainEndpoint]: this.makeDomainEndpointOutput(),
},
};
}
/**
* Given the name of a data source and optional logical id return a CF
* spec for a data source pointing to the elasticsearch domain.
* @param name The name for the data source. If a logicalId is not provided the name is used.
* @param logicalId The logicalId of the domain if it is different than the name of the data source.
*/
public makeElasticsearchDataSource() {
const logicalName = ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID;
return new AppSync.DataSource({
ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
Name: logicalName,
Type: 'AMAZON_ELASTICSEARCH',
ServiceRoleArn: Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchAccessIAMRoleLogicalID, 'Arn'),
ElasticsearchConfig: {
AwsRegion: Fn.Select(3, Fn.Split(':', Fn.GetAtt(logicalName, 'DomainArn'))),
Endpoint: Fn.Join('', ['https://', Fn.GetAtt(logicalName, 'DomainEndpoint')]),
},
}).dependsOn(ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID);
}
public getLayerMapping(): MappingParameters {
return {
LayerResourceMapping: {
'ap-northeast-1': {
layerRegion: 'arn:aws:lambda:ap-northeast-1:249908578461:layer:AWSLambda-Python-AWS-SDK:1',
},
'us-east-1': {
layerRegion: 'arn:aws:lambda:us-east-1:668099181075:layer:AWSLambda-Python-AWS-SDK:1',
},
'ap-southeast-1': {
layerRegion: 'arn:aws:lambda:ap-southeast-1:468957933125:layer:AWSLambda-Python-AWS-SDK:1',
},
'eu-west-1': {
layerRegion: 'arn:aws:lambda:eu-west-1:399891621064:layer:AWSLambda-Python-AWS-SDK:1',
},
'us-west-1': {
layerRegion: 'arn:aws:lambda:us-west-1:325793726646:layer:AWSLambda-Python-AWS-SDK:1',
},
'ap-east-1': {
layerRegion: 'arn:aws:lambda:ap-east-1:118857876118:layer:AWSLambda-Python-AWS-SDK:1',
},
'ap-northeast-2': {
layerRegion: 'arn:aws:lambda:ap-northeast-2:296580773974:layer:AWSLambda-Python-AWS-SDK:1',
},
'ap-northeast-3': {
layerRegion: 'arn:aws:lambda:ap-northeast-3:961244031340:layer:AWSLambda-Python-AWS-SDK:1',
},
'ap-south-1': {
layerRegion: 'arn:aws:lambda:ap-south-1:631267018583:layer:AWSLambda-Python-AWS-SDK:1',
},
'ap-southeast-2': {
layerRegion: 'arn:aws:lambda:ap-southeast-2:817496625479:layer:AWSLambda-Python-AWS-SDK:1',
},
'ca-central-1': {
layerRegion: 'arn:aws:lambda:ca-central-1:778625758767:layer:AWSLambda-Python-AWS-SDK:1',
},
'eu-central-1': {
layerRegion: 'arn:aws:lambda:eu-central-1:292169987271:layer:AWSLambda-Python-AWS-SDK:1',
},
'eu-north-1': {
layerRegion: 'arn:aws:lambda:eu-north-1:642425348156:layer:AWSLambda-Python-AWS-SDK:1',
},
'eu-west-2': {
layerRegion: 'arn:aws:lambda:eu-west-2:142628438157:layer:AWSLambda-Python-AWS-SDK:1',
},
'eu-west-3': {
layerRegion: 'arn:aws:lambda:eu-west-3:959311844005:layer:AWSLambda-Python-AWS-SDK:1',
},
'sa-east-1': {
layerRegion: 'arn:aws:lambda:sa-east-1:640010853179:layer:AWSLambda-Python-AWS-SDK:1',
},
'us-east-2': {
layerRegion: 'arn:aws:lambda:us-east-2:259788987135:layer:AWSLambda-Python-AWS-SDK:1',
},
'us-west-2': {
layerRegion: 'arn:aws:lambda:us-west-2:420165488524:layer:AWSLambda-Python-AWS-SDK:1',
},
'cn-north-1': {
layerRegion: 'arn:aws-cn:lambda:cn-north-1:683298794825:layer:AWSLambda-Python-AWS-SDK:1',
},
'cn-northwest-1': {
layerRegion: 'arn:aws-cn:lambda:cn-northwest-1:382066503313:layer:AWSLambda-Python-AWS-SDK:1',
},
'us-gov-west-1': {
layerRegion: 'arn:aws-us-gov:lambda:us-gov-west-1:556739011827:layer:AWSLambda-Python-AWS-SDK:1',
},
'us-gov-east-1': {
layerRegion: 'arn:aws-us-gov:lambda:us-gov-east-1:138526772879:layer:AWSLambda-Python-AWS-SDK:1',
},
'me-south-1': {
layerRegion: 'arn:aws:lambda:me-south-1:507411403535:layer:AWSLambda-Python-AWS-SDK:1',
},
},
};
}
/**
* Deploy a lambda function that will stream data from our DynamoDB table
* to our elasticsearch index.
*/
public makeDynamoDBStreamingFunction(isProjectUsingDataStore: boolean = false) {
return new Lambda.Function({
Code: {
S3Bucket: Fn.Ref(ResourceConstants.PARAMETERS.S3DeploymentBucket),
S3Key: Fn.Join('/', [
Fn.Ref(ResourceConstants.PARAMETERS.S3DeploymentRootKey),
'functions',
Fn.Join('.', [ResourceConstants.RESOURCES.ElasticsearchStreamingLambdaFunctionLogicalID, 'zip']),
]),
},
FunctionName: this.joinWithEnv('-', [
Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchStreamingFunctionName),
Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
]),
Handler: Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchStreamingLambdaHandlerName),
Role: Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchStreamingLambdaIAMRoleLogicalID, 'Arn'),
Runtime: Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchStreamingLambdaRuntime),
Layers: [Fn.FindInMap('LayerResourceMapping', Fn.Ref('AWS::Region'), 'layerRegion')],
Environment: {
Variables: {
ES_ENDPOINT: Fn.Join('', ['https://', Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID, 'DomainEndpoint')]),
ES_REGION: Fn.Select(3, Fn.Split(':', Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID, 'DomainArn'))),
DEBUG: Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchDebugStreamingLambda),
ES_USE_EXTERNAL_VERSIONING: isProjectUsingDataStore.toString(),
},
},
}).dependsOn([
ResourceConstants.RESOURCES.ElasticsearchStreamingLambdaIAMRoleLogicalID,
ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID,
]);
}
public makeDynamoDBStreamEventSourceMapping(typeName: string) {
return new Lambda.EventSourceMapping({
BatchSize: 1,
Enabled: true,
EventSourceArn: Fn.GetAtt(ModelResourceIDs.ModelTableResourceID(typeName), 'StreamArn'),
FunctionName: Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchStreamingLambdaFunctionLogicalID, 'Arn'),
StartingPosition: 'LATEST',
}).dependsOn([ResourceConstants.RESOURCES.ElasticsearchStreamingLambdaFunctionLogicalID]);
}
private joinWithEnv(separator: string, listToJoin: any[]) {
return Fn.If(
ResourceConstants.CONDITIONS.HasEnvironmentParameter,
Fn.Join(separator, [...listToJoin, Fn.Ref(ResourceConstants.PARAMETERS.Env)]),
Fn.Join(separator, listToJoin),
);
}
/**
* Create a single role that has access to all the resources created by the
* transform.
* @param name The name of the IAM role to create.
*/
public makeElasticsearchAccessIAMRole() {
return new IAM.Role({
RoleName: this.joinWithEnv('-', [
Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchAccessIAMRoleName),
Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
]),
AssumeRolePolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: {
Service: 'appsync.amazonaws.com',
},
Action: 'sts:AssumeRole',
},
],
},
Policies: [
new IAM.Role.Policy({
PolicyName: 'ElasticsearchAccess',
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: ['es:ESHttpPost', 'es:ESHttpDelete', 'es:ESHttpHead', 'es:ESHttpGet', 'es:ESHttpPost', 'es:ESHttpPut'],
Effect: 'Allow',
Resource: Fn.Join('', [this.domainArn(), '/*']),
},
],
},
}),
],
});
}
/**
* Create a single role that has access to all the resources created by the
* transform.
* @param name The name of the IAM role to create.
*/
public makeStreamingLambdaIAMRole() {
return new IAM.Role({
RoleName: this.joinWithEnv('-', [
Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchStreamingIAMRoleName),
Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
]),
AssumeRolePolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: {
Service: 'lambda.amazonaws.com',
},
Action: 'sts:AssumeRole',
},
],
},
Policies: [
new IAM.Role.Policy({
PolicyName: 'ElasticsearchAccess',
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: ['es:ESHttpPost', 'es:ESHttpDelete', 'es:ESHttpHead', 'es:ESHttpGet', 'es:ESHttpPost', 'es:ESHttpPut'],
Effect: 'Allow',
Resource: Fn.Join('', [this.domainArn(), '/*']),
},
],
},
}),
new IAM.Role.Policy({
PolicyName: 'DynamoDBStreamAccess',
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: ['dynamodb:DescribeStream', 'dynamodb:GetRecords', 'dynamodb:GetShardIterator', 'dynamodb:ListStreams'],
Effect: 'Allow',
Resource: [
'*',
// TODO: Scope this to each table individually.
// Fn.Join(
// '/',
// [Fn.GetAtt(ResourceConstants.RESOURCES.DynamoDBModelTableLogicalID, 'Arn'), '*']
// )
],
},
],
},
}),
new IAM.Role.Policy({
PolicyName: 'CloudWatchLogsAccess',
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Action: ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'],
Resource: 'arn:aws:logs:*:*:*',
},
],
},
}),
],
});
// .dependsOn(ResourceConstants.RESOURCES.DynamoDBModelTableLogicalID)
}
/**
* If there is an env, allow ES to create the domain name so we don't go
* over 28 characters. If there is no env, fallback to original behavior.
*/
private domainName() {
return Fn.If(
ResourceConstants.CONDITIONS.HasEnvironmentParameter,
Refs.NoValue,
Fn.Join('-', ['d', Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId')]),
);
}
private domainArn() {
return Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID, 'DomainArn');
}
/**
* Create the elasticsearch domain.
*/
public makeElasticsearchDomain() {
return new Elasticsearch.Domain({
DomainName: this.domainName(),
ElasticsearchVersion: '6.2',
ElasticsearchClusterConfig: {
ZoneAwarenessEnabled: false,
InstanceCount: Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchInstanceCount),
InstanceType: Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchInstanceType),
},
EBSOptions: {
EBSEnabled: true,
VolumeType: 'gp2',
VolumeSize: Fn.Ref(ResourceConstants.PARAMETERS.ElasticsearchEBSVolumeGB),
},
});
}
/**
* Create the Elasticsearch search resolver.
*/
public makeSearchResolver(
type: string,
nonKeywordFields: Expression[],
primaryKey: string,
queryTypeName: string,
improvePluralization: boolean,
nameOverride?: string,
includeVersion: boolean = false,
) {
const fieldName = nameOverride ? nameOverride : graphqlName('search' + plurality(toUpper(type), improvePluralization));
return new AppSync.Resolver({
ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
DataSourceName: Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchDataSourceLogicalID, 'Name'),
FieldName: fieldName,
TypeName: queryTypeName,
RequestMappingTemplate: print(
compoundExpression([
set(ref('indexPath'), str(`/${type.toLowerCase()}/doc/_search`)),
set(ref('nonKeywordFields'), list(nonKeywordFields)),
ifElse(
ref('util.isNullOrEmpty($context.args.sort)'),
compoundExpression([set(ref('sortDirection'), str('desc')), set(ref('sortField'), str(primaryKey))]),
compoundExpression([
set(ref('sortDirection'), ref('util.defaultIfNull($context.args.sort.direction, "desc")')),
set(ref('sortField'), ref(`util.defaultIfNull($context.args.sort.field, "${primaryKey}")`)),
]),
),
ifElse(
ref('nonKeywordFields.contains($sortField)'),
compoundExpression([set(ref('sortField0'), ref('util.toJson($sortField)'))]),
compoundExpression([set(ref('sortField0'), ref('util.toJson("${sortField}.keyword")'))]),
),
ElasticsearchMappingTemplate.searchItem({
path: str('$indexPath'),
size: ifElse(ref('context.args.limit'), ref('context.args.limit'), int(ResourceConstants.DEFAULT_SEARCHABLE_PAGE_LIMIT), true),
search_after: list([ref('util.toJson($context.args.nextToken)')]),
from: ref('context.args.from'),
version: bool(includeVersion),
query: ifElse(
ref('context.args.filter'),
ref('util.transform.toElasticsearchQueryDSL($ctx.args.filter)'),
obj({
match_all: obj({}),
}),
),
sort: list([raw('{$sortField0: { "order" : $util.toJson($sortDirection) }}')]),
}),
]),
),
ResponseMappingTemplate: print(
compoundExpression([
set(ref('es_items'), list([])),
forEach(ref('entry'), ref('context.result.hits.hits'), [
iff(raw('!$foreach.hasNext'), set(ref('nextToken'), ref('entry.sort.get(0)'))),
...this.getSourceMapper(includeVersion),
]),
toJson(
obj({
items: ref('es_items'),
total: ref('ctx.result.hits.total'),
nextToken: ref('nextToken'),
}),
),
]),
),
}).dependsOn([ResourceConstants.RESOURCES.ElasticsearchDataSourceLogicalID]);
}
private getSourceMapper = (includeVersion: boolean) => {
if (includeVersion) {
return [
set(ref('row'), methodCall(ref('entry.get'), str('_source'))),
qref('$row.put("_version", $entry.get("_version"))'),
qref('$es_items.add($row)'),
];
}
return [qref('$es_items.add($entry.get("_source"))')];
};
/**
* OUTPUTS
*/
/**
* Create output to export the Elasticsearch DomainArn
* @returns Output
*/
public makeDomainArnOutput(): Output {
return {
Description: 'Elasticsearch instance Domain ARN.',
Value: Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID, 'DomainArn'),
Export: {
Name: Fn.Join(':', [Fn.Ref(ResourceConstants.PARAMETERS.AppSyncApiId), 'GetAtt', 'Elasticsearch', 'DomainArn']),
},
};
}
/**
* Create output to export the Elasticsearch DomainEndpoint
* @returns Output
*/
public makeDomainEndpointOutput(): Output {
return {
Description: 'Elasticsearch instance Domain Endpoint.',
Value: Fn.Join('', ['https://', Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchDomainLogicalID, 'DomainEndpoint')]),
Export: {
Name: Fn.Join(':', [Fn.Ref(ResourceConstants.PARAMETERS.AppSyncApiId), 'GetAtt', 'Elasticsearch', 'DomainEndpoint']),
},
};
}
} | the_stack |
import * as React from 'react';
import { IEvents } from '../Events';
import { ScriptLoader } from '../ScriptLoader';
import { getTinymce } from '../TinyMCE';
import { isFunction, isTextareaOrInput, mergePlugins, uuid, configHandlers, isBeforeInputEventAvailable, isInDoc } from '../Utils';
import { EditorPropTypes, IEditorPropTypes } from './EditorPropTypes';
import { Bookmark, Editor as TinyMCEEditor, EditorEvent, RawEditorSettings } from 'tinymce';
export interface IProps {
apiKey: string;
id: string;
inline: boolean;
initialValue: string;
onEditorChange: (a: string, editor: TinyMCEEditor) => void;
value: string;
init: RawEditorSettings & { selector?: undefined; target?: undefined };
/** @deprecated use `editor.getContent({format: 'text' })` in `onEditorChange` prop instead */
outputFormat: 'html' | 'text';
tagName: string;
cloudChannel: string;
plugins: NonNullable<RawEditorSettings['plugins']>;
toolbar: NonNullable<RawEditorSettings['toolbar']>;
disabled: boolean;
textareaName: string;
tinymceScriptSrc: string;
rollback: number | false;
scriptLoading: {
async?: boolean;
defer?: boolean;
delay?: number;
};
}
export interface IAllProps extends Partial<IProps>, Partial<IEvents> { }
const changeEvents = () => getTinymce()?.Env?.browser?.isIE() ? 'change keyup compositionend setcontent' : 'change input compositionend setcontent';
const beforeInputEvent = () => isBeforeInputEventAvailable() ? 'beforeinput SelectionChange' : 'SelectionChange';
export class Editor extends React.Component<IAllProps> {
public static propTypes: IEditorPropTypes = EditorPropTypes;
public static defaultProps: Partial<IAllProps> = {
cloudChannel: '5'
};
public editor?: TinyMCEEditor;
private id: string;
private elementRef: React.RefObject<HTMLElement>;
private inline: boolean;
private currentContent?: string;
private boundHandlers: Record<string, (event: EditorEvent<unknown>) => unknown>;
private rollbackTimer: number | undefined = undefined;
private valueCursor: Bookmark | undefined = undefined;
public constructor(props: Partial<IAllProps>) {
super(props);
this.id = this.props.id || uuid('tiny-react');
this.elementRef = React.createRef<HTMLElement>();
this.inline = this.props.inline ?? this.props.init?.inline ?? false;
this.boundHandlers = {};
}
public componentDidUpdate(prevProps: Partial<IAllProps>) {
if (this.rollbackTimer) {
clearTimeout(this.rollbackTimer);
this.rollbackTimer = undefined;
}
if (this.editor) {
this.bindHandlers(prevProps);
if (this.editor.initialized) {
this.currentContent = this.currentContent ?? this.editor.getContent();
if (typeof this.props.initialValue === 'string' && this.props.initialValue !== prevProps.initialValue) {
// same as resetContent in TinyMCE 5
this.editor.setContent(this.props.initialValue);
this.editor.undoManager.clear();
this.editor.undoManager.add();
this.editor.setDirty(false);
} else if (typeof this.props.value === 'string' && this.props.value !== this.currentContent) {
const localEditor = this.editor;
localEditor.undoManager.transact(() => {
// inline editors grab focus when restoring selection
// so we don't try to keep their selection unless they are currently focused
let cursor: Bookmark | undefined;
if (!this.inline || localEditor.hasFocus()) {
try {
// getBookmark throws exceptions when the editor has not been focused
// possibly only in inline mode but I'm not taking chances
cursor = localEditor.selection.getBookmark(3);
} catch (e) { /* ignore */ }
}
const valueCursor = this.valueCursor;
localEditor.setContent(this.props.value as string);
if (!this.inline || localEditor.hasFocus()) {
for (const bookmark of [ cursor, valueCursor ]) {
if (bookmark) {
try {
localEditor.selection.moveToBookmark(bookmark);
this.valueCursor = bookmark;
break;
} catch (e) { /* ignore */ }
}
}
}
});
}
if (this.props.disabled !== prevProps.disabled) {
const disabled = this.props.disabled ?? false;
this.editor.setMode(disabled ? 'readonly' : 'design');
}
}
}
}
public componentDidMount() {
if (getTinymce() !== null) {
this.initialise();
} else if (this.elementRef.current && this.elementRef.current.ownerDocument) {
ScriptLoader.load(
this.elementRef.current.ownerDocument,
this.getScriptSrc(),
this.props.scriptLoading?.async ?? false,
this.props.scriptLoading?.defer ?? false,
this.props.scriptLoading?.delay ?? 0,
this.initialise
);
}
}
public componentWillUnmount() {
const editor = this.editor;
if (editor) {
editor.off(changeEvents(), this.handleEditorChange);
editor.off(beforeInputEvent(), this.handleBeforeInput);
editor.off('keypress', this.handleEditorChangeSpecial);
editor.off('keydown', this.handleBeforeInputSpecial);
editor.off('NewBlock', this.handleEditorChange);
Object.keys(this.boundHandlers).forEach((eventName) => {
editor.off(eventName, this.boundHandlers[eventName]);
});
this.boundHandlers = {};
editor.remove();
this.editor = undefined;
}
}
public render() {
return this.inline ? this.renderInline() : this.renderIframe();
}
private renderInline() {
const { tagName = 'div' } = this.props;
return React.createElement(tagName, {
ref: this.elementRef,
id: this.id
});
}
private renderIframe() {
return React.createElement('textarea', {
ref: this.elementRef,
style: { visibility: 'hidden' },
name: this.props.textareaName,
id: this.id
});
}
private getScriptSrc() {
if (typeof this.props.tinymceScriptSrc === 'string') {
return this.props.tinymceScriptSrc;
} else {
const channel = this.props.cloudChannel;
const apiKey = this.props.apiKey ? this.props.apiKey : 'no-api-key';
return `https://cdn.tiny.cloud/1/${apiKey}/tinymce/${channel}/tinymce.min.js`;
}
}
private getInitialValue() {
if (typeof this.props.initialValue === 'string') {
return this.props.initialValue;
} else if (typeof this.props.value === 'string') {
return this.props.value;
} else {
return '';
}
}
private bindHandlers(prevProps: Partial<IAllProps>) {
if (this.editor !== undefined) {
// typescript chokes trying to understand the type of the lookup function
configHandlers(this.editor, prevProps, this.props, this.boundHandlers, (key) => this.props[key] as any);
// check if we should monitor editor changes
const isValueControlled = (p: Partial<IAllProps>) => p.onEditorChange !== undefined || p.value !== undefined;
const wasControlled = isValueControlled(prevProps);
const nowControlled = isValueControlled(this.props);
if (!wasControlled && nowControlled) {
this.editor.on(changeEvents(), this.handleEditorChange);
this.editor.on(beforeInputEvent(), this.handleBeforeInput);
this.editor.on('keydown', this.handleBeforeInputSpecial);
this.editor.on('keyup', this.handleEditorChangeSpecial);
this.editor.on('NewBlock', this.handleEditorChange);
} else if (wasControlled && !nowControlled) {
this.editor.off(changeEvents(), this.handleEditorChange);
this.editor.off(beforeInputEvent(), this.handleBeforeInput);
this.editor.off('keydown', this.handleBeforeInputSpecial);
this.editor.off('keyup', this.handleEditorChangeSpecial);
this.editor.off('NewBlock', this.handleEditorChange);
}
}
}
private rollbackChange = () => {
const editor = this.editor;
const value = this.props.value;
if (editor && value && value !== this.currentContent) {
editor.undoManager.ignore(() => {
editor.setContent(value);
// only restore cursor on inline editors when they are focused
// as otherwise it will cause a focus grab
if (this.valueCursor && (!this.inline || editor.hasFocus())) {
try {
editor.selection.moveToBookmark(this.valueCursor);
} catch (e) { /* ignore */ }
}
});
}
this.rollbackTimer = undefined;
};
private handleBeforeInput = (_evt: EditorEvent<unknown>) => {
if (this.props.value !== undefined && this.props.value === this.currentContent && this.editor) {
if (!this.inline || this.editor.hasFocus) {
try {
// getBookmark throws exceptions when the editor has not been focused
// possibly only in inline mode but I'm not taking chances
this.valueCursor = this.editor.selection.getBookmark(3);
} catch (e) { /* ignore */ }
}
}
};
private handleBeforeInputSpecial = (evt: EditorEvent<KeyboardEvent>) => {
if (evt.key === 'Enter' || evt.key === 'Backspace' || evt.key === 'Delete') {
this.handleBeforeInput(evt);
}
};
private handleEditorChange = (_evt: EditorEvent<unknown>) => {
const editor = this.editor;
if (editor && editor.initialized) {
const newContent = editor.getContent();
if (this.props.value !== undefined && this.props.value !== newContent && this.props.rollback !== false) {
// start a timer and revert to the value if not applied in time
if (!this.rollbackTimer) {
this.rollbackTimer = window.setTimeout(
this.rollbackChange,
typeof this.props.rollback === 'number' ? this.props.rollback : 200
);
}
}
if (newContent !== this.currentContent) {
this.currentContent = newContent;
if (isFunction(this.props.onEditorChange)) {
const format = this.props.outputFormat;
const out = format === 'html' ? newContent : editor.getContent({ format });
this.props.onEditorChange(out, editor);
}
}
}
};
private handleEditorChangeSpecial = (evt: EditorEvent<KeyboardEvent>) => {
if (evt.key === 'Backspace' || evt.key === 'Delete') {
this.handleEditorChange(evt);
}
};
private initialise = (attempts = 0) => {
const target = this.elementRef.current;
if (!target) {
return; // Editor has been unmounted
}
if (!isInDoc(target)) {
// this is probably someone trying to help by rendering us offscreen
// but we can't do that because the editor iframe must be in the document
// in order to have state
if (attempts === 0) {
// we probably just need to wait for the current events to be processed
setTimeout(() => this.initialise(1), 1);
} else if (attempts < 100) {
// wait for ten seconds, polling every tenth of a second
setTimeout(() => this.initialise(attempts + 1), 100);
} else {
// give up, at this point it seems that more polling is unlikely to help
throw new Error('tinymce can only be initialised when in a document');
}
return;
}
const tinymce = getTinymce();
if (!tinymce) {
throw new Error('tinymce should have been loaded into global scope');
}
const finalInit: RawEditorSettings = {
...this.props.init,
selector: undefined,
target,
readonly: this.props.disabled,
inline: this.inline,
plugins: mergePlugins(this.props.init?.plugins, this.props.plugins),
toolbar: this.props.toolbar ?? this.props.init?.toolbar,
setup: (editor) => {
this.editor = editor;
this.bindHandlers({});
// When running in inline mode the editor gets the initial value
// from the innerHTML of the element it is initialized on.
// However we don't want to take on the responsibility of sanitizing
// to remove XSS in the react integration so we have a chicken and egg
// problem... We avoid it by sneaking in a set content before the first
// "official" setContent and using TinyMCE to do the sanitization.
if (this.inline && !isTextareaOrInput(target)) {
editor.once('PostRender', (_evt) => {
editor.setContent(this.getInitialValue(), { no_events: true });
});
}
if (this.props.init && isFunction(this.props.init.setup)) {
this.props.init.setup(editor);
}
},
init_instance_callback: (editor) => {
// check for changes that happened since tinymce.init() was called
const initialValue = this.getInitialValue();
this.currentContent = this.currentContent ?? editor.getContent();
if (this.currentContent !== initialValue) {
this.currentContent = initialValue;
// same as resetContent in TinyMCE 5
editor.setContent(initialValue);
editor.undoManager.clear();
editor.undoManager.add();
editor.setDirty(false);
}
const disabled = this.props.disabled ?? false;
editor.setMode(disabled ? 'readonly' : 'design');
// ensure existing init_instance_callback is called
if (this.props.init && isFunction(this.props.init.init_instance_callback)) {
this.props.init.init_instance_callback(editor);
}
}
};
if (!this.inline) {
target.style.visibility = '';
}
if (isTextareaOrInput(target)) {
target.value = this.getInitialValue();
}
tinymce.init(finalInit);
};
} | the_stack |
import { define } from 'elements-sk/define';
import { html } from 'lit-html';
import { ParamSet, toParamSet, fromParamSet } from 'common-sk/modules/query';
import { SelectSk } from 'elements-sk/select-sk/select-sk';
import { ElementSk } from '../ElementSk';
import {
QueryValuesSk,
QueryValuesSkQueryValuesChangedEventDetail,
} from '../query-values-sk/query-values-sk';
import '../query-values-sk';
import 'elements-sk/select-sk';
import 'elements-sk/styles/buttons';
// The delay in ms before sending a delayed query-change event.
const DELAY_MS = 500;
export interface QuerySkQueryChangeEventDetail {
readonly q: string;
}
/**
* Removes the prefix, if any, from a query value.
*
* TODO(jcgregorio) - The fact that query values can have a prefix of either '!' or '~'
* is just something you have to know about them. We need a way to share the knowledge
* of all possible valid prefixes with the Go code.
*/
export const removePrefix = (s: string): string => {
if (s.length == 0) {
return s;
}
if ('~!'.includes(s[0])) {
return s.slice(1);
}
return s;
};
export class QuerySk extends ElementSk {
private static template = (ele: QuerySk) => html`
<div class="filtering">
<input
id="fast"
@input=${ele._fastFilter}
placeholder="Filter Parameters and Values"
/>
${QuerySk.clearFilterButton(ele)}
</div>
<div class="bottom">
<div class="selection">
<select-sk @selection-changed=${ele._keyChange}>
${QuerySk.keysTemplate(ele)}
</select-sk>
<button @click=${ele._clear} class="clear_selections">
Clear Selections
</button>
</div>
<query-values-sk
id="values"
class=${ele._keySelect?.selection === -1 ? 'hidden' : ''}
@query-values-changed=${ele._valuesChanged}
?hide_invert=${ele.hide_invert}
?hide_regex=${ele.hide_regex}
></query-values-sk>
</div>
`;
private static clearFilterButton(ele: QuerySk) {
if (!ele._filtering) {
return html``;
}
return html`
<button
@click=${ele._clearFilter}
class="clear_filters"
title="Clear filter"
>
✗
</button>
`;
}
private static keysTemplate = (ele: QuerySk) => ele._keys.map(
(k) => html`
<div>${k}</div>
`,
);
private _paramset: ParamSet = {};
private _originalParamset: ParamSet = {};
// True if there is text in the fitler input.
private _filtering: boolean = false;
// We keep the current_query as an object.
private _query: ParamSet = {};
private _key_order: string[] = [];
// The full set of keys in the desired order.
private _keys: string[] = [];
// The id of a pending timeout func that will send a delayed query-change event.
private _delayedTimeout: number | null = null;
private _keySelect: SelectSk | null = null;
private _values: QueryValuesSk | null = null;
private _fast: HTMLInputElement | null = null;
constructor() {
super(QuerySk.template);
}
connectedCallback() {
super.connectedCallback();
this._upgradeProperty('paramset');
this._upgradeProperty('key_order');
this._upgradeProperty('current_query');
this._upgradeProperty('hide_invert');
this._upgradeProperty('hide_regex');
this._render();
this._values = this.querySelector('#values');
this._keySelect = this.querySelector('select-sk');
this._fast = this.querySelector('#fast');
}
private _valuesChanged(
e: CustomEvent<QueryValuesSkQueryValuesChangedEventDetail>,
) {
const key = this._keys[this._keySelect!.selection as number];
if (this._fast!.value.trim() !== '') {
// Things get complicated if the user has entered a filter. The user may
// have selections in this._query[key] which don't appear in e.detail
// because they have been filtered out, so we should only add/remove
// values from this._query[key] that appear in this._paramset[key], while
// being careful because value(s) may be prefixed with either a '!' or a
// '~' if they are invert or regex queries.
// When we toggle from a regex to a non-regex we need to clear the values.
if (
!e.detail.regex
&& this._query[key]
&& this._query[key][0][0] === '~'
) {
this._query[key] = [];
}
if (e.detail.regex) {
this._query[key] = e.detail.values;
}
// The user might have toggled the invert checkbox, which means we need to
// make sure that the current values for the current key are also inverted
// appropriately even if not displayed due to the filter.
this._applyInvert(key, e.detail.invert);
// Make everything into Sets to make our lives easier.
const valuesDisplayed = new Set(this._paramset[key]);
const currentQueryForKey = new Set(this._query[key]);
const unprefixedSelectionsFromEvent = new Set(
e.detail.values.map(removePrefix),
);
// Loop over valuesDisplayed, if the value appears in selectionsFromEvent
// then add it to currentQueryForKey, otherwise remove it from
// currentQueryForKey.
valuesDisplayed.forEach((value) => {
const prefix = e.detail.invert ? '!' : '';
const prefixedValue = prefix + value;
if (unprefixedSelectionsFromEvent.has(value)) {
currentQueryForKey.add(prefixedValue);
} else {
currentQueryForKey.delete(prefixedValue);
}
});
this._query[key] = [...currentQueryForKey];
} else {
this._query[key] = e.detail.values;
}
this._queryChanged();
}
/**
* Set or clear the invery prefix ('!') on all the values for the given key in
* this._query, based on the value of 'invert'.
*/
private _applyInvert(key: string, invert: boolean) {
const values = this._query[key];
if (!values || !values.length) {
return;
}
const valuesHaveInvert = values[0][0] === '!';
if (invert === valuesHaveInvert) {
// eslint-disable-next-line no-useless-return
return;
} if (invert && !valuesHaveInvert) {
this._query[key] = values.map((v) => `!${v}`);
} else {
this._query[key] = values.map(removePrefix);
}
}
private _keyChange() {
if (this._keySelect!.selection === -1) {
return;
}
const key = this._keys[this._keySelect!.selection as number];
this._values!.options = this._paramset[key] || [];
this._values!.selected = this._query[key] || [];
this._render();
}
private _recalcKeys() {
const keys = Object.keys(this._paramset);
keys.sort();
// Pull out all the keys that appear in _key_order to be pushed to the front of the list.
const pre = this._key_order.filter((ordered) => keys.indexOf(ordered) > -1);
const post = keys.filter((key) => pre.indexOf(key) === -1);
this._keys = pre.concat(post);
}
private _queryChanged() {
const prev_query = this.current_query;
this._rationalizeQuery();
if (prev_query !== this.current_query) {
this.dispatchEvent(
new CustomEvent<QuerySkQueryChangeEventDetail>('query-change', {
detail: { q: this.current_query },
bubbles: true,
}),
);
window.clearTimeout(this._delayedTimeout!);
this._delayedTimeout = window.setTimeout(() => {
this.dispatchEvent(
new CustomEvent<QuerySkQueryChangeEventDetail>(
'query-change-delayed',
{
detail: { q: this.current_query },
bubbles: true,
},
),
);
}, DELAY_MS);
}
}
// Rationalize the _query, i.e. remove keys and values that don't exist in the ParamSet.
private _rationalizeQuery() {
// We will use this to determine whether we've made any changes to the original query.
const originalCurrentQuery = this.current_query;
const originalKeys = Object.keys(this._originalParamset);
Object.keys(this._query).forEach((key) => {
if (originalKeys.indexOf(key) === -1) {
// Filter out invalid keys.
delete this._query[key];
} else {
// Filter out invalid values.
this._query[key] = this._query[key].filter(
(val) => this._originalParamset[key].includes(val)
|| val.startsWith('~')
|| val.startsWith('!'),
);
}
});
// _rationalizeQuery is called when current_query is set. This avoids an infinite recursion.
const newCurrentQuery = fromParamSet(this._query);
if (newCurrentQuery !== originalCurrentQuery) {
this.current_query = fromParamSet(this._query);
}
}
private _clear() {
this._query = {};
this._recalcKeys();
this._queryChanged();
this._keyChange();
this._render();
}
private _fastFilter() {
const filterString = this._fast!.value.trim();
const filters = filterString.toLowerCase().split(/\s+/);
if (filterString) {
this._filtering = true;
}
// Create a closure that returns true if the given label matches the filter.
const matches = (s: string) => {
s = s.toLowerCase();
return filters.filter((f) => s.indexOf(f) > -1).length > 0;
};
// Loop over this._originalParamset.
const filtered: ParamSet = {};
Object.keys(this._originalParamset).forEach((paramkey) => {
// If the param key matches, then all the values go over.
if (matches(paramkey)) {
filtered[paramkey] = this._originalParamset[paramkey];
} else {
// Look for matches in the param values.
const valueMatches: string[] = [];
this._originalParamset[paramkey].forEach((paramvalue) => {
if (matches(paramvalue)) {
valueMatches.push(paramvalue);
}
});
if (valueMatches.length > 0) {
filtered[paramkey] = valueMatches;
}
}
});
this._paramset = filtered;
this._recalcKeys();
this._keyChange();
this._render();
}
private _clearFilter() {
this._fast!.value = '';
this.paramset = this._originalParamset;
this._filtering = false;
this._queryChanged();
this._render();
}
/** @prop paramset {Object} A serialized paramtools.ParamSet. */
get paramset() {
return this._paramset;
}
set paramset(val) {
// Record the current key so we can restore it later.
let prevSelectKey = '';
if (this._keySelect && this._keySelect.selection) {
prevSelectKey = this._keys[this._keySelect!.selection as number];
}
this._paramset = val;
this._originalParamset = val;
this._recalcKeys();
if (this._fast && this._fast.value.trim() !== '') {
this._fastFilter();
}
this._render();
// Now re-select the current key if it still exists post-filtering.
if (
this._keySelect
&& prevSelectKey
&& this._keys.indexOf(prevSelectKey) !== -1
) {
this._keySelect.selection = this._keys.indexOf(prevSelectKey);
this._keyChange();
}
}
/**
* The keys in the order they should appear. All keys not in the key order will be present after
* and in alphabetical order.
*/
get key_order() {
return this._key_order;
}
set key_order(val) {
this._key_order = val;
this._recalcKeys();
this._render();
}
/** Mirrors the hide_invert attribute. */
get hide_invert() {
return this.hasAttribute('hide_invert');
}
set hide_invert(val) {
if (val) {
this.setAttribute('hide_invert', '');
} else {
this.removeAttribute('hide_invert');
}
this._render();
}
/** Mirrors the hide_regex attribute. */
get hide_regex() {
return this.hasAttribute('hide_regex');
}
set hide_regex(val) {
if (val) {
this.setAttribute('hide_regex', '');
} else {
this.removeAttribute('hide_regex');
}
this._render();
}
/** Mirrors the current_query attribute. */
get current_query() {
return this.getAttribute('current_query') || '';
}
set current_query(val: string) {
this.setAttribute('current_query', val);
}
static get observedAttributes() {
return ['current_query', 'hide_invert', 'hide_regex'];
}
attributeChangedCallback(name: string, _: string, newValue: string) {
if (name === 'current_query') {
// Convert the current_query string into an object.
this._query = toParamSet(newValue);
// Remove invalid key/value pairs from the new query.
this._rationalizeQuery();
// This updates query-value-sk with the new selection and renders the template.
if (this._connected) {
this._keyChange();
}
} else {
this._render();
}
}
}
define('query-sk', QuerySk); | the_stack |
import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types';
import Utils from '@requestnetwork/utils';
import Erc20FeeProxyContract from '../../../../src/extensions/payment-network/erc20/fee-proxy-contract';
import * as DataERC20FeeAddData from '../../../utils/payment-network/erc20/fee-proxy-contract-add-data-generator';
import * as DataERC20FeeCreate from '../../../utils/payment-network/erc20/fee-proxy-contract-create-data-generator';
import * as TestData from '../../../utils/test-data-generator';
const erc20FeeProxyContract = new Erc20FeeProxyContract();
/* eslint-disable @typescript-eslint/no-unused-expressions */
describe('extensions/payment-network/erc20/fee-proxy-contract', () => {
describe('createCreationAction', () => {
it('can create a create action with all parameters', () => {
expect(
erc20FeeProxyContract.createCreationAction({
feeAddress: '0x0000000000000000000000000000000000000001',
feeAmount: '0',
paymentAddress: '0x0000000000000000000000000000000000000002',
refundAddress: '0x0000000000000000000000000000000000000003',
salt: 'ea3bc7caf64110ca',
}),
).toEqual({
action: 'create',
id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT,
parameters: {
feeAddress: '0x0000000000000000000000000000000000000001',
feeAmount: '0',
paymentAddress: '0x0000000000000000000000000000000000000002',
refundAddress: '0x0000000000000000000000000000000000000003',
salt: 'ea3bc7caf64110ca',
},
version: '0.2.0',
});
});
it('can create a create action without fee parameters', () => {
expect(
erc20FeeProxyContract.createCreationAction({
paymentAddress: '0x0000000000000000000000000000000000000001',
refundAddress: '0x0000000000000000000000000000000000000002',
salt: 'ea3bc7caf64110ca',
}),
).toEqual({
action: 'create',
id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT,
parameters: {
paymentAddress: '0x0000000000000000000000000000000000000001',
refundAddress: '0x0000000000000000000000000000000000000002',
salt: 'ea3bc7caf64110ca',
},
version: '0.2.0',
});
});
it('can create a create action with only salt', () => {
expect(
erc20FeeProxyContract.createCreationAction({
salt: 'ea3bc7caf64110ca',
}),
).toEqual({
action: 'create',
id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT,
parameters: {
salt: 'ea3bc7caf64110ca',
},
version: '0.2.0',
});
});
it('cannot createCreationAction with payment address not an ethereum address', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.createCreationAction({
paymentAddress: 'not an ethereum address',
refundAddress: '0x0000000000000000000000000000000000000002',
salt: 'ea3bc7caf64110ca',
});
}).toThrowError("paymentAddress 'not an ethereum address' is not a valid address");
});
it('cannot createCreationAction with refund address not an ethereum address', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.createCreationAction({
paymentAddress: '0x0000000000000000000000000000000000000001',
refundAddress: 'not an ethereum address',
salt: 'ea3bc7caf64110ca',
});
}).toThrowError("refundAddress 'not an ethereum address' is not a valid address");
});
it('cannot createCreationAction with fee address not an ethereum address', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.createCreationAction({
feeAddress: 'not an ethereum address',
paymentAddress: '0x0000000000000000000000000000000000000001',
salt: 'ea3bc7caf64110ca',
});
}).toThrowError('feeAddress is not a valid address');
});
it('cannot createCreationAction with invalid fee amount', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.createCreationAction({
feeAmount: '-20000',
paymentAddress: '0x0000000000000000000000000000000000000001',
salt: 'ea3bc7caf64110ca',
});
}).toThrowError('feeAmount is not a valid amount');
});
});
describe('createAddPaymentAddressAction', () => {
it('can createAddPaymentAddressAction', () => {
expect(
erc20FeeProxyContract.createAddPaymentAddressAction({
paymentAddress: '0x0000000000000000000000000000000000000001',
}),
).toEqual({
action: ExtensionTypes.PnReferenceBased.ACTION.ADD_PAYMENT_ADDRESS,
id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT,
parameters: {
paymentAddress: '0x0000000000000000000000000000000000000001',
},
});
});
it('cannot createAddPaymentAddressAction with payment address not an ethereum address', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.createAddPaymentAddressAction({
paymentAddress: 'not an ethereum address',
});
}).toThrowError("paymentAddress 'not an ethereum address' is not a valid address");
});
});
describe('createAddRefundAddressAction', () => {
it('can createAddRefundAddressAction', () => {
expect(
erc20FeeProxyContract.createAddRefundAddressAction({
refundAddress: '0x0000000000000000000000000000000000000002',
}),
).toEqual({
action: ExtensionTypes.PnReferenceBased.ACTION.ADD_REFUND_ADDRESS,
id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT,
parameters: {
refundAddress: '0x0000000000000000000000000000000000000002',
},
});
});
it('cannot createAddRefundAddressAction with payment address not an ethereum address', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.createAddRefundAddressAction({
refundAddress: 'not an ethereum address',
});
}).toThrowError("refundAddress 'not an ethereum address' is not a valid address");
});
});
describe('createAddFeeAction', () => {
it('can createAddFeeAction', () => {
expect(
erc20FeeProxyContract.createAddFeeAction({
feeAddress: '0x0000000000000000000000000000000000000002',
feeAmount: '2000',
}),
).toEqual({
action: ExtensionTypes.PnFeeReferenceBased.ACTION.ADD_FEE,
id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT,
parameters: {
feeAddress: '0x0000000000000000000000000000000000000002',
feeAmount: '2000',
},
});
});
it('cannot createAddFeeAddressAction with payment address not an ethereum address', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.createAddFeeAction({
feeAddress: 'not an ethereum address',
feeAmount: '2000',
});
}).toThrowError('feeAddress is not a valid address');
});
it('cannot createAddFeeAction with amount non positive integer', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.createAddFeeAction({
feeAddress: '0x0000000000000000000000000000000000000002',
feeAmount: '-30000',
});
}).toThrowError('feeAmount is not a valid amount');
});
});
describe('applyActionToExtension', () => {
describe('applyActionToExtension/unknown action', () => {
it('cannot applyActionToExtensions of unknown action', () => {
const unknownAction = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress);
unknownAction.action = 'unknown action' as any;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
unknownAction,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError('Unknown action: unknown action');
});
it('cannot applyActionToExtensions of unknown id', () => {
const unknownAction = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress);
unknownAction.id = 'unknown id' as any;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
unknownAction,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError('The extension should be created before receiving any other action');
});
});
describe('applyActionToExtension/create', () => {
it('can applyActionToExtensions of creation', () => {
// 'new extension state wrong'
expect(
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateNoExtensions.extensions,
DataERC20FeeCreate.actionCreationFull,
DataERC20FeeCreate.requestStateNoExtensions,
TestData.otherIdRaw.identity,
TestData.arbitraryTimestamp,
),
).toEqual(DataERC20FeeCreate.extensionFullState);
});
it('cannot applyActionToExtensions of creation with a previous state', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestFullStateCreated.extensions,
DataERC20FeeCreate.actionCreationFull,
DataERC20FeeCreate.requestFullStateCreated,
TestData.otherIdRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError('This extension has already been created');
});
it('cannot applyActionToExtensions of creation on a non ERC20 request', () => {
const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy(
TestData.requestCreatedNoExtension,
);
requestCreatedNoExtension.currency = {
type: RequestLogicTypes.CURRENCY.BTC,
value: 'BTC',
};
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
TestData.requestCreatedNoExtension.extensions,
DataERC20FeeCreate.actionCreationFull,
requestCreatedNoExtension,
TestData.otherIdRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError('This extension can be used only on ERC20 requests');
});
it('cannot applyActionToExtensions of creation with payment address not valid', () => {
const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeCreate.actionCreationFull);
testnetPaymentAddress.parameters.paymentAddress = DataERC20FeeAddData.invalidAddress;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateNoExtensions.extensions,
testnetPaymentAddress,
DataERC20FeeCreate.requestStateNoExtensions,
TestData.otherIdRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(
`paymentAddress '${DataERC20FeeAddData.invalidAddress}' is not a valid address`,
);
});
it('cannot applyActionToExtensions of creation with refund address not valid', () => {
const testnetRefundAddress = Utils.deepCopy(DataERC20FeeCreate.actionCreationFull);
testnetRefundAddress.parameters.refundAddress = DataERC20FeeAddData.invalidAddress;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateNoExtensions.extensions,
testnetRefundAddress,
DataERC20FeeCreate.requestStateNoExtensions,
TestData.otherIdRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(
`refundAddress '${DataERC20FeeAddData.invalidAddress}' is not a valid address`,
);
});
it('keeps the version used at creation', () => {
const newState = erc20FeeProxyContract.applyActionToExtension(
{},
{ ...DataERC20FeeCreate.actionCreationFull, version: 'ABCD' },
DataERC20FeeCreate.requestStateNoExtensions,
TestData.otherIdRaw.identity,
TestData.arbitraryTimestamp,
);
expect(newState[erc20FeeProxyContract.extensionId].version).toBe('ABCD');
});
it('requires a version at creation', () => {
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
{},
{ ...DataERC20FeeCreate.actionCreationFull, version: '' },
DataERC20FeeCreate.requestStateNoExtensions,
TestData.otherIdRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError('version is required at creation');
});
});
describe('applyActionToExtension/addPaymentAddress', () => {
it('can applyActionToExtensions of addPaymentAddress', () => {
// 'new extension state wrong'
expect(
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
DataERC20FeeAddData.actionAddPaymentAddress,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
),
).toEqual(DataERC20FeeAddData.extensionStateWithPaymentAfterCreation);
});
it('cannot applyActionToExtensions of addPaymentAddress without a previous state', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateNoExtensions.extensions,
DataERC20FeeAddData.actionAddPaymentAddress,
DataERC20FeeCreate.requestStateNoExtensions,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The extension should be created before receiving any other action`);
});
it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => {
const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty);
previousState.payee = undefined;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
previousState.extensions,
DataERC20FeeAddData.actionAddPaymentAddress,
previousState,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The request must have a payee`);
});
it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => {
const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty);
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
previousState.extensions,
DataERC20FeeAddData.actionAddPaymentAddress,
previousState,
TestData.payerRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The signer must be the payee`);
});
it('cannot applyActionToExtensions of addPaymentAddress with payment address already given', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestFullStateCreated.extensions,
DataERC20FeeAddData.actionAddPaymentAddress,
DataERC20FeeCreate.requestFullStateCreated,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`Payment address already given`);
});
it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => {
const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress);
testnetPaymentAddress.parameters.paymentAddress = DataERC20FeeAddData.invalidAddress;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
testnetPaymentAddress,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(
`paymentAddress '${DataERC20FeeAddData.invalidAddress}' is not a valid address`,
);
});
});
describe('applyActionToExtension/addRefundAddress', () => {
it('can applyActionToExtensions of addRefundAddress', () => {
// 'new extension state wrong'
expect(
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
DataERC20FeeAddData.actionAddRefundAddress,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payerRaw.identity,
TestData.arbitraryTimestamp,
),
).toEqual(DataERC20FeeAddData.extensionStateWithRefundAfterCreation);
});
it('cannot applyActionToExtensions of addRefundAddress without a previous state', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateNoExtensions.extensions,
DataERC20FeeAddData.actionAddRefundAddress,
DataERC20FeeCreate.requestStateNoExtensions,
TestData.payerRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The extension should be created before receiving any other action`);
});
it('cannot applyActionToExtensions of addRefundAddress without a payer', () => {
const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty);
previousState.payer = undefined;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
previousState.extensions,
DataERC20FeeAddData.actionAddRefundAddress,
previousState,
TestData.payerRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The request must have a payer`);
});
it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => {
const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty);
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
previousState.extensions,
DataERC20FeeAddData.actionAddRefundAddress,
previousState,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The signer must be the payer`);
});
it('cannot applyActionToExtensions of addRefundAddress with payment address already given', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestFullStateCreated.extensions,
DataERC20FeeAddData.actionAddRefundAddress,
DataERC20FeeCreate.requestFullStateCreated,
TestData.payerRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`Refund address already given`);
});
it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => {
const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddRefundAddress);
testnetPaymentAddress.parameters.refundAddress = DataERC20FeeAddData.invalidAddress;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
testnetPaymentAddress,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError('refundAddress is not a valid address');
});
});
describe('applyActionToExtension/addFee', () => {
it('can applyActionToExtensions of addFee', () => {
// 'new extension state wrong'
expect(
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
DataERC20FeeAddData.actionAddFee,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
),
).toEqual(DataERC20FeeAddData.extensionStateWithFeeAfterCreation);
});
it('cannot applyActionToExtensions of addFee without a previous state', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateNoExtensions.extensions,
DataERC20FeeAddData.actionAddFee,
DataERC20FeeCreate.requestStateNoExtensions,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The extension should be created before receiving any other action`);
});
it('cannot applyActionToExtensions of addFee without a payee', () => {
const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty);
previousState.payee = undefined;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
previousState.extensions,
DataERC20FeeAddData.actionAddFee,
previousState,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The request must have a payee`);
});
it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => {
const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty);
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
previousState.extensions,
DataERC20FeeAddData.actionAddFee,
previousState,
TestData.payerRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`The signer must be the payee`);
});
it('cannot applyActionToExtensions of addFee with fee data already given', () => {
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestFullStateCreated.extensions,
DataERC20FeeAddData.actionAddFee,
DataERC20FeeCreate.requestFullStateCreated,
TestData.payeeRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError(`Fee address already given`);
});
it('cannot applyActionToExtensions of addFee with fee address not valid', () => {
const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddFee);
testnetPaymentAddress.parameters.feeAddress = DataERC20FeeAddData.invalidAddress;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
testnetPaymentAddress,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payerRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError('feeAddress is not a valid address');
});
it('cannot applyActionToExtensions of addFee with fee amount not valid', () => {
const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddFee);
testnetPaymentAddress.parameters.feeAmount = DataERC20FeeAddData.invalidAddress;
// 'must throw'
expect(() => {
erc20FeeProxyContract.applyActionToExtension(
DataERC20FeeCreate.requestStateCreatedEmpty.extensions,
testnetPaymentAddress,
DataERC20FeeCreate.requestStateCreatedEmpty,
TestData.payerRaw.identity,
TestData.arbitraryTimestamp,
);
}).toThrowError('feeAmount is not a valid amount');
});
});
});
}); | the_stack |
import { mat4, vec3, vec4 } from 'gl-matrix';
import {
AccumulatePass,
AntiAliasingKernel,
BlitPass,
Camera,
Canvas,
Context,
CuboidGeometry,
DefaultFramebuffer,
EventProvider,
Framebuffer,
Invalidate,
Navigation,
Program,
Renderbuffer,
Renderer,
Shader,
Texture2D,
Wizard,
} from 'webgl-operate';
import { Example } from './example';
/* spellchecker: enable */
// tslint:disable:max-classes-per-file
export class ProgressiveCubeRenderer extends Renderer {
protected _camera: Camera;
protected _navigation: Navigation;
protected _depthRenderbuffer: Renderbuffer;
protected _colorRenderTexture: Texture2D;
protected _intermediateFBO: Framebuffer;
protected _ndcOffsetKernel: AntiAliasingKernel;
protected _uNdcOffset: WebGLUniformLocation;
protected _cuboid: CuboidGeometry;
protected _texture: Texture2D;
protected _program: Program;
protected _uViewProjection: WebGLUniformLocation;
protected _defaultFBO: DefaultFramebuffer;
protected _accumulate: AccumulatePass;
protected _blit: BlitPass;
protected _zoomSrcBounds: vec4;
protected _zoomDstBounds: vec4;
/**
* Initializes and sets up buffer, cube geometry, camera and links shaders with program.
* @param context - valid context to create the object for.
* @param identifier - meaningful name for identification of this instance.
* @param eventProvider - required for mouse interaction
* @returns - whether initialization was successful
*/
protected onInitialize(context: Context, callback: Invalidate,
eventProvider: EventProvider): boolean {
const gl = context.gl;
const gl2facade = this._context.gl2facade;
this._defaultFBO = new DefaultFramebuffer(context, 'DefaultFBO');
this._defaultFBO.initialize();
const internalFormatAndType = Wizard.queryInternalTextureFormat(this._context, gl.RGBA, Wizard.Precision.half);
this._colorRenderTexture = new Texture2D(this._context, 'ColorRenderTexture');
this._colorRenderTexture.initialize(1, 1, internalFormatAndType[0], gl.RGBA, internalFormatAndType[1]);
this._colorRenderTexture.filter(gl.LINEAR, gl.LINEAR);
this._depthRenderbuffer = new Renderbuffer(this._context, 'DepthRenderbuffer');
this._depthRenderbuffer.initialize(1, 1, gl.DEPTH_COMPONENT16);
this._intermediateFBO = new Framebuffer(this._context, 'IntermediateFBO');
this._intermediateFBO.initialize([
[gl2facade.COLOR_ATTACHMENT0, this._colorRenderTexture],
[gl.DEPTH_ATTACHMENT, this._depthRenderbuffer]]);
this._cuboid = new CuboidGeometry(context, 'Cuboid', true, [2.0, 2.0, 2.0]);
this._cuboid.initialize();
const vert = new Shader(context, gl.VERTEX_SHADER, 'mesh-progressive.vert');
vert.initialize(require('./data/mesh-progressive.vert'));
const frag = new Shader(context, gl.FRAGMENT_SHADER, 'mesh.frag');
frag.initialize(require('./data/mesh.frag'));
this._program = new Program(context, 'CubeProgram');
this._program.initialize([vert, frag], false);
this._program.attribute('a_vertex', this._cuboid.vertexLocation);
this._program.attribute('a_texCoord', this._cuboid.uvCoordLocation);
this._program.link();
this._program.bind();
this._uViewProjection = this._program.uniform('u_viewProjection');
this._uNdcOffset = this._program.uniform('u_ndcOffset');
const identity = mat4.identity(mat4.create());
gl.uniformMatrix4fv(this._program.uniform('u_model'), false, identity);
gl.uniform1i(this._program.uniform('u_texture'), 0);
gl.uniform1i(this._program.uniform('u_textured'), false);
this._texture = new Texture2D(context, 'Texture');
this._texture.initialize(1, 1, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE);
this._texture.wrap(gl.REPEAT, gl.REPEAT);
this._texture.filter(gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR);
this._texture.maxAnisotropy(Texture2D.MAX_ANISOTROPY);
this._texture.fetch('/examples/data/blue-painted-planks-diff-1k-modified.webp').then(() => {
const gl = context.gl;
this._program.bind();
gl.uniform1i(this._program.uniform('u_textured'), true);
this.finishLoading();
this.invalidate(true);
});
this._camera = new Camera();
this._camera.center = vec3.fromValues(0.0, 0.0, 0.0);
this._camera.up = vec3.fromValues(0.0, 1.0, 0.0);
this._camera.eye = vec3.fromValues(0.0, 0.0, 5.0);
this._camera.near = 1.0;
this._camera.far = 8.0;
this._navigation = new Navigation(callback, eventProvider);
this._navigation.camera = this._camera;
this._accumulate = new AccumulatePass(context);
this._accumulate.initialize();
this._accumulate.precision = this._framePrecision;
this._accumulate.texture = this._colorRenderTexture;
this._blit = new BlitPass(this._context);
this._blit.initialize();
this._blit.readBuffer = gl2facade.COLOR_ATTACHMENT0;
this._blit.target = this._defaultFBO;
this._blit.drawBuffer = gl.BACK;
return true;
}
/**
* Uninitializes buffers, geometry and program.
*/
protected onUninitialize(): void {
super.uninitialize();
this._cuboid.uninitialize();
this._program.uninitialize();
this._defaultFBO.uninitialize();
}
protected onDiscarded(): void {
this._altered.alter('canvasSize');
this._altered.alter('clearColor');
this._altered.alter('frameSize');
this._altered.alter('multiFrameNumber');
}
/**
* This is invoked in order to check if rendering of a frame is required by means of implementation specific
* evaluation (e.g., lazy non continuous rendering). Regardless of the return value a new frame (preparation,
* frame, swap) might be invoked anyway, e.g., when update is forced or canvas or context properties have
* changed or the renderer was invalidated @see{@link invalidate}.
* @returns whether to redraw
*/
protected onUpdate(): boolean {
this._navigation.update();
return this._altered.any || this._camera.altered;
}
/**
* This is invoked in order to prepare rendering of one or more frames, regarding multi-frame rendering and
* camera-updates.
*/
protected onPrepare(): void {
if (this._altered.frameSize) {
this._intermediateFBO.resize(this._frameSize[0], this._frameSize[1]);
this._camera.viewport = this._canvasSize;
const aspect = this._frameSize[0] / this._frameSize[1];
this._zoomSrcBounds = vec4.fromValues(
this._frameSize[0] * (0.3333 - 0.02), this._frameSize[1] * (0.6666 - 0.02 * aspect),
this._frameSize[0] * (0.3333 + 0.02), this._frameSize[1] * (0.6666 + 0.02 * aspect));
}
if (this._altered.canvasSize) {
this._camera.aspect = this._canvasSize[0] / this._canvasSize[1];
this._zoomDstBounds = vec4.fromValues(
this._canvasSize[0] * (1.0 - 0.374), this._canvasSize[1] * (1.0 - 0.374 * this._camera.aspect),
this._canvasSize[0] * (1.0 - 0.008), this._canvasSize[1] * (1.0 - 0.008 * this._camera.aspect));
}
if (this._altered.clearColor) {
this._defaultFBO.clearColor(this._clearColor);
this._intermediateFBO.clearColor(this._clearColor);
}
if (this._altered.multiFrameNumber) {
this._ndcOffsetKernel = new AntiAliasingKernel(this._multiFrameNumber);
}
this._accumulate.update();
this._altered.reset();
this._camera.altered = false;
}
protected onFrame(frameNumber: number): void {
const gl = this._context.gl;
this._intermediateFBO.bind();
this._intermediateFBO.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, false, false);
gl.viewport(0, 0, this._frameSize[0], this._frameSize[1]);
const ndcOffset = this._ndcOffsetKernel.get(frameNumber);
ndcOffset[0] = 2.0 * ndcOffset[0] / this._frameSize[0];
ndcOffset[1] = 2.0 * ndcOffset[1] / this._frameSize[1];
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.BACK);
gl.enable(gl.DEPTH_TEST);
this._texture.bind(gl.TEXTURE0);
this._program.bind();
gl.uniformMatrix4fv(this._uViewProjection, false, this._camera.viewProjection);
gl.uniform2fv(this._uNdcOffset, ndcOffset);
this._cuboid.bind();
this._cuboid.draw();
this._cuboid.unbind();
this._program.unbind();
this._texture.unbind(gl.TEXTURE0);
gl.cullFace(gl.BACK);
gl.disable(gl.CULL_FACE);
this._accumulate.frame(frameNumber);
}
protected onSwap(): void {
this._blit.framebuffer = this._accumulate.framebuffer ?
this._accumulate.framebuffer : this._intermediateFBO;
this._blit.frame();
this._blit.srcBounds = this._zoomSrcBounds;
this._blit.dstBounds = this._zoomDstBounds;
this._blit.frame();
this._blit.srcBounds = this._blit.dstBounds = undefined;
}
}
export class ProgressiveCubeExample extends Example {
private _canvas: Canvas;
private _renderer: ProgressiveCubeRenderer;
onInitialize(element: HTMLCanvasElement | string): boolean {
this._canvas = new Canvas(element, { antialias: false });
this._canvas.controller.multiFrameNumber = 64;
this._canvas.framePrecision = Wizard.Precision.half;
this._canvas.frameScale = [0.5, 0.5];
this._renderer = new ProgressiveCubeRenderer();
this._canvas.renderer = this._renderer;
return true;
}
onUninitialize(): void {
this._canvas.dispose();
(this._renderer as Renderer).uninitialize();
}
get canvas(): Canvas {
return this._canvas;
}
get renderer(): ProgressiveCubeRenderer {
return this._renderer;
}
} | the_stack |
var globTest:any = {};
module WinJSTests {
"use strict";
function testDefaultSurfaceChaining(flipView) {
var element = flipView.element,
surface = element.querySelector(".win-surface");
// Verify if win-surface class was applied
LiveUnit.Assert.isNotNull(surface, "win-surface class was not set");
// Verify the value of scrollChaining when touch is supported
if (flipView._environmentSupportsTouch) {
var style = document.defaultView.getComputedStyle(surface, null)[WinJS.Utilities._browserStyleEquivalents["scroll-chaining"].scriptName];
LiveUnit.Assert.areEqual(style, "none", "Default value is not set to none");
}
}
export class FlipperInstantiationTests {
testNavigationWithSizeInPercent = function (complete) {
var elem = document.createElement("div");
elem.id = "flipper";
elem.style.width = "50%";
elem.style.height = "50%";
document.body.appendChild(elem);
function template(itemPromise) {
return itemPromise.then(function (item) {
var root = document.createElement("div");
root.innerHTML = "Microsoft " + item.data;
return root;
});
}
var ds = new WinJS.Binding.List([1, 2, 3, 4, 5, 6, 7]);
var flipView = new WinJS.UI.FlipView(elem, {
itemTemplate: template,
itemDataSource: ds.dataSource
});
waitForFlipViewReady(flipView).
then(function () {
var promiseChain = WinJS.Promise.timeout();
var i = 0;
Helper.asyncWhile(
function () { return i < 6; },
function () {
promiseChain = promiseChain.then(function () {
return waitForFlipViewReady(flipView, function () {
flipView.next();
});
});
i++;
}
);
return promiseChain;
}).
done(function () {
// Cleanup
WinJS.Utilities.disposeSubTree(elem);
document.body.removeChild(elem);
complete();
});
};
testSimpleTemplate = function (complete) {
var host = document.createElement("div");
host.style.width = "400px";
host.style.height = "400px";
document.body.appendChild(host);
function template(itemPromise) {
var root = document.createElement("div");
root.innerHTML = "Microsoft";
return root;
}
var ds = new WinJS.Binding.List([1, 2, 3, 4, 5, 6, 7]);
var flipView = new WinJS.UI.FlipView(host, {
itemTemplate: template,
itemDataSource: ds.dataSource
});
flipView.addEventListener("pagecompleted", function (ev) {
WinJS.Utilities.disposeSubTree(host);
document.body.removeChild(host);
complete();
});
};
testNoNavigationOnResize = function (complete) {
var flipperElement = document.createElement('div'),
startPage = 0,
flipper;
document.body.appendChild(flipperElement);
var onComplete = function (ev) {
flipperElement.removeEventListener("pagecompleted", onComplete);
// Attach another handler
var afterComplete = function (ev) {
LiveUnit.Assert.fail("Pagecompleted shouldn't have fired after resize");
};
flipperElement.addEventListener("pagecompleted", afterComplete);
// Resize flipview
flipperElement.style.width = "600px";
// Wait and then complete the test
WinJS.Promise.timeout(WinJS.UI._animationTimeAdjustment(500)).then(function () {
// Check the currentPage is same as before
LiveUnit.Assert.areEqual(startPage, flipper.currentPage, "Current Page should not have changed");
// Done
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
complete();
});
};
flipperElement.addEventListener("pagecompleted", onComplete);
flipper = new WinJS.UI.FlipView(flipperElement, {
itemDataSource: Helper.createBindingList(10).dataSource,
itemTemplate: Helper.syncJSTemplate
});
};
testNoNavigationOnFocus = function (complete) {
var flipperElement = document.createElement('div'),
startPage = 0,
flipper;
document.body.appendChild(flipperElement);
var onComplete = function (ev) {
flipperElement.removeEventListener("pagecompleted", onComplete);
// Attach another handler
var afterComplete = function (ev) {
LiveUnit.Assert.fail("Pagecompleted shouldn't have fired after resize");
};
flipperElement.addEventListener("pagecompleted", afterComplete);
// Set the focus on the flipview
flipperElement.focus();
// Wait and then complete the test
WinJS.Promise.timeout(WinJS.UI._animationTimeAdjustment(500)).then(function () {
// Check the currentPage is same as before
LiveUnit.Assert.areEqual(startPage, flipper.currentPage, "Current Page should not have changed");
// Done
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
complete();
});
};
flipperElement.addEventListener("pagecompleted", onComplete);
flipper = new WinJS.UI.FlipView(flipperElement, {
itemDataSource: Helper.createBindingList(10).dataSource,
itemTemplate: Helper.syncJSTemplate
});
};
testDeleteItemAndOrientationChange = function (complete) {
var flipperElement = document.createElement('div'),
flipper;
document.body.appendChild(flipperElement);
var onComplete = function (ev) {
flipperElement.removeEventListener("pagecompleted", onComplete);
// Attach another handler
var afterComplete = function (ev) {
// Item has been deleted and orientation changed
// Verify the item is displayed on screen
var expectedText = "title1",
currentText = flipper._pageManager._currentPage.element.textContent.trim();
LiveUnit.Assert.areEqual(expectedText, currentText, "FlipView is not displaying the expected page");
// Done
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
complete();
};
flipperElement.addEventListener("datasourcecountchanged", afterComplete);
// Delete item
flipper.itemDataSource.itemFromIndex(0).then(function (item) {
flipper.itemDataSource.remove(item.key);
// Change orientation without waiting for pagecompleted
flipper.orientation = "vertical";
});
};
flipperElement.addEventListener("pagecompleted", onComplete);
flipper = new WinJS.UI.FlipView(flipperElement, {
itemDataSource: Helper.createBindingList(10).dataSource,
itemTemplate: Helper.syncJSTemplate
});
};
testFlipperInstantiation = function (signalTestCaseCompleted) {
var flipperElement = document.createElement('div');
document.body.appendChild(flipperElement);
LiveUnit.LoggingCore.logComment("Attempt to Instantiate the flipper element");
var flipper = new WinJS.UI.FlipView(flipperElement);
LiveUnit.LoggingCore.logComment("Flipper has been instantiated.");
LiveUnit.Assert.isNotNull(flipper, "Flipper element should not be null when instantiated.");
testDefaultSurfaceChaining(flipper);
function verifyFunction(functionName) {
LiveUnit.LoggingCore.logComment("Verifying that function " + functionName + " exists");
if (flipper[functionName] === undefined) {
LiveUnit.Assert.fail(functionName + " missing from flipper");
}
LiveUnit.Assert.isNotNull(flipper[functionName]);
LiveUnit.Assert.isTrue(typeof (flipper[functionName]) === "function", functionName + " exists on flipper, but it isn't a function");
}
verifyFunction("next");
verifyFunction("previous");
verifyFunction("count");
verifyFunction("forceLayout");
verifyFunction("setCustomAnimations");
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
signalTestCaseCompleted();
}
// Test Flipper Instantiation with null element
testFlipperNullInstantiation = function (signalTestCaseCompleted) {
LiveUnit.LoggingCore.logComment("Attempt to Instantiate the flipper with null element");
var flipper = new WinJS.UI.FlipView(null);
LiveUnit.Assert.isNotNull(flipper.element, "should have created an element");
document.body.appendChild(flipper.element);
testDefaultSurfaceChaining(flipper);
WinJS.Utilities.disposeSubTree(flipper.element);
document.body.removeChild(flipper.element);
signalTestCaseCompleted();
}
testEmptyFlipperFunctions = function (signalTestCaseCompleted) {
var flipperElement = document.createElement("div");
document.body.appendChild(flipperElement);
LiveUnit.LoggingCore.logComment("Attempt to Instantiate the flipper element");
var flipper = new WinJS.UI.FlipView(flipperElement);
LiveUnit.LoggingCore.logComment("Flipper has been instantiated.");
LiveUnit.Assert.isNotNull(flipper, "Flipper element should not be null when instantiated.");
testDefaultSurfaceChaining(flipper);
LiveUnit.Assert.areEqual(flipper.currentPage, 0, "Verifying that currentPage is 0");
LiveUnit.Assert.isFalse(flipper.next(), "Verifying that we can't flip to next");
LiveUnit.Assert.areEqual(flipper.currentPage, 0, "Verifying that currentPage is 0");
LiveUnit.Assert.isFalse(flipper.previous(), "Verifying that we can't flip to previous");
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
signalTestCaseCompleted();
}
testFlipperParams = function (signalTestCaseCompleted) {
function testGoodInitOption(paramName, value) {
LiveUnit.LoggingCore.logComment("Testing creating a flipper using good parameter " + paramName + "=" + value);
var div = document.createElement("div");
var options = {};
options[paramName] = value;
document.body.appendChild(div);
var flipper = new WinJS.UI.FlipView(div, options);
LiveUnit.Assert.isNotNull(flipper);
testDefaultSurfaceChaining(flipper);
WinJS.Utilities.disposeSubTree(div);
document.body.removeChild(div);
}
testGoodInitOption("orientation", "horizontal");
testGoodInitOption("orientation", "vertical");
testGoodInitOption("orientation", "HoRiZONTal");
testGoodInitOption("orientation", "verTical");
testGoodInitOption("currentPage", 0);
signalTestCaseCompleted();
}
testFlipperElement = function (signalTestCaseCompleted) {
var flipperElement = document.createElement('div');
flipperElement.id = "myFlipViewDiv";
document.body.appendChild(flipperElement);
LiveUnit.LoggingCore.logComment("Attempt to Instantiate the flipper element");
var flipper = new WinJS.UI.FlipView(flipperElement);
LiveUnit.LoggingCore.logComment("Verify that the element property is correct");
LiveUnit.Assert.areEqual(flipperElement, flipper.element);
testDefaultSurfaceChaining(flipper);
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
signalTestCaseCompleted();
}
testFlipperEventsInConstructorOptions = function (signalTestCaseCompleted) {
var flipperElement = document.createElement('div');
flipperElement.id = "myFlipViewDiv";
document.body.appendChild(flipperElement);
var pageVisiblityChangedCalled = false;
var pageSelectedCalled = false;
var testData = createArraySource(1, ["400px"], ["400px"]),
rawData = testData.rawData,
options = {
itemDataSource: testData.dataSource,
itemTemplate: basicInstantRenderer,
onpagevisibilitychanged: function () {
pageVisiblityChangedCalled = true;
},
onpageselected: function () {
pageSelectedCalled = true;
},
onpagecompleted: function () {
LiveUnit.Assert.isTrue(pageVisiblityChangedCalled);
LiveUnit.Assert.isTrue(pageSelectedCalled);
document.body.removeChild(flipperElement);
signalTestCaseCompleted();
}
};
var flipView = new WinJS.UI.FlipView(flipperElement, options);
};
testFlipViewDispose = function (complete) {
var flipperElement = document.createElement('div');
flipperElement.id = "myFlipViewDiv";
document.body.appendChild(flipperElement);
var dispose = function () {
if (this.disposed) {
LiveUnit.Assert.fail("Disposed was called again.");
}
this.disposed = true;
itemsAlive--;
};
var data = [1, 2, 3, 4, 5, 6, 7];
var list = new WinJS.Binding.List(data);
var itemsAlive = 0;
var fv = new WinJS.UI.FlipView(flipperElement);
fv.itemTemplate = function (itemPromise) {
return itemPromise.then(function (item) {
var div = document.createElement("div");
div.textContent = item.data;
WinJS.Utilities.addClass(div, "win-disposable");
div.dispose = dispose.bind(div);
itemsAlive++;
return div;
});
};
fv.addEventListener("pagecompleted", function () {
LiveUnit.Assert.isTrue(itemsAlive > 0);
fv.dispose();
LiveUnit.Assert.areEqual(itemsAlive, 0, "At least one element wasn't cleaned up.");
document.body.removeChild(flipperElement);
complete();
});
fv.itemDataSource = list.dataSource;
};
testFlipViewDisposeDuringVirtualization = function (complete) {
var dispose = function () {
if (this.disposed) {
LiveUnit.Assert.fail("Disposed was called again.");
}
this.disposed = true;
itemsAlive--;
if (!disposing && this.textContent != "1") {
LiveUnit.Assert.fail("An unexpected item was released.");
}
firstItemDisposed = true;
};
var data = [1, 2, 3, 4, 5, 6, 7];
var list = new WinJS.Binding.List(data);
var itemsAlive = 0;
var fv = new WinJS.UI.FlipView();
fv.element.id = "fv";
document.body.appendChild(fv.element);
fv.itemTemplate = function (itemPromise) {
return itemPromise.then(function (item) {
var div = document.createElement("div");
div.textContent = item.data;
WinJS.Utilities.addClass(div, "win-disposable");
div.dispose = dispose.bind(div);
itemsAlive++;
return div;
});
};
var firstItemDisposed = false;
var disposing = false;
var call = 0;
fv.addEventListener("pagecompleted", function () {
if (call === 0) {
// Initialized, should be in this state: [1], 2, 3. (This notation means that
// pages 1, 2, and 3 are realized and page 1 is the current page.)
LiveUnit.Assert.isFalse(firstItemDisposed, "The first page shouldn't have been disposed.");
fv.next();
} else if (call === 1) {
// First next was called, should be in this state: 1, [2], 3, 4
LiveUnit.Assert.isFalse(firstItemDisposed, "The first page shouldn't have been disposed.");
fv.next();
} else if (call === 2) {
// Second next was called, should be in this state: 1, 2, [3], 4, 5
LiveUnit.Assert.isFalse(firstItemDisposed, "The first page shouldn't have been disposed.");
fv.next();
} else if (call === 3) {
// Third next was called, should be in this state: 2, 3, [4], 5, 6. Verify that page 1 has been unrealized.
LiveUnit.Assert.isTrue(firstItemDisposed, "The first page should have been disposed, but was not.");
disposing = true;
fv.dispose();
document.body.removeChild(fv.element);
complete();
}
call++;
});
fv.itemDataSource = list.dataSource;
};
}
(function () {
function generateTest(ds) {
return function (complete) {
var flipperElement = document.createElement('div'),
flipper;
document.body.appendChild(flipperElement);
var onComplete = function (ev) {
flipperElement.removeEventListener("pagecompleted", onComplete);
flipperElement.addEventListener("pagecompleted", function (ev) {
// Done
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
complete();
});
// Move a non-current item in datasource
flipper.itemDataSource.itemFromIndex(4).then(function (item) {
// Move the item to end
flipper.itemDataSource.moveToEnd(item.key).then(function () {
// Jump to the end
flipper.currentPage = 9;
});
});
};
flipper = new WinJS.UI.FlipView(flipperElement, {
itemDataSource: ds,
onpagecompleted: onComplete,
itemTemplate: Helper.syncJSTemplate
});
}
}
var bl = Helper.createBindingList(10).dataSource;
FlipperInstantiationTests.prototype["testMoveItemAndJumpBL"] = generateTest(bl);
})();
(function () {
function generateTest(fromDS, toDS) {
return function (complete) {
var flipperElement = document.createElement('div'),
flipper;
document.body.appendChild(flipperElement);
var onComplete = function (ev) {
flipperElement.removeEventListener("pagecompleted", onComplete);
flipperElement.addEventListener("pagecompleted", function (ev) {
// Done
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
complete();
});
// Update the itemDataSource
flipper.itemDataSource = toDS;
};
flipper = new WinJS.UI.FlipView(flipperElement, {
itemDataSource: fromDS,
onpageselected: onComplete,
itemTemplate: Helper.syncJSTemplate
});
}
}
var bl = Helper.createBindingList(10).dataSource,
vds = Helper.createTestDataSource(10),
emptyBL = Helper.createBindingList(0).dataSource,
emptyVDS = Helper.createTestDataSource(0);
FlipperInstantiationTests.prototype["testUpdateToEmptyBindingList"] = generateTest(vds, emptyBL);
FlipperInstantiationTests.prototype["testUpdateToEmptyVDS"] = generateTest(bl, emptyVDS);
})();
(function () {
function generateTest(currentPage) {
return function (complete) {
var element = document.createElement('div');
globTest.vds = Helper.createTestDataSource(20);
document.body.appendChild(element);
element.innerHTML = '<div class="flipperTemplate" data-win-control="WinJS.Binding.Template">' +
'<div data-win-bind="innerHTML: title; style.width: itemWidth; style.height: itemHeight;"></div></div>' +
'<div class="flipperDiv" data-win-control="WinJS.UI.FlipView" data-win-options="{ currentPage: ' +
currentPage + ', onpagecompleted: globTest.onComplete, itemDataSource: globTest.vds, itemTemplate: ' +
'select(' + "'" + '.flipperTemplate' + "'" + ') }"></div>';
globTest.onComplete = WinJS.Utilities.markSupportedForProcessing(function (ev) {
// Verify
var flipper = element.querySelector(".flipperDiv").winControl;
LiveUnit.Assert.areEqual(flipper.currentPage, currentPage, "Flipper didn't instantiate at the expected page");
// Done
WinJS.Utilities.disposeSubTree(element);
document.body.removeChild(element);
complete();
});
WinJS.UI.processAll(element);
}
}
FlipperInstantiationTests.prototype["testHTMLInstantiationWithCurrentPageAtStart"] = generateTest(0);
FlipperInstantiationTests.prototype["testHTMLInstantiationWithCurrentPageAtMiddle"] = generateTest(10);
FlipperInstantiationTests.prototype["testHTMLInstantiationWithCurrentPageAtEnd"] = generateTest(19);
})();
(function () {
function generateTest(ds) {
return function (complete) {
var flipperElement = document.createElement('div'),
flipper;
document.body.appendChild(flipperElement);
var onComplete = function (ev) {
// Verify
flipper.count().then(function (count) {
LiveUnit.Assert.areEqual(0, count, "Unexpected flipper count");
// Done
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
complete();
}, function (er) {
LiveUnit.Assert.fail("Flipper failed to return count");
});
};
flipper = new WinJS.UI.FlipView(flipperElement, {
itemDataSource: ds,
onpageselected: onComplete,
itemTemplate: Helper.syncJSTemplate
});
}
}
// Disabling the tests for now, as pageselected is never fired.
// Win8: 901271
FlipperInstantiationTests.prototype["xtestFlipViewEmptyBindingList"] = generateTest(Helper.createBindingList(0).dataSource);
FlipperInstantiationTests.prototype["xtestFlipViewEmptyVDS"] = generateTest(Helper.createTestDataSource(0));
})();
(function () {
function generateTest(ds, action) {
return function (complete) {
var flipperElement = document.createElement('div'),
flipper,
before,
after;
document.body.appendChild(flipperElement);
var onComplete = function (ev) {
flipperElement.removeEventListener("pagecompleted", onComplete);
// Grab the currently visible element
before = flipper._pageManager._currentPage.element.innerHTML;
flipperElement.addEventListener("pagecompleted", function (ev) {
// Grab the currently visible element and compare to the previously current element
after = flipper._pageManager._currentPage.element.innerHTML;
// Verify
LiveUnit.Assert.areEqual(after, before, "Current Page elements are different");
// Done
WinJS.Utilities.disposeSubTree(flipperElement);
document.body.removeChild(flipperElement);
complete();
});
// Perform action
action();
};
flipperElement.addEventListener("pagecompleted", onComplete);
flipper = new WinJS.UI.FlipView(flipperElement, {
itemDataSource: ds,
itemTemplate: Helper.syncJSTemplate
});
}
}
// I should be able to use datasources across tests
var bl = Helper.createBindingList(10),
vds = Helper.createTestDataSource(10),
setItemTemplate = function () {
var flipperElement = <HTMLElement>document.getElementsByClassName("win-flipview")[0],
flipper = flipperElement.winControl;
flipper.itemTemplate = flipper.itemTemplate;
},
setItemDataSource = function () {
var flipperElement = <HTMLElement>document.getElementsByClassName("win-flipview")[0],
flipper = flipperElement.winControl;
flipper.itemDataSource = flipper.itemDataSource;
};
FlipperInstantiationTests.prototype["testBindingListSetItemDataSource"] = generateTest(bl.dataSource, setItemDataSource);
FlipperInstantiationTests.prototype["testBindingListSetItemTemplate"] = generateTest(bl.dataSource, setItemTemplate);
FlipperInstantiationTests.prototype["testVDSSetItemDataSource"] = generateTest(vds, setItemDataSource);
FlipperInstantiationTests.prototype["testVDSSetItemTemplate"] = generateTest(vds, setItemTemplate);
})();
}
LiveUnit.registerTestClass("WinJSTests.FlipperInstantiationTests"); | the_stack |
import { autoBindMethodsForReact } from 'class-autobind-decorator';
import classnames from 'classnames';
import clone from 'clone';
import React, { FC, PureComponent, ReactNode } from 'react';
import { AUTOBIND_CFG } from '../../../common/constants';
import { database as db } from '../../../common/database';
import { delay, fnOrString } from '../../../common/misc';
import { HandleGetRenderContext, HandleRender } from '../../../common/render';
import { metaSortKeySort } from '../../../common/sorting';
import * as models from '../../../models';
import type { BaseModel } from '../../../models/index';
import { isRequest, Request } from '../../../models/request';
import { isRequestGroup, RequestGroup } from '../../../models/request-group';
import type { Workspace } from '../../../models/workspace';
import { getTemplateTags } from '../../../plugins';
import * as pluginContexts from '../../../plugins/context';
import * as templating from '../../../templating';
import type { PluginArgumentEnumOption } from '../../../templating/extensions/index';
import type {
NunjucksActionTag,
NunjucksParsedTag,
NunjucksParsedTagArg,
} from '../../../templating/utils';
import * as templateUtils from '../../../templating/utils';
import { useNunjucks } from '../../context/nunjucks/use-nunjucks';
import { Dropdown } from '../base/dropdown/dropdown';
import { DropdownButton } from '../base/dropdown/dropdown-button';
import { DropdownDivider } from '../base/dropdown/dropdown-divider';
import { DropdownItem } from '../base/dropdown/dropdown-item';
import { FileInputButton } from '../base/file-input-button';
import { HelpTooltip } from '../help-tooltip';
interface Props {
handleRender: HandleRender;
handleGetRenderContext: HandleGetRenderContext;
defaultValue: string;
onChange: (...args: any[]) => any;
workspace: Workspace;
}
interface State {
activeTagData: NunjucksParsedTag | null;
activeTagDefinition: NunjucksParsedTag | null;
tagDefinitions: NunjucksParsedTag[];
loadingDocs: boolean;
allDocs: Record<string, BaseModel[]>;
rendering: boolean;
preview: string;
error: string;
variables: {
name: string;
value: string;
}[];
}
@autoBindMethodsForReact(AUTOBIND_CFG)
class TagEditorInternal extends PureComponent<Props, State> {
_select: HTMLSelectElement | null = null;
state: State = {
activeTagData: null,
activeTagDefinition: null,
tagDefinitions: [],
loadingDocs: false,
allDocs: {},
rendering: true,
preview: '',
error: '',
variables: [],
};
async load() {
const activeTagData = templateUtils.tokenizeTag(this.props.defaultValue);
const tagDefinitions = await templating.getTagDefinitions();
const activeTagDefinition: NunjucksParsedTag | null =
tagDefinitions.find(d => d.name === activeTagData.name) || null;
// Edit tags raw that we don't know about
if (!activeTagDefinition) {
activeTagData.rawValue = this.props.defaultValue;
}
// Fix strings: arg.value expects an escaped value (based on _updateArg logic)
for (const arg of activeTagData.args) {
if (typeof arg.value === 'string') {
arg.value = this._escapeStringArgs(arg.value);
}
}
await Promise.all([
this._refreshModels(this.props.workspace),
this._update(tagDefinitions, activeTagDefinition, activeTagData, true),
]);
}
async loadVariables() {
const context = await this.props.handleGetRenderContext();
const variables = context.keys;
this.setState({
variables,
});
}
componentDidMount() {
this.load();
this.loadVariables();
}
// eslint-disable-next-line camelcase
UNSAFE_componentWillReceiveProps(nextProps: Props) {
const { workspace } = nextProps;
if (this.props.workspace._id !== workspace._id) {
this._refreshModels(workspace);
}
}
async _handleRefresh() {
await this._update(
this.state.tagDefinitions,
this.state.activeTagDefinition,
this.state.activeTagData,
true,
);
}
_sortRequests(_models: (Request | RequestGroup)[], parentId: string) {
let sortedModels: (Request | RequestGroup)[] = [];
_models
.filter(model => model.parentId === parentId)
.sort(metaSortKeySort)
.forEach(model => {
if (isRequest(model)) {
sortedModels.push(model);
}
if (isRequestGroup(model)) {
sortedModels = sortedModels.concat(this._sortRequests(_models, model._id));
}
});
return sortedModels;
}
async _refreshModels(workspace: Workspace) {
this.setState({
loadingDocs: true,
});
const allDocs = {};
for (const type of models.types()) {
allDocs[type] = [];
}
for (const doc of await db.withDescendants(workspace, models.request.type)) {
allDocs[doc.type].push(doc);
}
const requests = allDocs[models.request.type] || [];
const requestGroups = allDocs[models.requestGroup.type] || [];
const sortedReqs = this._sortRequests(requests.concat(requestGroups), this.props.workspace._id);
allDocs[models.request.type] = sortedReqs;
this.setState({
allDocs,
loadingDocs: false,
});
}
async _updateArg(
argValue: string | number | boolean,
argIndex: number,
forceNewType: string | null = null,
patch: Record<string, any> = {},
) {
const { tagDefinitions, activeTagData, activeTagDefinition } = this.state;
if (!activeTagData) {
console.warn('No active tag data to update', {
state: this.state,
});
return;
}
if (!activeTagDefinition) {
console.warn('No active tag definition to update', {
state: this.state,
});
return;
}
// Fix strings
if (typeof argValue === 'string') {
argValue = this._escapeStringArgs(argValue);
}
// Ensure all arguments exist
const defaultArgs = TagEditorInternal._getDefaultTagData(activeTagDefinition).args;
for (let i = 0; i < defaultArgs.length; i++) {
if (activeTagData.args[i]) {
continue;
}
activeTagData.args[i] = defaultArgs[i];
}
const tagData = clone(activeTagData);
const argData: NunjucksParsedTagArg = tagData.args[argIndex];
if (!argData) {
// Should never happen
console.warn('Could not find arg data to update', {
tagData,
argIndex,
});
return;
}
// Update it
argData.value = argValue;
// Update type if we need to
if (forceNewType) {
// Ugh, what a hack (because it's enum)
Object.assign(
argData as any,
{
type: forceNewType,
},
patch,
);
}
await this._update(tagDefinitions, activeTagDefinition, tagData, false);
}
async _handleChangeArgVariable(options: { argIndex: number; variable: boolean }) {
const { variable, argIndex } = options;
const { activeTagData, activeTagDefinition, variables } = this.state;
if (!activeTagData || !activeTagDefinition) {
console.warn('Failed to change arg variable', {
state: this.state,
});
return;
}
const argData = activeTagData.args[argIndex];
const argDef = activeTagDefinition.args[argIndex];
const existingValue = argData ? argData.value : '';
if (variable) {
const variable = variables.find(v => v.value === existingValue);
const firstVariable = variables.length ? variables[0].name : '';
const value = variable ? variable.name : firstVariable;
return this._updateArg(value || 'my_variable', argIndex, 'variable');
} else {
const initialType = argDef ? argDef.type : 'string';
const variable = variables.find(v => v.name === existingValue);
const value = variable ? variable.value : '';
return this._updateArg(value, argIndex, initialType, {
quotedBy: "'",
});
}
}
_handleChangeFile(path: string, argIndex: number) {
return this._updateArg(path, argIndex);
}
_handleChange(event: React.SyntheticEvent<HTMLInputElement | HTMLSelectElement>) {
const parent = event.currentTarget.parentNode;
let argIndex = -1;
if (parent instanceof HTMLElement) {
const index = parent?.getAttribute('data-arg-index');
argIndex = typeof index === 'string' ? parseInt(index, 10) : -1;
}
// Handle special types
if (event.currentTarget.getAttribute('data-encoding') === 'base64') {
return this._updateArg(
templateUtils.encodeEncoding(event.currentTarget.value, 'base64'),
argIndex,
);
}
// Handle normal types
if (event.currentTarget.type === 'number') {
return this._updateArg(parseFloat(event.currentTarget.value), argIndex);
} else if (event.currentTarget.type === 'checkbox') {
// @ts-expect-error -- TSCONVERSION .checked doesn't exist on HTMLSelectElement
return this._updateArg(event.currentTarget.checked, argIndex);
} else {
return this._updateArg(event.currentTarget.value, argIndex);
}
}
_handleChangeCustomArg(event: React.SyntheticEvent<HTMLInputElement>) {
const { tagDefinitions, activeTagData, activeTagDefinition } = this.state;
const tagData: NunjucksParsedTag | null = clone(activeTagData);
if (tagData) {
tagData.rawValue = event.currentTarget.value;
}
this._update(tagDefinitions, activeTagDefinition, tagData, false);
}
async _handleChangeTag(event: React.SyntheticEvent<HTMLInputElement | HTMLSelectElement>) {
const name = event.currentTarget.value;
const tagDefinitions = await templating.getTagDefinitions();
const tagDefinition = tagDefinitions.find(d => d.name === name) || null;
this._update(this.state.tagDefinitions, tagDefinition, null, false);
}
async _handleActionClick(action: NunjucksActionTag) {
const templateTags = await getTemplateTags();
const activeTemplateTag = templateTags.find(({ templateTag }) => {
return templateTag.name === this.state.activeTagData?.name;
});
// @ts-expect-error -- TSCONVERSION activeTemplateTag can be undefined
const helperContext: pluginContexts.PluginStore = { ...pluginContexts.store.init(activeTemplateTag.plugin) };
await action.run(helperContext);
return this._handleRefresh();
}
_setSelectRef(select: HTMLSelectElement) {
this._select = select;
// Let it render, then focus the input
setTimeout(() => {
if (this._select instanceof HTMLSelectElement) {
this._select.focus();
}
}, 100);
}
_escapeStringArgs(value: string) {
return value.replace(/\\/g, '\\\\');
}
_unescapeStringArgs(value: string) {
return value.replace(/\\\\/g, '\\');
}
static _getDefaultTagData(tagDefinition: NunjucksParsedTag): NunjucksParsedTag {
const defaultFill: string = templateUtils.getDefaultFill(
tagDefinition.name,
tagDefinition.args,
);
return templateUtils.tokenizeTag(defaultFill);
}
async _update(
tagDefinitions: NunjucksParsedTag[],
tagDefinition: NunjucksParsedTag | null,
tagData: NunjucksParsedTag | null,
noCallback = false,
) {
const { handleRender } = this.props;
this.setState({
rendering: true,
});
// Start render loader
const start = Date.now();
this.setState({
rendering: true,
});
let preview = '';
let error = '';
let activeTagData: NunjucksParsedTag | null = tagData;
if (!activeTagData && tagDefinition) {
activeTagData = TagEditorInternal._getDefaultTagData(tagDefinition);
} else if (!activeTagData && !tagDefinition && this.state.activeTagData) {
activeTagData = {
name: 'custom',
displayName: 'Custom',
args: [],
rawValue: templateUtils.unTokenizeTag(this.state.activeTagData),
};
}
let template;
if (activeTagData) {
try {
template =
typeof activeTagData.rawValue === 'string'
? activeTagData.rawValue
: templateUtils.unTokenizeTag(activeTagData);
preview = await handleRender(template);
} catch (err) {
error = err.message;
}
}
this.setState({
tagDefinitions,
activeTagData,
error,
activeTagDefinition: tagDefinition,
});
// Call the callback if we need to
if (!noCallback) {
this.props.onChange(template);
}
// Make rendering take at least this long so we can see a spinner
await delay(300 - (Date.now() - start));
this.setState({
rendering: false,
preview,
});
}
renderArgVariable(path: string) {
const { variables } = this.state;
if (variables.length === 0) {
return (
<select disabled>
<option>-- No Environment Variables Found --</option>
</select>
);
}
return (
<select value={path || ''} onChange={this._handleChange}>
<option key="n/a" value="NO_VARIABLE">
-- Select Variable --
</option>
{variables.map((v, i) => (
<option key={`${i}::${v.name}`} value={v.name}>
{v.name}
</option>
))}
</select>
);
}
renderArgString(value: string, placeholder: string, encoding: string) {
return (
<input
type="text"
defaultValue={this._unescapeStringArgs(value) || ''}
placeholder={placeholder}
onChange={this._handleChange}
data-encoding={encoding || 'utf8'}
/>
);
}
renderArgNumber(value: string, placeholder: string) {
return (
<input
type="number"
defaultValue={value || '0'}
placeholder={placeholder}
onChange={this._handleChange}
/>
);
}
renderArgBoolean(checked: boolean) {
return <input type="checkbox" checked={checked} onChange={this._handleChange} />;
}
renderArgFile(
value: string,
argIndex: number,
itemTypes?: ('file' | 'directory')[],
extensions?: string[],
) {
return (
<FileInputButton
showFileIcon
showFileName
className="btn btn--clicky btn--super-compact"
onChange={path => this._handleChangeFile(path, argIndex)}
path={this._unescapeStringArgs(value)}
itemtypes={itemTypes}
extensions={extensions}
/>
);
}
renderArgEnum(value: string, options: PluginArgumentEnumOption[]) {
const argDatas = this.state.activeTagData ? this.state.activeTagData.args : [];
let unsetOption: ReactNode = null;
if (!options.find(o => o.value === value)) {
unsetOption = <option value="">-- Select Option --</option>;
}
return (
<select value={value} onChange={this._handleChange}>
{unsetOption}
{options.map(option => {
let label: string;
const { description } = option;
if (description) {
label = `${fnOrString(option.displayName, argDatas)} – ${description}`;
} else {
label = fnOrString(option.displayName, argDatas);
}
return (
// @ts-expect-error -- TSCONVERSION boolean not accepted by option
<option key={option.value.toString()} value={option.value}>
{label}
</option>
);
})}
</select>
);
}
resolveRequestGroupPrefix(requestGroupId: string, allRequestGroups: any[]) {
let prefix = '';
let reqGroup: any;
do {
// Get prefix from inner most request group.
reqGroup = allRequestGroups.find(rg => rg._id === requestGroupId);
if (reqGroup == null) {
break;
}
const name = typeof reqGroup.name === 'string' ? reqGroup.name : '';
prefix = `[${name}] ` + prefix;
requestGroupId = reqGroup.parentId;
} while (true);
return prefix;
}
renderArgModel(value: string, modelType: string) {
const { allDocs, loadingDocs } = this.state;
const docs = allDocs[modelType] || [];
const id = value || 'n/a';
if (loadingDocs) {
return (
<select disabled={loadingDocs}>
<option>Loading...</option>
</select>
);
}
return (
<select value={id} onChange={this._handleChange}>
<option value="n/a">-- Select Item --</option>
{docs.map((doc: any) => {
let namePrefix: string | null = null;
// Show parent folder with name if it's a request
if (isRequest(doc)) {
const requests = allDocs[models.request.type] || [];
const request: any = requests.find(r => r._id === doc._id);
const method = request && typeof request.method === 'string' ? request.method : 'GET';
const parentId = request ? request.parentId : 'n/a';
const allRequestGroups = allDocs[models.requestGroup.type] || [];
const requestGroupPrefix = this.resolveRequestGroupPrefix(parentId, allRequestGroups);
namePrefix = `${requestGroupPrefix + method} `;
}
const docName = typeof doc.name === 'string' ? doc.name : 'Unknown Request';
return (
<option key={doc._id} value={doc._id}>
{namePrefix}
{docName}
</option>
);
})}
</select>
);
}
renderArg(
argDefinition: NunjucksParsedTagArg,
argDatas: NunjucksParsedTagArg[],
argIndex: number,
) {
// Decide whether or not to show it
if (typeof argDefinition.hide === 'function' && argDefinition.hide(argDatas)) {
return null;
}
let argData: NunjucksParsedTagArg;
if (argIndex < argDatas.length) {
argData = argDatas[argIndex];
} else if (this.state.activeTagDefinition) {
const defaultTagData = TagEditorInternal._getDefaultTagData(this.state.activeTagDefinition);
argData = defaultTagData.args[argIndex];
} else {
return null;
}
if (!argData) {
console.error('Failed to find argument to set default', {
argDefinition,
argDatas,
argIndex,
});
return null;
}
const strValue = templateUtils.decodeEncoding(argData.value.toString());
const isVariable = argData.type === 'variable';
const argInputVariable = isVariable ? this.renderArgVariable(strValue) : null;
let argInput;
let isVariableAllowed = true;
if (argDefinition.type === 'string') {
const placeholder =
typeof argDefinition.placeholder === 'string' ? argDefinition.placeholder : '';
const encoding = argDefinition.encoding || 'utf8';
argInput = this.renderArgString(strValue, placeholder, encoding);
} else if (argDefinition.type === 'enum') {
const { options } = argDefinition;
argInput = this.renderArgEnum(strValue, options || []);
} else if (argDefinition.type === 'file') {
argInput = this.renderArgFile(
strValue,
argIndex,
argDefinition.itemTypes,
argDefinition.extensions,
);
} else if (argDefinition.type === 'model') {
isVariableAllowed = false;
const model = typeof argDefinition.model === 'string' ? argDefinition.model : 'unknown';
const modelId = typeof strValue === 'string' ? strValue : 'unknown';
argInput = this.renderArgModel(modelId, model);
} else if (argDefinition.type === 'boolean') {
argInput = this.renderArgBoolean(strValue.toLowerCase() === 'true');
} else if (argDefinition.type === 'number') {
const placeholder =
typeof argDefinition.placeholder === 'string' ? argDefinition.placeholder : '';
argInput = this.renderArgNumber(strValue, placeholder || '');
} else {
return null;
}
const help =
typeof argDefinition.help === 'string' || typeof argDefinition.help === 'function'
? fnOrString(argDefinition.help, argDatas)
: '';
const displayName =
typeof argDefinition.displayName === 'string' ||
typeof argDefinition.displayName === 'function'
? fnOrString(argDefinition.displayName, argDatas)
: '';
let validationError = '';
const canValidate = argDefinition.type === 'string' || argDefinition.type === 'number';
if (canValidate && typeof argDefinition.validate === 'function') {
validationError = argDefinition.validate(strValue) || '';
}
const formControlClasses = classnames({
'form-control': true,
'form-control--thin': argDefinition.type === 'boolean',
'form-control--outlined': argDefinition.type !== 'boolean',
});
return (
<div key={argIndex} className="form-row">
<div className={formControlClasses}>
<label data-arg-index={argIndex}>
{fnOrString(displayName, argDatas)}
{isVariable && <span className="faded space-left">(Variable)</span>}
{help && <HelpTooltip className="space-left">{help}</HelpTooltip>}
{validationError && <span className="font-error space-left">{validationError}</span>}
{argInputVariable || argInput}
</label>
</div>
{isVariableAllowed ? (
<div
className={classnames('form-control form-control--outlined width-auto', {
'form-control--no-label': argDefinition.type !== 'boolean',
})}
>
<Dropdown right>
<DropdownButton className="btn btn--clicky">
<i className="fa fa-gear" />
</DropdownButton>
<DropdownDivider>Input Type</DropdownDivider>
<DropdownItem
value={{
variable: false,
argIndex,
}}
onClick={this._handleChangeArgVariable}
>
<i className={'fa ' + (isVariable ? '' : 'fa-check')} /> Static Value
</DropdownItem>
<DropdownItem
value={{
variable: true,
argIndex,
}}
onClick={this._handleChangeArgVariable}
>
<i className={'fa ' + (isVariable ? 'fa-check' : '')} /> Environment Variable
</DropdownItem>
</Dropdown>
</div>
) : null}
</div>
);
}
renderActions(actions: NunjucksActionTag[] = []) {
return (
<div className="form-row">
<div className="form-control">
<label>Actions</label>
<div className="form-row">{actions.map(this.renderAction)}</div>
</div>
</div>
);
}
renderAction(action: NunjucksActionTag) {
const name = action.name;
const icon = action.icon ? <i className={action.icon} /> : undefined;
return (
<button
key={name}
className="btn btn--clicky btn--largest"
type="button"
onClick={() => this._handleActionClick(action)}
>
{icon}
{name}
</button>
);
}
render() {
const { error, preview, activeTagDefinition, activeTagData, rendering } = this.state;
if (!activeTagData) {
return null;
}
let finalPreview = preview;
if (activeTagDefinition?.disablePreview) {
finalPreview = activeTagDefinition.disablePreview(activeTagData.args)
? preview.replace(/./g, '*')
: preview;
}
let previewElement;
if (error) {
previewElement = <textarea className="danger" value={error || 'Error'} readOnly rows={5} />;
} else if (rendering) {
previewElement = <textarea value="rendering..." readOnly rows={5} />;
} else {
previewElement = <textarea value={finalPreview || 'error'} readOnly rows={5} />;
}
return (
<div>
<div className="form-control form-control--outlined">
<label>
Function to Perform
<select
ref={this._setSelectRef}
onChange={this._handleChangeTag}
value={activeTagDefinition ? activeTagDefinition.name : ''}
>
{this.state.tagDefinitions.map((tagDefinition, i) => (
<option key={`${i}::${tagDefinition.name}`} value={tagDefinition.name}>
{tagDefinition.displayName} – {tagDefinition.description}
</option>
))}
<option value="custom">-- Custom --</option>
</select>
</label>
</div>
{activeTagDefinition?.args.map((argDefinition: NunjucksParsedTagArg, index) =>
this.renderArg(argDefinition, activeTagData.args, index),
)}
{activeTagDefinition?.actions && activeTagDefinition?.actions?.length > 0 ? (
this.renderActions(activeTagDefinition.actions)
) : null}
{!activeTagDefinition && (
<div className="form-control form-control--outlined">
<label>
Custom
<input
type="text"
defaultValue={activeTagData.rawValue}
onChange={this._handleChangeCustomArg}
/>
</label>
</div>
)}
<hr className="hr" />
<div className="form-row">
<div className="form-control form-control--outlined">
<button
type="button"
style={{
zIndex: 10,
position: 'relative',
}}
className="txt-sm pull-right icon inline-block"
onClick={this._handleRefresh}
>
refresh{' '}
<i
className={classnames('fa fa-refresh', {
'fa-spin': rendering,
})}
/>
</button>
<label>
Live Preview
{previewElement}
</label>
</div>
</div>
</div>
);
}
}
export const TagEditor: FC<Omit<Props, 'handleRender' | 'handleGetRenderContext'>> = props => {
const { handleRender, handleGetRenderContext } = useNunjucks();
return <TagEditorInternal {...props} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} />;
}; | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
CancelRotateSecretCommand,
CancelRotateSecretCommandInput,
CancelRotateSecretCommandOutput,
} from "./commands/CancelRotateSecretCommand";
import {
CreateSecretCommand,
CreateSecretCommandInput,
CreateSecretCommandOutput,
} from "./commands/CreateSecretCommand";
import {
DeleteResourcePolicyCommand,
DeleteResourcePolicyCommandInput,
DeleteResourcePolicyCommandOutput,
} from "./commands/DeleteResourcePolicyCommand";
import {
DeleteSecretCommand,
DeleteSecretCommandInput,
DeleteSecretCommandOutput,
} from "./commands/DeleteSecretCommand";
import {
DescribeSecretCommand,
DescribeSecretCommandInput,
DescribeSecretCommandOutput,
} from "./commands/DescribeSecretCommand";
import {
GetRandomPasswordCommand,
GetRandomPasswordCommandInput,
GetRandomPasswordCommandOutput,
} from "./commands/GetRandomPasswordCommand";
import {
GetResourcePolicyCommand,
GetResourcePolicyCommandInput,
GetResourcePolicyCommandOutput,
} from "./commands/GetResourcePolicyCommand";
import {
GetSecretValueCommand,
GetSecretValueCommandInput,
GetSecretValueCommandOutput,
} from "./commands/GetSecretValueCommand";
import { ListSecretsCommand, ListSecretsCommandInput, ListSecretsCommandOutput } from "./commands/ListSecretsCommand";
import {
ListSecretVersionIdsCommand,
ListSecretVersionIdsCommandInput,
ListSecretVersionIdsCommandOutput,
} from "./commands/ListSecretVersionIdsCommand";
import {
PutResourcePolicyCommand,
PutResourcePolicyCommandInput,
PutResourcePolicyCommandOutput,
} from "./commands/PutResourcePolicyCommand";
import {
PutSecretValueCommand,
PutSecretValueCommandInput,
PutSecretValueCommandOutput,
} from "./commands/PutSecretValueCommand";
import {
RemoveRegionsFromReplicationCommand,
RemoveRegionsFromReplicationCommandInput,
RemoveRegionsFromReplicationCommandOutput,
} from "./commands/RemoveRegionsFromReplicationCommand";
import {
ReplicateSecretToRegionsCommand,
ReplicateSecretToRegionsCommandInput,
ReplicateSecretToRegionsCommandOutput,
} from "./commands/ReplicateSecretToRegionsCommand";
import {
RestoreSecretCommand,
RestoreSecretCommandInput,
RestoreSecretCommandOutput,
} from "./commands/RestoreSecretCommand";
import {
RotateSecretCommand,
RotateSecretCommandInput,
RotateSecretCommandOutput,
} from "./commands/RotateSecretCommand";
import {
StopReplicationToReplicaCommand,
StopReplicationToReplicaCommandInput,
StopReplicationToReplicaCommandOutput,
} from "./commands/StopReplicationToReplicaCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateSecretCommand,
UpdateSecretCommandInput,
UpdateSecretCommandOutput,
} from "./commands/UpdateSecretCommand";
import {
UpdateSecretVersionStageCommand,
UpdateSecretVersionStageCommandInput,
UpdateSecretVersionStageCommandOutput,
} from "./commands/UpdateSecretVersionStageCommand";
import {
ValidateResourcePolicyCommand,
ValidateResourcePolicyCommandInput,
ValidateResourcePolicyCommandOutput,
} from "./commands/ValidateResourcePolicyCommand";
import { SecretsManagerClient } from "./SecretsManagerClient";
/**
* <fullname>Amazon Web Services Secrets Manager</fullname>
* <p>Amazon Web Services Secrets Manager provides a service to enable you to store, manage, and retrieve, secrets.</p>
*
* <p>This guide provides descriptions of the Secrets Manager API. For more information about using this
* service, see the <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/introduction.html">Amazon Web Services Secrets Manager User Guide</a>.</p>
*
* <p>
* <b>API Version</b>
* </p>
*
* <p>This version of the Secrets Manager API Reference documents the Secrets Manager API version 2017-10-17.</p>
* <note>
* <p>As an alternative to using the API, you can use one of the Amazon Web Services SDKs, which consist of
* libraries and sample code for various programming languages and platforms such as Java,
* Ruby, .NET, iOS, and Android. The SDKs provide a convenient way to create programmatic
* access to Amazon Web Services Secrets Manager. For example, the SDKs provide cryptographically signing requests,
* managing errors, and retrying requests automatically. For more information about the Amazon Web Services
* SDKs, including downloading and installing them, see <a href="http://aws.amazon.com/tools/">Tools for Amazon Web Services</a>.</p>
* </note>
* <p>We recommend you use the Amazon Web Services SDKs to make programmatic API calls to Secrets Manager. However, you
* also can use the Secrets Manager HTTP Query API to make direct calls to the Secrets Manager web service. To learn
* more about the Secrets Manager HTTP Query API, see <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/query-requests.html">Making Query Requests</a> in the
* <i>Amazon Web Services Secrets Manager User Guide</i>. </p>
* <p>Secrets Manager API supports GET and POST requests for all actions, and doesn't require you to use
* GET for some actions and POST for others. However, GET requests are subject to the limitation
* size of a URL. Therefore, for operations that require larger sizes, use a POST request.</p>
*
*
*
*
*
*
*
* <p>
* <b>Support and Feedback for Amazon Web Services Secrets Manager</b>
* </p>
*
* <p>We welcome your feedback. Send your comments to <a href="mailto:awssecretsmanager-feedback@amazon.com">awssecretsmanager-feedback@amazon.com</a>, or post your feedback and questions in the <a href="http://forums.aws.amazon.com/forum.jspa?forumID=296">Amazon Web Services Secrets Manager Discussion Forum</a>. For more
* information about the Amazon Web Services Discussion Forums, see <a href="http://forums.aws.amazon.com/help.jspa">Forums
* Help</a>.</p>
*
* <p>
* <b>How examples are presented</b>
* </p>
*
* <p>The JSON that Amazon Web Services Secrets Manager expects as your request parameters and the service returns as a
* response to HTTP query requests contain single, long strings without line breaks or white
* space formatting. The JSON shown in the examples displays the code formatted with both line
* breaks and white space to improve readability. When example input parameters can also cause
* long strings extending beyond the screen, you can insert line breaks to enhance readability.
* You should always submit the input as a single JSON text string.</p>
*
*
* <p>
* <b>Logging API Requests</b>
* </p>
* <p>Amazon Web Services Secrets Manager supports Amazon Web Services CloudTrail, a service that records Amazon Web Services API calls for your Amazon Web Services
* account and delivers log files to an Amazon S3 bucket. By using information that's collected
* by Amazon Web Services CloudTrail, you can determine the requests successfully made to Secrets Manager, who made the
* request, when it was made, and so on. For more about Amazon Web Services Secrets Manager and support for Amazon Web Services
* CloudTrail, see <a href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/monitoring.html#monitoring_cloudtrail">Logging
* Amazon Web Services Secrets Manager Events with Amazon Web Services CloudTrail</a> in the <i>Amazon Web Services Secrets Manager User Guide</i>.
* To learn more about CloudTrail, including enabling it and find your log files, see the <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html">Amazon Web Services CloudTrail User Guide</a>.</p>
*/
export class SecretsManager extends SecretsManagerClient {
/**
* <p>Disables automatic scheduled rotation and cancels the rotation of a secret if currently in
* progress.</p>
* <p>To re-enable scheduled rotation, call <a>RotateSecret</a> with
* <code>AutomaticallyRotateAfterDays</code> set to a value greater than 0. This immediately
* rotates your secret and then enables the automatic schedule.</p>
* <note>
* <p>If you cancel a rotation while in progress, it can leave the <code>VersionStage</code>
* labels in an unexpected state. Depending on the step of the rotation in progress, you might
* need to remove the staging label <code>AWSPENDING</code> from the partially created version, specified
* by the <code>VersionId</code> response value. You should also evaluate the partially rotated
* new version to see if it should be deleted, which you can do by removing all staging labels
* from the new version <code>VersionStage</code> field.</p>
* </note>
* <p>To successfully start a rotation, the staging label <code>AWSPENDING</code> must be in one of the
* following states:</p>
* <ul>
* <li>
* <p>Not attached to any version at all</p>
* </li>
* <li>
* <p>Attached to the same version as the staging label <code>AWSCURRENT</code>
* </p>
* </li>
* </ul>
* <p>If the staging label <code>AWSPENDING</code> attached to a different version than the version with
* <code>AWSCURRENT</code> then the attempt to rotate fails.</p>
*
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:CancelRotateSecret</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To configure rotation for a secret or to manually trigger a rotation, use <a>RotateSecret</a>.</p>
* </li>
* <li>
* <p>To get the rotation configuration details for a secret, use <a>DescribeSecret</a>.</p>
* </li>
* <li>
* <p>To list all of the currently available secrets, use <a>ListSecrets</a>.</p>
* </li>
* <li>
* <p>To list all of the versions currently associated with a secret, use <a>ListSecretVersionIds</a>.</p>
* </li>
* </ul>
*/
public cancelRotateSecret(
args: CancelRotateSecretCommandInput,
options?: __HttpHandlerOptions
): Promise<CancelRotateSecretCommandOutput>;
public cancelRotateSecret(
args: CancelRotateSecretCommandInput,
cb: (err: any, data?: CancelRotateSecretCommandOutput) => void
): void;
public cancelRotateSecret(
args: CancelRotateSecretCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CancelRotateSecretCommandOutput) => void
): void;
public cancelRotateSecret(
args: CancelRotateSecretCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CancelRotateSecretCommandOutput) => void),
cb?: (err: any, data?: CancelRotateSecretCommandOutput) => void
): Promise<CancelRotateSecretCommandOutput> | void {
const command = new CancelRotateSecretCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a new secret. A secret in Secrets Manager consists of both the protected secret data and the
* important information needed to manage the secret.</p>
* <p>Secrets Manager stores the encrypted secret data in one of a collection of "versions"
* associated with the secret. Each version contains a copy of the encrypted secret data. Each
* version is associated with one or more "staging labels" that identify where the version is in
* the rotation cycle. The <code>SecretVersionsToStages</code> field of the secret contains the
* mapping of staging labels to the active versions of the secret. Versions without a staging
* label are considered deprecated and not included in the list.</p>
* <p>You provide the secret data to be encrypted by putting text in either the
* <code>SecretString</code> parameter or binary data in the <code>SecretBinary</code>
* parameter, but not both. If you include <code>SecretString</code> or <code>SecretBinary</code>
* then Secrets Manager also creates an initial secret version and automatically attaches the staging
* label <code>AWSCURRENT</code> to the new version.</p>
* <note>
* <ul>
* <li>
* <p>If you call an operation to encrypt or decrypt the <code>SecretString</code>
* or <code>SecretBinary</code> for a secret in the same account as the calling user and that
* secret doesn't specify a Amazon Web Services KMS encryption key, Secrets Manager uses the account's default
* Amazon Web Services managed customer master key (CMK) with the alias <code>aws/secretsmanager</code>. If this key
* doesn't already exist in your account then Secrets Manager creates it for you automatically. All
* users and roles in the same Amazon Web Services account automatically have access to use the default CMK.
* Note that if an Secrets Manager API call results in Amazon Web Services creating the account's
* Amazon Web Services-managed CMK, it can result in a one-time significant delay in returning the
* result.</p>
* </li>
* <li>
* <p>If the secret resides in a different Amazon Web Services account from the credentials calling an API that
* requires encryption or decryption of the secret value then you must create and use a custom
* Amazon Web Services KMS CMK because you can't access the default CMK for the account using credentials
* from a different Amazon Web Services account. Store the ARN of the CMK in the secret when you create the
* secret or when you update it by including it in the <code>KMSKeyId</code>. If you call an
* API that must encrypt or decrypt <code>SecretString</code> or <code>SecretBinary</code>
* using credentials from a different account then the Amazon Web Services KMS key policy must grant cross-account
* access to that other account's user or role for both the kms:GenerateDataKey and
* kms:Decrypt operations.</p>
* </li>
* </ul>
* </note>
* <p> </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:CreateSecret</p>
* </li>
* <li>
* <p>kms:GenerateDataKey - needed only if you use a customer-managed Amazon Web Services KMS key to encrypt
* the secret. You do not need this permission to use the account default Amazon Web Services managed CMK
* for Secrets Manager.</p>
* </li>
* <li>
* <p>kms:Decrypt - needed only if you use a customer-managed Amazon Web Services KMS key to encrypt the
* secret. You do not need this permission to use the account default Amazon Web Services managed CMK for
* Secrets Manager.</p>
* </li>
* <li>
* <p>secretsmanager:TagResource - needed only if you include the <code>Tags</code>
* parameter. </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To delete a secret, use <a>DeleteSecret</a>.</p>
* </li>
* <li>
* <p>To modify an existing secret, use <a>UpdateSecret</a>.</p>
* </li>
* <li>
* <p>To create a new version of a secret, use <a>PutSecretValue</a>.</p>
* </li>
* <li>
* <p>To retrieve the encrypted secure string and secure binary values, use <a>GetSecretValue</a>.</p>
* </li>
* <li>
* <p>To retrieve all other details for a secret, use <a>DescribeSecret</a>. This
* does not include the encrypted secure string and secure binary values.</p>
* </li>
* <li>
* <p>To retrieve the list of secret versions associated with the current secret, use <a>DescribeSecret</a> and examine the <code>SecretVersionsToStages</code> response
* value.</p>
* </li>
* </ul>
*/
public createSecret(
args: CreateSecretCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateSecretCommandOutput>;
public createSecret(args: CreateSecretCommandInput, cb: (err: any, data?: CreateSecretCommandOutput) => void): void;
public createSecret(
args: CreateSecretCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateSecretCommandOutput) => void
): void;
public createSecret(
args: CreateSecretCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateSecretCommandOutput) => void),
cb?: (err: any, data?: CreateSecretCommandOutput) => void
): Promise<CreateSecretCommandOutput> | void {
const command = new CreateSecretCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the resource-based permission policy attached to the secret.</p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:DeleteResourcePolicy</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To attach a resource policy to a secret, use <a>PutResourcePolicy</a>.</p>
* </li>
* <li>
* <p>To retrieve the current resource-based policy attached to a secret, use <a>GetResourcePolicy</a>.</p>
* </li>
* <li>
* <p>To list all of the currently available secrets, use <a>ListSecrets</a>.</p>
* </li>
* </ul>
*/
public deleteResourcePolicy(
args: DeleteResourcePolicyCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteResourcePolicyCommandOutput>;
public deleteResourcePolicy(
args: DeleteResourcePolicyCommandInput,
cb: (err: any, data?: DeleteResourcePolicyCommandOutput) => void
): void;
public deleteResourcePolicy(
args: DeleteResourcePolicyCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteResourcePolicyCommandOutput) => void
): void;
public deleteResourcePolicy(
args: DeleteResourcePolicyCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteResourcePolicyCommandOutput) => void),
cb?: (err: any, data?: DeleteResourcePolicyCommandOutput) => void
): Promise<DeleteResourcePolicyCommandOutput> | void {
const command = new DeleteResourcePolicyCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes an entire secret and all of the versions. You can optionally include a recovery
* window during which you can restore the secret. If you don't specify a recovery window value,
* the operation defaults to 30 days. Secrets Manager attaches a <code>DeletionDate</code> stamp to
* the secret that specifies the end of the recovery window. At the end of the recovery window,
* Secrets Manager deletes the secret permanently.</p>
* <p>At any time before recovery window ends, you can use <a>RestoreSecret</a> to
* remove the <code>DeletionDate</code> and cancel the deletion of the secret.</p>
* <p>You cannot access the encrypted secret information in any secret scheduled for deletion.
* If you need to access that information, you must cancel the deletion with <a>RestoreSecret</a> and then retrieve the information.</p>
* <note>
* <ul>
* <li>
* <p>There is no explicit operation to delete a version of a secret. Instead, remove all
* staging labels from the <code>VersionStage</code> field of a version. That marks the
* version as deprecated and allows Secrets Manager to delete it as needed. Versions without any
* staging labels do not show up in <a>ListSecretVersionIds</a> unless you
* specify <code>IncludeDeprecated</code>.</p>
* </li>
* <li>
* <p>The permanent secret deletion at the end of the waiting period is performed as a
* background task with low priority. There is no guarantee of a specific time after the
* recovery window for the actual delete operation to occur.</p>
* </li>
* </ul>
* </note>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:DeleteSecret</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To create a secret, use <a>CreateSecret</a>.</p>
* </li>
* <li>
* <p>To cancel deletion of a version of a secret before the recovery window has expired,
* use <a>RestoreSecret</a>.</p>
* </li>
* </ul>
*/
public deleteSecret(
args: DeleteSecretCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteSecretCommandOutput>;
public deleteSecret(args: DeleteSecretCommandInput, cb: (err: any, data?: DeleteSecretCommandOutput) => void): void;
public deleteSecret(
args: DeleteSecretCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteSecretCommandOutput) => void
): void;
public deleteSecret(
args: DeleteSecretCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteSecretCommandOutput) => void),
cb?: (err: any, data?: DeleteSecretCommandOutput) => void
): Promise<DeleteSecretCommandOutput> | void {
const command = new DeleteSecretCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the details of a secret. It does not include the encrypted fields. Secrets
* Manager only returns fields populated with a value in the response. </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:DescribeSecret</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To create a secret, use <a>CreateSecret</a>.</p>
* </li>
* <li>
* <p>To modify a secret, use <a>UpdateSecret</a>.</p>
* </li>
* <li>
* <p>To retrieve the encrypted secret information in a version of the secret, use <a>GetSecretValue</a>.</p>
* </li>
* <li>
* <p>To list all of the secrets in the Amazon Web Services account, use <a>ListSecrets</a>.</p>
* </li>
* </ul>
*/
public describeSecret(
args: DescribeSecretCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeSecretCommandOutput>;
public describeSecret(
args: DescribeSecretCommandInput,
cb: (err: any, data?: DescribeSecretCommandOutput) => void
): void;
public describeSecret(
args: DescribeSecretCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeSecretCommandOutput) => void
): void;
public describeSecret(
args: DescribeSecretCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeSecretCommandOutput) => void),
cb?: (err: any, data?: DescribeSecretCommandOutput) => void
): Promise<DescribeSecretCommandOutput> | void {
const command = new DescribeSecretCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Generates a random password of the specified complexity. This operation is intended for
* use in the Lambda rotation function. Per best practice, we recommend that you specify the
* maximum length and include every character type that the system you are generating a password
* for can support.</p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:GetRandomPassword</p>
* </li>
* </ul>
*/
public getRandomPassword(
args: GetRandomPasswordCommandInput,
options?: __HttpHandlerOptions
): Promise<GetRandomPasswordCommandOutput>;
public getRandomPassword(
args: GetRandomPasswordCommandInput,
cb: (err: any, data?: GetRandomPasswordCommandOutput) => void
): void;
public getRandomPassword(
args: GetRandomPasswordCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetRandomPasswordCommandOutput) => void
): void;
public getRandomPassword(
args: GetRandomPasswordCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetRandomPasswordCommandOutput) => void),
cb?: (err: any, data?: GetRandomPasswordCommandOutput) => void
): Promise<GetRandomPasswordCommandOutput> | void {
const command = new GetRandomPasswordCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the JSON text of the resource-based policy document attached to the specified
* secret. The JSON request string input and response output displays formatted code
* with white space and line breaks for better readability. Submit your input as a single line
* JSON string.</p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:GetResourcePolicy</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To attach a resource policy to a secret, use <a>PutResourcePolicy</a>.</p>
* </li>
* <li>
* <p>To delete the resource-based policy attached to a secret, use <a>DeleteResourcePolicy</a>.</p>
* </li>
* <li>
* <p>To list all of the currently available secrets, use <a>ListSecrets</a>.</p>
* </li>
* </ul>
*/
public getResourcePolicy(
args: GetResourcePolicyCommandInput,
options?: __HttpHandlerOptions
): Promise<GetResourcePolicyCommandOutput>;
public getResourcePolicy(
args: GetResourcePolicyCommandInput,
cb: (err: any, data?: GetResourcePolicyCommandOutput) => void
): void;
public getResourcePolicy(
args: GetResourcePolicyCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetResourcePolicyCommandOutput) => void
): void;
public getResourcePolicy(
args: GetResourcePolicyCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetResourcePolicyCommandOutput) => void),
cb?: (err: any, data?: GetResourcePolicyCommandOutput) => void
): Promise<GetResourcePolicyCommandOutput> | void {
const command = new GetResourcePolicyCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the contents of the encrypted fields <code>SecretString</code> or
* <code>SecretBinary</code> from the specified version of a secret, whichever contains
* content.</p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:GetSecretValue</p>
* </li>
* <li>
* <p>kms:Decrypt - required only if you use a customer-managed Amazon Web Services KMS key to encrypt the
* secret. You do not need this permission to use the account's default Amazon Web Services managed CMK for
* Secrets Manager.</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To create a new version of the secret with different encrypted information, use <a>PutSecretValue</a>.</p>
* </li>
* <li>
* <p>To retrieve the non-encrypted details for the secret, use <a>DescribeSecret</a>.</p>
* </li>
* </ul>
*/
public getSecretValue(
args: GetSecretValueCommandInput,
options?: __HttpHandlerOptions
): Promise<GetSecretValueCommandOutput>;
public getSecretValue(
args: GetSecretValueCommandInput,
cb: (err: any, data?: GetSecretValueCommandOutput) => void
): void;
public getSecretValue(
args: GetSecretValueCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetSecretValueCommandOutput) => void
): void;
public getSecretValue(
args: GetSecretValueCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSecretValueCommandOutput) => void),
cb?: (err: any, data?: GetSecretValueCommandOutput) => void
): Promise<GetSecretValueCommandOutput> | void {
const command = new GetSecretValueCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists all of the secrets that are stored by Secrets Manager in the Amazon Web Services account. To list the
* versions currently stored for a specific secret, use <a>ListSecretVersionIds</a>.
* The encrypted fields <code>SecretString</code> and <code>SecretBinary</code> are not included
* in the output. To get that information, call the <a>GetSecretValue</a>
* operation.</p>
* <note>
* <p>Always check the <code>NextToken</code> response parameter
* when calling any of the <code>List*</code> operations. These operations can occasionally return
* an empty or shorter than expected list of results even when there more results become available.
* When this happens, the <code>NextToken</code> response parameter contains a value to pass to the
* next call to the same API to request the next part of the list.</p>
* </note>
* <p>
* <b>Minimum
* permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:ListSecrets</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To list the versions attached to a secret, use <a>ListSecretVersionIds</a>.</p>
* </li>
* </ul>
*/
public listSecrets(args: ListSecretsCommandInput, options?: __HttpHandlerOptions): Promise<ListSecretsCommandOutput>;
public listSecrets(args: ListSecretsCommandInput, cb: (err: any, data?: ListSecretsCommandOutput) => void): void;
public listSecrets(
args: ListSecretsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListSecretsCommandOutput) => void
): void;
public listSecrets(
args: ListSecretsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListSecretsCommandOutput) => void),
cb?: (err: any, data?: ListSecretsCommandOutput) => void
): Promise<ListSecretsCommandOutput> | void {
const command = new ListSecretsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists all of the versions attached to the specified secret. The output does not include
* the <code>SecretString</code> or <code>SecretBinary</code> fields. By default, the list
* includes only versions that have at least one staging label in <code>VersionStage</code>
* attached.</p>
* <note>
* <p>Always check the <code>NextToken</code> response parameter
* when calling any of the <code>List*</code> operations. These operations can occasionally return
* an empty or shorter than expected list of results even when there more results become available.
* When this happens, the <code>NextToken</code> response parameter contains a value to pass to the
* next call to the same API to request the next part of the list.</p>
* </note>
* <p>
* <b>Minimum
* permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:ListSecretVersionIds</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To list the secrets in an account, use <a>ListSecrets</a>.</p>
* </li>
* </ul>
*/
public listSecretVersionIds(
args: ListSecretVersionIdsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListSecretVersionIdsCommandOutput>;
public listSecretVersionIds(
args: ListSecretVersionIdsCommandInput,
cb: (err: any, data?: ListSecretVersionIdsCommandOutput) => void
): void;
public listSecretVersionIds(
args: ListSecretVersionIdsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListSecretVersionIdsCommandOutput) => void
): void;
public listSecretVersionIds(
args: ListSecretVersionIdsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListSecretVersionIdsCommandOutput) => void),
cb?: (err: any, data?: ListSecretVersionIdsCommandOutput) => void
): Promise<ListSecretVersionIdsCommandOutput> | void {
const command = new ListSecretVersionIdsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Attaches the contents of the specified resource-based permission policy to a secret. A
* resource-based policy is optional. Alternatively, you can use IAM identity-based policies
* that specify the secret's Amazon Resource Name (ARN) in the policy statement's
* <code>Resources</code> element. You can also use a combination of both identity-based and
* resource-based policies. The affected users and roles receive the permissions that are
* permitted by all of the relevant policies. For more information, see <a href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_resource-based-policies.html">Using Resource-Based
* Policies for Amazon Web Services Secrets Manager</a>. For the complete description of the Amazon Web Services policy syntax and
* grammar, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html">IAM JSON
* Policy Reference</a> in the <i>IAM User Guide</i>.</p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:PutResourcePolicy</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To retrieve the resource policy attached to a secret, use <a>GetResourcePolicy</a>.</p>
* </li>
* <li>
* <p>To delete the resource-based policy attached to a secret, use <a>DeleteResourcePolicy</a>.</p>
* </li>
* <li>
* <p>To list all of the currently available secrets, use <a>ListSecrets</a>.</p>
* </li>
* </ul>
*/
public putResourcePolicy(
args: PutResourcePolicyCommandInput,
options?: __HttpHandlerOptions
): Promise<PutResourcePolicyCommandOutput>;
public putResourcePolicy(
args: PutResourcePolicyCommandInput,
cb: (err: any, data?: PutResourcePolicyCommandOutput) => void
): void;
public putResourcePolicy(
args: PutResourcePolicyCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutResourcePolicyCommandOutput) => void
): void;
public putResourcePolicy(
args: PutResourcePolicyCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutResourcePolicyCommandOutput) => void),
cb?: (err: any, data?: PutResourcePolicyCommandOutput) => void
): Promise<PutResourcePolicyCommandOutput> | void {
const command = new PutResourcePolicyCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Stores a new encrypted secret value in the specified secret. To do this, the operation
* creates a new version and attaches it to the secret. The version can contain a new
* <code>SecretString</code> value or a new <code>SecretBinary</code> value. You can also
* specify the staging labels that are initially attached to the new version.</p>
* <p>We recommend you avoid calling <code>PutSecretValue</code> at a sustained rate of more than
* once every 10 minutes. When you update the secret value, Secrets Manager creates a new version
* of the secret. Secrets Manager removes outdated versions when there are more than 100, but it does not
* remove versions created less than 24 hours ago. If you call <code>PutSecretValue</code> more
* than once every 10 minutes, you create more versions than Secrets Manager removes, and you will reach
* the quota for secret versions.</p>
* <ul>
* <li>
* <p>If this operation creates the first version for the secret then Secrets Manager
* automatically attaches the staging label <code>AWSCURRENT</code> to the new version.</p>
* </li>
* <li>
* <p>If you do not specify a value for VersionStages then Secrets Manager automatically
* moves the staging label <code>AWSCURRENT</code> to this new version.</p>
* </li>
* <li>
* <p>If this operation moves the staging label <code>AWSCURRENT</code> from another version to this
* version, then Secrets Manager also automatically moves the staging label <code>AWSPREVIOUS</code> to
* the version that <code>AWSCURRENT</code> was removed from.</p>
* </li>
* <li>
* <p>This operation is idempotent. If a version with a <code>VersionId</code> with the same
* value as the <code>ClientRequestToken</code> parameter already exists and you specify the
* same secret data, the operation succeeds but does nothing. However, if the secret data is
* different, then the operation fails because you cannot modify an existing version; you can
* only create new ones.</p>
* </li>
* </ul>
* <note>
* <ul>
* <li>
* <p>If you call an operation to encrypt or decrypt the <code>SecretString</code>
* or <code>SecretBinary</code> for a secret in the same account as the calling user and that
* secret doesn't specify a Amazon Web Services KMS encryption key, Secrets Manager uses the account's default
* Amazon Web Services managed customer master key (CMK) with the alias <code>aws/secretsmanager</code>. If this key
* doesn't already exist in your account then Secrets Manager creates it for you automatically. All
* users and roles in the same Amazon Web Services account automatically have access to use the default CMK.
* Note that if an Secrets Manager API call results in Amazon Web Services creating the account's
* Amazon Web Services-managed CMK, it can result in a one-time significant delay in returning the
* result.</p>
* </li>
* <li>
* <p>If the secret resides in a different Amazon Web Services account from the credentials calling an API that
* requires encryption or decryption of the secret value then you must create and use a custom
* Amazon Web Services KMS CMK because you can't access the default CMK for the account using credentials
* from a different Amazon Web Services account. Store the ARN of the CMK in the secret when you create the
* secret or when you update it by including it in the <code>KMSKeyId</code>. If you call an
* API that must encrypt or decrypt <code>SecretString</code> or <code>SecretBinary</code>
* using credentials from a different account then the Amazon Web Services KMS key policy must grant cross-account
* access to that other account's user or role for both the kms:GenerateDataKey and
* kms:Decrypt operations.</p>
* </li>
* </ul>
* </note>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:PutSecretValue</p>
* </li>
* <li>
* <p>kms:GenerateDataKey - needed only if you use a customer-managed Amazon Web Services KMS key to encrypt
* the secret. You do not need this permission to use the account's default Amazon Web Services managed CMK
* for Secrets Manager.</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To retrieve the encrypted value you store in the version of a secret, use <a>GetSecretValue</a>.</p>
* </li>
* <li>
* <p>To create a secret, use <a>CreateSecret</a>.</p>
* </li>
* <li>
* <p>To get the details for a secret, use <a>DescribeSecret</a>.</p>
* </li>
* <li>
* <p>To list the versions attached to a secret, use <a>ListSecretVersionIds</a>.</p>
* </li>
* </ul>
*/
public putSecretValue(
args: PutSecretValueCommandInput,
options?: __HttpHandlerOptions
): Promise<PutSecretValueCommandOutput>;
public putSecretValue(
args: PutSecretValueCommandInput,
cb: (err: any, data?: PutSecretValueCommandOutput) => void
): void;
public putSecretValue(
args: PutSecretValueCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutSecretValueCommandOutput) => void
): void;
public putSecretValue(
args: PutSecretValueCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutSecretValueCommandOutput) => void),
cb?: (err: any, data?: PutSecretValueCommandOutput) => void
): Promise<PutSecretValueCommandOutput> | void {
const command = new PutSecretValueCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Remove regions from replication.</p>
*/
public removeRegionsFromReplication(
args: RemoveRegionsFromReplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<RemoveRegionsFromReplicationCommandOutput>;
public removeRegionsFromReplication(
args: RemoveRegionsFromReplicationCommandInput,
cb: (err: any, data?: RemoveRegionsFromReplicationCommandOutput) => void
): void;
public removeRegionsFromReplication(
args: RemoveRegionsFromReplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RemoveRegionsFromReplicationCommandOutput) => void
): void;
public removeRegionsFromReplication(
args: RemoveRegionsFromReplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveRegionsFromReplicationCommandOutput) => void),
cb?: (err: any, data?: RemoveRegionsFromReplicationCommandOutput) => void
): Promise<RemoveRegionsFromReplicationCommandOutput> | void {
const command = new RemoveRegionsFromReplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Converts an existing secret to a multi-Region secret and begins replication the secret to a
* list of new regions. </p>
*/
public replicateSecretToRegions(
args: ReplicateSecretToRegionsCommandInput,
options?: __HttpHandlerOptions
): Promise<ReplicateSecretToRegionsCommandOutput>;
public replicateSecretToRegions(
args: ReplicateSecretToRegionsCommandInput,
cb: (err: any, data?: ReplicateSecretToRegionsCommandOutput) => void
): void;
public replicateSecretToRegions(
args: ReplicateSecretToRegionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ReplicateSecretToRegionsCommandOutput) => void
): void;
public replicateSecretToRegions(
args: ReplicateSecretToRegionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ReplicateSecretToRegionsCommandOutput) => void),
cb?: (err: any, data?: ReplicateSecretToRegionsCommandOutput) => void
): Promise<ReplicateSecretToRegionsCommandOutput> | void {
const command = new ReplicateSecretToRegionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Cancels the scheduled deletion of a secret by removing the <code>DeletedDate</code> time
* stamp. This makes the secret accessible to query once again.</p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:RestoreSecret</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To delete a secret, use <a>DeleteSecret</a>.</p>
* </li>
* </ul>
*/
public restoreSecret(
args: RestoreSecretCommandInput,
options?: __HttpHandlerOptions
): Promise<RestoreSecretCommandOutput>;
public restoreSecret(
args: RestoreSecretCommandInput,
cb: (err: any, data?: RestoreSecretCommandOutput) => void
): void;
public restoreSecret(
args: RestoreSecretCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RestoreSecretCommandOutput) => void
): void;
public restoreSecret(
args: RestoreSecretCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RestoreSecretCommandOutput) => void),
cb?: (err: any, data?: RestoreSecretCommandOutput) => void
): Promise<RestoreSecretCommandOutput> | void {
const command = new RestoreSecretCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Configures and starts the asynchronous process of rotating this secret. If you include the
* configuration parameters, the operation sets those values for the secret and then immediately
* starts a rotation. If you do not include the configuration parameters, the operation starts a
* rotation with the values already stored in the secret. After the rotation completes, the
* protected service and its clients all use the new version of the secret. </p>
* <p>This required configuration information includes the ARN of an Amazon Web Services Lambda function and
* optionally, the time between scheduled rotations. The Lambda rotation function creates a new
* version of the secret and creates or updates the credentials on the protected service to
* match. After testing the new credentials, the function marks the new secret with the staging
* label <code>AWSCURRENT</code> so that your clients all immediately begin to use the new version. For more
* information about rotating secrets and how to configure a Lambda function to rotate the
* secrets for your protected service, see <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html">Rotating Secrets in Amazon Web Services Secrets Manager</a> in the
* <i>Amazon Web Services Secrets Manager User Guide</i>.</p>
* <p>Secrets Manager schedules the next rotation when the previous
* one completes. Secrets Manager schedules the date by adding the rotation interval (number of days) to the
* actual date of the last rotation. The service chooses the hour within that 24-hour date window
* randomly. The minute is also chosen somewhat randomly, but weighted towards the top of the hour
* and influenced by a variety of factors that help distribute load.</p>
* <p>The
* rotation function must end with the versions of the secret in one of two states:</p>
* <ul>
* <li>
* <p>The <code>AWSPENDING</code> and <code>AWSCURRENT</code> staging labels are attached to the same version of
* the secret, or</p>
* </li>
* <li>
* <p>The <code>AWSPENDING</code> staging label is not attached to any version of the secret.</p>
* </li>
* </ul>
* <p>If the <code>AWSPENDING</code> staging label is present but not attached to the same version as
* <code>AWSCURRENT</code> then any later invocation of <code>RotateSecret</code> assumes that a previous
* rotation request is still in progress and returns an error.</p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:RotateSecret</p>
* </li>
* <li>
* <p>lambda:InvokeFunction (on the function specified in the secret's metadata)</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To list the secrets in your account, use <a>ListSecrets</a>.</p>
* </li>
* <li>
* <p>To get the details for a version of a secret, use <a>DescribeSecret</a>.</p>
* </li>
* <li>
* <p>To create a new version of a secret, use <a>CreateSecret</a>.</p>
* </li>
* <li>
* <p>To attach staging labels to or remove staging labels from a version of a secret, use
* <a>UpdateSecretVersionStage</a>.</p>
* </li>
* </ul>
*/
public rotateSecret(
args: RotateSecretCommandInput,
options?: __HttpHandlerOptions
): Promise<RotateSecretCommandOutput>;
public rotateSecret(args: RotateSecretCommandInput, cb: (err: any, data?: RotateSecretCommandOutput) => void): void;
public rotateSecret(
args: RotateSecretCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RotateSecretCommandOutput) => void
): void;
public rotateSecret(
args: RotateSecretCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RotateSecretCommandOutput) => void),
cb?: (err: any, data?: RotateSecretCommandOutput) => void
): Promise<RotateSecretCommandOutput> | void {
const command = new RotateSecretCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes the secret from replication and promotes the secret to a regional secret in the replica Region.</p>
*/
public stopReplicationToReplica(
args: StopReplicationToReplicaCommandInput,
options?: __HttpHandlerOptions
): Promise<StopReplicationToReplicaCommandOutput>;
public stopReplicationToReplica(
args: StopReplicationToReplicaCommandInput,
cb: (err: any, data?: StopReplicationToReplicaCommandOutput) => void
): void;
public stopReplicationToReplica(
args: StopReplicationToReplicaCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StopReplicationToReplicaCommandOutput) => void
): void;
public stopReplicationToReplica(
args: StopReplicationToReplicaCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StopReplicationToReplicaCommandOutput) => void),
cb?: (err: any, data?: StopReplicationToReplicaCommandOutput) => void
): Promise<StopReplicationToReplicaCommandOutput> | void {
const command = new StopReplicationToReplicaCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Attaches one or more tags, each consisting of a key name and a value, to the specified
* secret. Tags are part of the secret's overall metadata, and are not associated with any
* specific version of the secret. This operation only appends tags to the existing list of tags.
* To remove tags, you must use <a>UntagResource</a>.</p>
* <p>The following basic restrictions apply to tags:</p>
* <ul>
* <li>
* <p>Maximum number of tags per secret—50</p>
* </li>
* <li>
* <p>Maximum key length—127 Unicode characters in UTF-8</p>
* </li>
* <li>
* <p>Maximum value length—255 Unicode characters in UTF-8</p>
* </li>
* <li>
* <p>Tag keys and values are case sensitive.</p>
* </li>
* <li>
* <p>Do not use the <code>aws:</code> prefix in your tag names or values because Amazon Web Services reserves it
* for Amazon Web Services use. You can't edit or delete tag names or values with this
* prefix. Tags with this prefix do not count against your tags per secret limit.</p>
* </li>
* <li>
* <p>If you use your tagging schema across multiple services and resources,
* remember other services might have restrictions on allowed characters. Generally
* allowed characters: letters, spaces, and numbers representable in UTF-8, plus the
* following special characters: + - = . _ : / @.</p>
* </li>
* </ul>
* <important>
* <p>If you use tags as part of your security strategy, then adding or removing a tag can
* change permissions. If successfully completing this operation would result in you losing
* your permissions for this secret, then the operation is blocked and returns an Access Denied
* error.</p>
* </important>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:TagResource</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To remove one or more tags from the collection attached to a secret, use <a>UntagResource</a>.</p>
* </li>
* <li>
* <p>To view the list of tags attached to a secret, use <a>DescribeSecret</a>.</p>
* </li>
* </ul>
*/
public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>;
public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void;
public tagResource(
args: TagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TagResourceCommandOutput) => void
): void;
public tagResource(
args: TagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void),
cb?: (err: any, data?: TagResourceCommandOutput) => void
): Promise<TagResourceCommandOutput> | void {
const command = new TagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes one or more tags from the specified secret.</p>
* <p>This operation is idempotent. If a requested tag is not attached to the secret, no error
* is returned and the secret metadata is unchanged.</p>
* <important>
* <p>If you use tags as part of your security strategy, then removing a tag can change
* permissions. If successfully completing this operation would result in you losing your
* permissions for this secret, then the operation is blocked and returns an Access Denied
* error.</p>
* </important>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:UntagResource</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To add one or more tags to the collection attached to a secret, use <a>TagResource</a>.</p>
* </li>
* <li>
* <p>To view the list of tags attached to a secret, use <a>DescribeSecret</a>.</p>
* </li>
* </ul>
*/
public untagResource(
args: UntagResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UntagResourceCommandOutput>;
public untagResource(
args: UntagResourceCommandInput,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void),
cb?: (err: any, data?: UntagResourceCommandOutput) => void
): Promise<UntagResourceCommandOutput> | void {
const command = new UntagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Modifies many of the details of the specified secret. </p>
* <p>To change the secret value, you can also use <a>PutSecretValue</a>.</p>
* <p>To change the rotation configuration of a secret, use <a>RotateSecret</a>
* instead.</p>
*
* <p>We recommend you avoid calling <code>UpdateSecret</code> at a sustained rate of more than
* once every 10 minutes. When you call <code>UpdateSecret</code> to update the secret value, Secrets Manager creates a new version
* of the secret. Secrets Manager removes outdated versions when there are more than 100, but it does not
* remove versions created less than 24 hours ago. If you update the secret value more
* than once every 10 minutes, you create more versions than Secrets Manager removes, and you will reach
* the quota for secret versions.</p>
* <note>
* <p>The Secrets Manager console uses only the <code>SecretString</code> parameter and therefore limits
* you to encrypting and storing only a text string. To encrypt and store binary data as part
* of the version of a secret, you must use either the Amazon Web Services CLI or one of the Amazon Web Services
* SDKs.</p>
* </note>
* <ul>
* <li>
* <p>If a version with a <code>VersionId</code> with the same value as the
* <code>ClientRequestToken</code> parameter already exists, the operation results in an
* error. You cannot modify an existing version, you can only create a new version.</p>
* </li>
* <li>
* <p>If you include <code>SecretString</code> or <code>SecretBinary</code> to create a new
* secret version, Secrets Manager automatically attaches the staging label <code>AWSCURRENT</code> to the new
* version. </p>
* </li>
* </ul>
* <note>
* <ul>
* <li>
* <p>If you call an operation to encrypt or decrypt the <code>SecretString</code>
* or <code>SecretBinary</code> for a secret in the same account as the calling user and that
* secret doesn't specify a Amazon Web Services KMS encryption key, Secrets Manager uses the account's default
* Amazon Web Services managed customer master key (CMK) with the alias <code>aws/secretsmanager</code>. If this key
* doesn't already exist in your account then Secrets Manager creates it for you automatically. All
* users and roles in the same Amazon Web Services account automatically have access to use the default CMK.
* Note that if an Secrets Manager API call results in Amazon Web Services creating the account's
* Amazon Web Services-managed CMK, it can result in a one-time significant delay in returning the
* result.</p>
* </li>
* <li>
* <p>If the secret resides in a different Amazon Web Services account from the credentials calling an API that
* requires encryption or decryption of the secret value then you must create and use a custom
* Amazon Web Services KMS CMK because you can't access the default CMK for the account using credentials
* from a different Amazon Web Services account. Store the ARN of the CMK in the secret when you create the
* secret or when you update it by including it in the <code>KMSKeyId</code>. If you call an
* API that must encrypt or decrypt <code>SecretString</code> or <code>SecretBinary</code>
* using credentials from a different account then the Amazon Web Services KMS key policy must grant cross-account
* access to that other account's user or role for both the kms:GenerateDataKey and
* kms:Decrypt operations.</p>
* </li>
* </ul>
* </note>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:UpdateSecret</p>
* </li>
* <li>
* <p>kms:GenerateDataKey - needed only if you use a custom Amazon Web Services KMS key to encrypt the secret.
* You do not need this permission to use the account's Amazon Web Services managed CMK for
* Secrets Manager.</p>
* </li>
* <li>
* <p>kms:Decrypt - needed only if you use a custom Amazon Web Services KMS key to encrypt the secret. You do
* not need this permission to use the account's Amazon Web Services managed CMK for Secrets Manager.</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To create a new secret, use <a>CreateSecret</a>.</p>
* </li>
* <li>
* <p>To add only a new version to an existing secret, use <a>PutSecretValue</a>.</p>
* </li>
* <li>
* <p>To get the details for a secret, use <a>DescribeSecret</a>.</p>
* </li>
* <li>
* <p>To list the versions contained in a secret, use <a>ListSecretVersionIds</a>.</p>
* </li>
* </ul>
*/
public updateSecret(
args: UpdateSecretCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateSecretCommandOutput>;
public updateSecret(args: UpdateSecretCommandInput, cb: (err: any, data?: UpdateSecretCommandOutput) => void): void;
public updateSecret(
args: UpdateSecretCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateSecretCommandOutput) => void
): void;
public updateSecret(
args: UpdateSecretCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateSecretCommandOutput) => void),
cb?: (err: any, data?: UpdateSecretCommandOutput) => void
): Promise<UpdateSecretCommandOutput> | void {
const command = new UpdateSecretCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Modifies the staging labels attached to a version of a secret. Staging labels are used to
* track a version as it progresses through the secret rotation process. You can attach a staging
* label to only one version of a secret at a time. If a staging label to be added is already
* attached to another version, then it is moved--removed from the other version first and
* then attached to this one. For more information about staging labels, see <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/terms-concepts.html#term_staging-label">Staging
* Labels</a> in the <i>Amazon Web Services Secrets Manager User Guide</i>. </p>
* <p>The staging labels that you specify in the <code>VersionStage</code> parameter are added
* to the existing list of staging labels--they don't replace it.</p>
* <p>You can move the <code>AWSCURRENT</code> staging label to this version by including it in this
* call.</p>
* <note>
* <p>Whenever you move <code>AWSCURRENT</code>, Secrets Manager automatically moves the label <code>AWSPREVIOUS</code>
* to the version that <code>AWSCURRENT</code> was removed from.</p>
* </note>
* <p>If this action results in the last label being removed from a version, then the version is
* considered to be 'deprecated' and can be deleted by Secrets Manager.</p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>To run this command, you must have the following permissions:</p>
* <ul>
* <li>
* <p>secretsmanager:UpdateSecretVersionStage</p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>To get the list of staging labels that are currently associated with a version of a
* secret, use <code>
* <a>DescribeSecret</a>
* </code> and examine the
* <code>SecretVersionsToStages</code> response value. </p>
* </li>
* </ul>
*/
public updateSecretVersionStage(
args: UpdateSecretVersionStageCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateSecretVersionStageCommandOutput>;
public updateSecretVersionStage(
args: UpdateSecretVersionStageCommandInput,
cb: (err: any, data?: UpdateSecretVersionStageCommandOutput) => void
): void;
public updateSecretVersionStage(
args: UpdateSecretVersionStageCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateSecretVersionStageCommandOutput) => void
): void;
public updateSecretVersionStage(
args: UpdateSecretVersionStageCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateSecretVersionStageCommandOutput) => void),
cb?: (err: any, data?: UpdateSecretVersionStageCommandOutput) => void
): Promise<UpdateSecretVersionStageCommandOutput> | void {
const command = new UpdateSecretVersionStageCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Validates that the resource policy does not grant a wide range of IAM principals access to
* your secret. The JSON request string input and response output displays formatted code
* with white space and line breaks for better readability. Submit your input as a single line
* JSON string. A resource-based policy is optional for secrets.</p>
* <p>The API performs three checks when validating the secret:</p>
* <ul>
* <li>
* <p>Sends a call to <a href="https://aws.amazon.com/blogs/security/protect-sensitive-data-in-the-cloud-with-automated-reasoning-zelkova/">Zelkova</a>, an automated reasoning engine, to ensure your Resource Policy does not
* allow broad access to your secret.</p>
* </li>
* <li>
* <p>Checks for correct syntax in a policy.</p>
* </li>
* <li>
* <p>Verifies the policy does not lock out a caller.</p>
* </li>
* </ul>
*
*
* <p>
* <b>Minimum Permissions</b>
* </p>
* <p>You must have the permissions required to access the following APIs:</p>
* <ul>
* <li>
* <p>
* <code>secretsmanager:PutResourcePolicy</code>
* </p>
* </li>
* <li>
* <p>
* <code>secretsmanager:ValidateResourcePolicy</code>
* </p>
* </li>
* </ul>
*/
public validateResourcePolicy(
args: ValidateResourcePolicyCommandInput,
options?: __HttpHandlerOptions
): Promise<ValidateResourcePolicyCommandOutput>;
public validateResourcePolicy(
args: ValidateResourcePolicyCommandInput,
cb: (err: any, data?: ValidateResourcePolicyCommandOutput) => void
): void;
public validateResourcePolicy(
args: ValidateResourcePolicyCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ValidateResourcePolicyCommandOutput) => void
): void;
public validateResourcePolicy(
args: ValidateResourcePolicyCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ValidateResourcePolicyCommandOutput) => void),
cb?: (err: any, data?: ValidateResourcePolicyCommandOutput) => void
): Promise<ValidateResourcePolicyCommandOutput> | void {
const command = new ValidateResourcePolicyCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
import { readFileSync } from 'fs';
import { Settings } from 'insomnia-common';
import { ErrorResult, INSOMNIA_CONFIG_FILENAME, InsomniaConfig, isErrorResult, validate } from 'insomnia-config';
import { resolve } from 'path';
import { mapObjIndexed, once } from 'ramda';
import { omitBy } from 'ramda-adjunct';
import { ValueOf } from 'type-fest';
import { isDevelopment } from '../../common/constants';
import { getDataDirectory, getPortableExecutableDir } from '../../common/electron-helpers';
interface FailedParseResult {
syntaxError: SyntaxError;
fileContents: string;
configPath: string;
}
const isFailedParseResult = (input: any): input is FailedParseResult => {
const typesafeInput = input as FailedParseResult;
return (
typesafeInput ? typesafeInput.syntaxError instanceof SyntaxError : false
);
};
/** takes an unresolved (or resolved will work fine too) filePath of the insomnia config and reads the insomniaConfig from disk */
export const readConfigFile = (configPath?: string): unknown | FailedParseResult | undefined => {
if (!configPath) {
return undefined;
}
let fileContents = '';
try {
fileContents = readFileSync(configPath, 'utf-8');
} catch (error: unknown) {
// file not found
return undefined;
}
const fileIsFoundButEmpty = fileContents === '';
if (fileIsFoundButEmpty) {
return undefined;
}
try {
return JSON.parse(fileContents) as unknown;
} catch (syntaxError: unknown) {
// note: all JSON.parse errors are SyntaxErrors
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse
if (syntaxError instanceof SyntaxError) {
console.error('failed to parse insomnia config', { configPath, fileContents, syntaxError });
const failedParseResult: FailedParseResult = {
syntaxError,
fileContents,
configPath: configPath,
};
return failedParseResult;
}
return undefined;
}
};
export const getLocalDevConfigFilePath = () => (
isDevelopment() ? '../../packages/insomnia/src' as string : undefined
);
const addConfigFileToPath = (path: string | undefined) => (
path ? resolve(path, INSOMNIA_CONFIG_FILENAME) : undefined
);
export const getConfigFile = () => {
const portableExecutable = getPortableExecutableDir();
const insomniaDataDirectory = getDataDirectory();
const localDev = getLocalDevConfigFilePath();
const configPaths = [
portableExecutable,
insomniaDataDirectory,
localDev,
].map(addConfigFileToPath);
// note: this is written as to avoid unnecessary (synchronous) reads from disk.
// The paths above are in priority order such that if we already found what we're looking for, there's no reason to keep reading other files.
for (const configPath of configPaths) {
const fileReadResult = readConfigFile(configPath);
if (isFailedParseResult(fileReadResult)) {
return fileReadResult;
}
if (fileReadResult !== undefined && configPath !== undefined) {
return {
insomniaConfig: fileReadResult,
configPath,
};
}
}
const fallbackEmptyConfig: InsomniaConfig = { insomniaConfig: '1.0.0' };
return {
insomniaConfig: fallbackEmptyConfig,
configPath: '<internal fallback insomnia config>',
};
};
export interface ConfigError {
error: {
configPath?: string;
insomniaConfig: unknown;
errors: ErrorResult['errors'];
humanReadableErrors: ErrorResult['humanReadableErrors'];
};
}
export const isConfigError = (input: ConfigError | ParseError): input is ConfigError => (
// Cast for typesafety
(input as ConfigError).error?.humanReadableErrors?.length > 0
);
export interface ParseError {
error: FailedParseResult;
}
export const isParseError = (input: ConfigError | ParseError): input is ParseError => (
isFailedParseResult(input.error)
);
/**
* gets settings from the `insomnia.config.json`
*
* note that it is a business rule that the config is never read again after startup, hence the `once` usage.
*/
export const getConfigSettings: () => (NonNullable<InsomniaConfig['settings']> | ConfigError | ParseError) = once(() => {
const configFileResult = getConfigFile();
if (isFailedParseResult(configFileResult)) {
return {
error: configFileResult,
};
}
const { insomniaConfig, configPath } = configFileResult;
const validationResult = validate(insomniaConfig as InsomniaConfig);
if (isErrorResult(validationResult)) {
const { errors, humanReadableErrors } = validationResult;
const error = {
configPath,
insomniaConfig,
errors,
humanReadableErrors,
};
console.error('invalid insomnia config', error);
return { error };
}
// This cast is important for testing intentionally bad values (the above validation will catch it, anyway)
return (insomniaConfig as InsomniaConfig).settings || {};
});
interface Condition {
/** note: conditions are only suitable for boolean settings at this time */
when: boolean;
set: Partial<Settings>;
}
// using a Map because they are ordered (in such case as multiple settings could be controlled by other multiple settings in the future, we could control this reliably by changing the order in the Map)
const settingControllers = new Map<keyof Settings, Condition[]>([
[
'incognitoMode',
[
{
when: true,
set: {
enableAnalytics: false,
allowNotificationRequests: false,
},
},
],
],
]);
/** checks whether a given setting is literally specified in the insomnia config */
export const isControlledByConfig = (setting: keyof Settings | null) => setting ? (
Boolean(Object.prototype.hasOwnProperty.call(getConfigSettings(), setting))
) : false;
export interface SettingControlledSetting<T extends keyof Settings> {
controlledValue: Settings[T];
controller: keyof Settings;
isControlled: true;
}
export interface ConfigControlledSetting<T extends keyof Settings> {
controlledValue: Settings[T];
controller: 'insomnia-config';
isControlled: true;
}
export interface UncontrolledSetting {
controller: null;
isControlled: false;
}
export type SettingsControl<T extends keyof Settings> =
| SettingControlledSetting<T>
| ConfigControlledSetting<T>
| UncontrolledSetting
;
const isSettingControlledByCondition = (condition: Condition, setting: keyof Settings, value: ValueOf<Settings>) => {
return condition.when === value
&& Object.prototype.hasOwnProperty.call(condition.set, setting);
};
/**
* checks whether a given setting is controlled by another setting.
* if so, it will return that setting id. otherwise it will return false.
*/
export const isControlledByAnotherSetting = (settings: Settings) => (setting: keyof Settings) => {
for (const [controller, controlledSettings] of settingControllers.entries()) {
for (const condition of controlledSettings) {
if (isSettingControlledByCondition(condition, setting, settings[controller])) {
const output: SettingControlledSetting<typeof setting> = {
controlledValue: condition.set[setting],
controller,
isControlled: true,
};
return output;
}
}
}
const uncontrolledSetting: UncontrolledSetting = {
controller: null,
isControlled: false,
};
return uncontrolledSetting;
};
/**
* For any given setting, return what the value of that setting should be once you take the insomnia config and other potentially controlling settings into account
*/
export const getControlledStatus = (userSettings: Settings) => (setting: keyof Settings) => {
const configSettings = {
...userSettings,
...getConfigSettings(),
};
if (isControlledByConfig(setting)) {
// note that the raw config settings are being passed here (rathern than `settings` alone), because we must verify that the controller does not itself also have a specification in the config
const controllerSetting = isControlledByAnotherSetting(configSettings)(setting);
// TLDR; the config always wins
// It is a business rule that if a setting (e.g. `incognitoMode` specified in the config controlls another setting (e.g. `enableAnalytics`), that conflict should be resolved such that the config-specified controller should _always_ win, _even_ if the controlled setting (i.e. `enableAnalytics`) is _itself_ specified in the config with a conflicting value)
if (controllerSetting.isControlled && isControlledByConfig(controllerSetting.controller)) {
// since this setting is also controlled by a controller, and that controller is controlled by the config, we use the controller's desired value for this setting.
return {
controller: controllerSetting.controller,
isControlled: true,
value: controllerSetting.controlledValue,
};
}
// no other setting controls this, so we can grab its value the config directly
return {
controller: 'insomnia-config',
isControlled: true,
value: configSettings[setting],
};
}
const thisSetting = isControlledByAnotherSetting(configSettings)(setting);
if (thisSetting.isControlled) {
// this setting is controlled by another setting.
return {
controller: thisSetting.controller,
isControlled: true,
value: thisSetting.controlledValue,
};
}
// return the object unchanged, as it exists in the settings
return {
controller: null,
isControlled: false,
value: userSettings[setting],
};
};
/** removes any setting in the given patch object which is controlled in any way (i.e. either by the insomnia config or by another setting) */
export const omitControlledSettings = <
T extends Settings,
U extends Partial<Settings>
>(settings: T, patch: U) => {
return omitBy((_value, setting: keyof Settings) => (
getControlledStatus(settings)(setting).isControlled
), patch);
};
/** for any given setting, whether controlled by the insomnia config or whether controlled by another value, return the calculated value */
export const getMonkeyPatchedControlledSettings = <T extends Settings>(settings: T) => {
const override = mapObjIndexed((_value, setting: keyof Settings) => (
getControlledStatus(settings)(setting).value
), settings) as T;
return {
...settings,
...override,
};
}; | the_stack |
import { DataManager, Query, Deferred, ReturnOption, QueryOptions } from '@syncfusion/ej2-data';
import { Workbook, getCell, CellModel, RowModel, SheetModel, setCell, getSheetIndexFromId } from '../base/index';
import { getRangeIndexes, checkIsFormula, updateSheetFromDataSource, checkDateFormat, dataSourceChanged } from '../common/index';
import { ExtendedSheet, ExtendedRange, AutoDetectInfo, getCellIndexes, dataChanged, getCellAddress, isInRange } from '../common/index';
import { triggerDataChange } from '../common/index';
import { getFormatFromType } from './number-format';
/**
* Data binding module
*/
export class DataBind {
private parent: Workbook;
private requestedInfo: RequestedInfo[];
constructor(parent: Workbook) {
this.parent = parent;
this.requestedInfo = [];
this.addEventListener();
}
private addEventListener(): void {
this.parent.on(updateSheetFromDataSource, this.updateSheetFromDataSourceHandler, this);
this.parent.on(dataSourceChanged, this.dataSourceChangedHandler, this);
this.parent.on(dataChanged, this.dataChangedHandler, this);
this.parent.on(triggerDataChange, this.triggerDataChangeHandler, this);
}
private removeEventListener(): void {
if (!this.parent.isDestroyed) {
this.parent.off(updateSheetFromDataSource, this.updateSheetFromDataSourceHandler);
this.parent.off(dataSourceChanged, this.dataSourceChangedHandler);
this.parent.off(dataChanged, this.dataChangedHandler);
this.parent.off(triggerDataChange, this.triggerDataChangeHandler);
}
}
/**
* Update given data source to sheet.
*
* @param {Object} args - Specify the args.
* @param {ExtendedSheet} args.sheet - Specify the sheet.
* @param {number[]} args.indexes - Specify the indexes.
* @param {Promise<CellModel>} args.promise - Specify the promise.
* @param {number} args.rangeSettingCount - Specify the rangeSettingCount.
* @returns {void} - Update given data source to sheet.
*/
// eslint-disable-next-line
private updateSheetFromDataSourceHandler(
args: { sheet: ExtendedSheet, indexes: number[], promise: Promise<CellModel>, rangeSettingCount?: number[], formulaCellRef?: string,
sheetIndex?: number, dataSourceChange?: boolean, isFinite?: boolean }): void {
let cell: CellModel; let flds: string[]; let sCellIdx: number[];
let result: Object[]; let remoteUrl: string; let isLocal: boolean; let dataManager: DataManager;
const requestedRange: boolean[] = []; const sRanges: number[] = []; let rowIdx: number;
const deferred: Deferred = new Deferred(); let sRowIdx: number; let sColIdx: number;
let loadedInfo: { isNotLoaded: boolean, unloadedRange: number[] };
args.promise = deferred.promise;
if (args.sheet && args.sheet.ranges.length) {
for (let k: number = args.sheet.ranges.length - 1; k >= 0; k--) {
let sRange: number = args.indexes[0]; let eRange: number = args.indexes[2];
const range: ExtendedRange = args.sheet.ranges[k];
sRowIdx = getRangeIndexes(range.startCell)[0];
dataManager = range.dataSource instanceof DataManager ? range.dataSource as DataManager
: range.dataSource ? new DataManager(range.dataSource) : new DataManager();
remoteUrl = remoteUrl || dataManager.dataSource.url; args.sheet.isLocalData = isLocal || !dataManager.dataSource.url;
if (sRowIdx <= sRange) {
sRange = sRange - sRowIdx;
} else {
if (sRowIdx <= eRange) {
eRange = eRange - sRowIdx; sRange = 0;
} else { sRange = -1; }
}
if (range.showFieldAsHeader && sRange !== 0) {
sRange -= 1;
}
let isEndReached: boolean = false; let insertRowCount: number = 0;
this.initRangeInfo(range);
let count: number = this.getMaxCount(range);
loadedInfo = this.getLoadedInfo(sRange, eRange, range);
sRange = loadedInfo.unloadedRange[0]; eRange = loadedInfo.unloadedRange[1];
if (range.info.insertRowRange) {
range.info.insertRowRange.forEach((range: number[]): void => {
insertRowCount += ((range[1] - range[0]) + 1);
});
sRange -= insertRowCount; eRange -= insertRowCount;
}
if (sRange > count) {
isEndReached = true;
} else if (eRange > count) {
eRange = count;
}
this.requestedInfo.push({ deferred: deferred, indexes: args.indexes, isNotLoaded: loadedInfo.isNotLoaded });
if (sRange >= 0 && loadedInfo.isNotLoaded && !isEndReached) {
sRanges[k] = sRange; requestedRange[k] = false;
const query: Query = (range.query ? range.query : new Query()).clone();
dataManager.executeQuery(query.range(sRange, eRange >= count ? eRange : eRange + 1)
.requiresCount()).then((e: ReturnOption) => {
if (!this.parent || this.parent.isDestroyed) { return; }
result = (e.result && e.result.result ? e.result.result : e.result) as Object[];
sCellIdx = getRangeIndexes(range.startCell);
sRowIdx = sCellIdx[0]; sColIdx = sCellIdx[1];
if (result && result.length) {
if (!range.info.count) { count = e.count; range.info.count = e.count; }
flds = Object.keys(result[0]);
if (!range.info.fldLen) { range.info.fldLen = flds.length; range.info.flds = flds; }
if (range.info.insertColumnRange) {
let insertCount: number = 0;
range.info.insertColumnRange.forEach((insertRange: number[]): void => {
for (let i: number = insertRange[0]; i <= insertRange[1]; i++) {
if (i <= sColIdx) {
flds.splice(0, 0, `emptyCell${insertCount}`);
} else {
flds.splice(
i - sColIdx, 0, `emptyCell${insertCount}`);
}
insertCount++;
}
});
}
if (sRanges[k] === 0 && range.showFieldAsHeader) {
rowIdx = sRowIdx + sRanges[k] + insertRowCount;
flds.forEach((field: string, i: number) => {
cell = getCell(rowIdx, sColIdx + i, args.sheet, true);
if (!cell) {
args.sheet.rows[sRowIdx + sRanges[k]].cells[sColIdx + i] = field.includes('emptyCell') ? {}
: { value: field };
} else if (!field.includes('emptyCell')) {
cell.value = field;
}
});
}
const curSheetIdx: number = args.formulaCellRef ? getSheetIndexFromId(this.parent, args.sheet.id) : undefined;
result.forEach((item: { [key: string]: string }, i: number) => {
rowIdx = sRowIdx + sRanges[k] + i + (range.showFieldAsHeader ? 1 : 0) + insertRowCount;
for (let j: number = 0; j < flds.length; j++) {
cell = getCell(rowIdx, sColIdx + j, args.sheet, true);
if (cell) {
if (!flds[j].includes('emptyCell')) {
setCell(rowIdx, sColIdx + j, args.sheet, this.getCellDataFromProp(item[flds[j]]), true);
}
} else {
args.sheet.rows[rowIdx].cells[sColIdx + j] =
flds[j].includes('emptyCell') ? {} : this.getCellDataFromProp(item[flds[j]]);
}
this.checkDataForFormat({
args: args, cell: cell, colIndex: sColIdx + j, rowIndex: rowIdx, i: i, j: j, k: k, range: range,
sRanges: sRanges, value: item[flds[j]], sheetIndex: curSheetIdx
});
}
});
} else {
flds = [];
}
const totalRows: number = (sRowIdx + (count || e.count) + (range.showFieldAsHeader ? 1 : 0) + insertRowCount) - 1;
const totalCols: number = sColIdx + flds.length - 1 < 0 ? args.sheet.usedRange.colIndex: sColIdx + flds.length - 1;
if (args.isFinite) {
args.sheet.usedRange.rowIndex = totalRows < args.sheet.rowCount ? totalRows : args.sheet.rowCount - 1;
args.sheet.usedRange.colIndex = totalCols < args.sheet.colCount ? totalCols : args.sheet.colCount - 1;
} else {
args.sheet.usedRange.rowIndex = totalRows;
args.sheet.usedRange.colIndex = totalCols;
}
if (insertRowCount) {
loadedInfo = this.getLoadedInfo(sRange, eRange, range);
sRange = loadedInfo.unloadedRange[0]; eRange = loadedInfo.unloadedRange[1];
if (sRange > count) {
loadedInfo.isNotLoaded = false;
}
if (loadedInfo.isNotLoaded) {
if (eRange > count) { eRange = count; }
range.info.loadedRange.push([sRange, eRange]);
}
} else {
range.info.loadedRange.push([sRange, eRange]);
}
requestedRange[k] = true;
if (requestedRange.indexOf(false) === -1) {
if (eRange + sRowIdx < sRowIdx + range.info.count) {
if (!args.rangeSettingCount) { args.rangeSettingCount = []; }
args.rangeSettingCount.push(k);
//if (remoteUrl) {
const unloadedArgs: { sheet: ExtendedSheet, indexes: number[], promise: Promise<CellModel>,
rangeSettingCount?: number[], isFinite?: boolean } = {
sheet: args.sheet, indexes: [0, 0, totalRows, totalCols],
// eslint-disable-next-line @typescript-eslint/no-unused-vars
promise: new Promise((resolve: Function, reject: Function) => { resolve((() => { /** */ })()); }),
rangeSettingCount: args.rangeSettingCount, isFinite: args.isFinite
};
this.updateSheetFromDataSourceHandler(unloadedArgs);
unloadedArgs.promise.then((): void => {
if (this.parent.getModuleName() === 'workbook') { return; }
args.rangeSettingCount.pop();
if (!args.rangeSettingCount.length) { this.parent.notify('created', null); }
if (args.formulaCellRef) {
this.notfyFormulaCellRefresh(args.formulaCellRef, args.sheetIndex);
}
});
//}
} else if (args.formulaCellRef) {
this.notfyFormulaCellRefresh(args.formulaCellRef, args.sheetIndex);
}
this.checkResolve(args.indexes);
}
});
} else if (k === 0 && requestedRange.indexOf(false) === -1) {
this.checkResolve(args.indexes);
}
}
} else { deferred.resolve(); }
}
private notfyFormulaCellRefresh(formulaCellRef: string, sheetIndex: number): void {
this.parent.formulaRefCell = null;
this.parent.notify('updateView', { indexes: getRangeIndexes(formulaCellRef), sheetIndex: sheetIndex, refreshing: true });
}
private checkResolve(indexes: number[]): void {
let resolved: boolean;
let isSameRng: boolean;
let cnt: number = 0;
this.requestedInfo.forEach((info: RequestedInfo, idx: number) => {
isSameRng = JSON.stringify(info.indexes) === JSON.stringify(indexes);
if (isSameRng || resolved) {
if (idx === 0) {
info.deferred.resolve();
cnt++;
resolved = true;
} else {
if (resolved && (info.isLoaded || !info.isNotLoaded)) {
info.deferred.resolve();
cnt++;
} else if (isSameRng && resolved) {
info.deferred.resolve();
cnt++;
} else if (isSameRng) {
info.isLoaded = true;
} else {
resolved = false;
}
}
}
});
this.requestedInfo.splice(0, cnt);
}
private getCellDataFromProp(prop: CellModel | string): CellModel {
const data: CellModel = {};
if (Object.prototype.toString.call(prop) === '[object Object]') {
if ((<CellModel>prop).formula) {
data.formula = (<CellModel>prop).formula;
} else if ((<CellModel>prop).value) {
if (typeof ((<CellModel>prop).value) === 'string') {
if ((<CellModel>prop).value.indexOf('http://') === 0 || (<CellModel>prop).value.indexOf('https://') === 0 ||
(<CellModel>prop).value.indexOf('ftp://') === 0 || (<CellModel>prop).value.indexOf('www.') === 0) {
data.hyperlink = (<CellModel>prop).value;
} else {
data.value = (<CellModel>prop).value;
}
} else {
data.value = (<CellModel>prop).value;
}
}
} else {
if (checkIsFormula(<string>prop)) {
data.formula = <string>prop;
} else {
if (typeof ((<string>prop)) === 'string') {
if ((<string>prop).indexOf('http://') === 0 || (<string>prop).indexOf('https://') === 0 ||
(<string>prop).indexOf('ftp://') === 0 || (<string>prop).indexOf('www.') === 0) {
data.hyperlink = <string>prop;
} else {
data.value = <string>prop;
}
} else {
data.value = <string>prop;
}
}
}
return data;
}
private checkDataForFormat(args: AutoDetectInfo): void {
if (args.value !== '') {
const dateEventArgs: { [key: string]: string | number | boolean } = {
value: args.value,
rowIndex: args.rowIndex,
colIndex: args.colIndex,
isDate: false,
updatedVal: args.value,
isTime: false,
sheetIndex: args.sheetIndex
};
this.parent.notify(checkDateFormat, dateEventArgs);
if (dateEventArgs.isDate) {
if (args.cell) {
if (!args.cell.format) { args.cell.format = getFormatFromType('ShortDate'); }
args.cell.value = <string>dateEventArgs.updatedVal;
} else {
args.args.sheet.rows[args.rowIndex]
.cells[args.colIndex].format = getFormatFromType('ShortDate');
args.args.sheet.rows[args.rowIndex]
.cells[args.colIndex].value = <string>dateEventArgs.updatedVal;
}
} else if (dateEventArgs.isTime) {
if (args.cell) {
if (!args.cell.format) { args.cell.format = getFormatFromType('Time'); }
args.cell.value = <string>dateEventArgs.updatedVal;
} else {
args.args.sheet.rows[args.rowIndex]
.cells[args.colIndex].format = getFormatFromType('Time');
args.args.sheet.rows[args.rowIndex]
.cells[args.colIndex].value = <string>dateEventArgs.updatedVal;
}
}
}
}
private getLoadedInfo(sRange: number, eRange: number, range: ExtendedRange): { isNotLoaded: boolean, unloadedRange: number[] } {
let isNotLoaded: boolean = true;
range.info.loadedRange.forEach((range: number[]) => {
if (range[0] <= sRange && sRange <= range[1]) {
if (range[0] <= eRange && eRange <= range[1]) {
isNotLoaded = false;
} else {
sRange = range[1] + 1;
}
} else if (range[0] <= eRange && eRange <= range[1]) {
eRange = range[0] - 1;
}
});
return { isNotLoaded: isNotLoaded, unloadedRange: [sRange, eRange] };
}
private getMaxCount(range: ExtendedRange): number {
if (range.query) {
const query: QueryOptions[] = range.query.queries;
for (let i: number = 0; i < query.length; i++) {
if (query[i].fn === 'onTake') {
return Math.min(query[i].e.nos, range.info.count || query[i].e.nos);
}
}
}
return range.info.count;
}
private initRangeInfo(range: ExtendedRange): void {
if (!range.info) {
range.info = { loadedRange: [] };
}
}
/**
* Remove old data from sheet.
*
* @param {Object} args - Specify the args.
* @param {Workbook} args.oldProp - Specify the oldProp.
* @param {string} args.sheetIdx - Specify the sheetIdx.
* @param {string} args.rangeIdx - Specify the rangeIdx.
* @param {boolean} args.isLastRange - Specify the isLastRange.
* @returns {void} - Remove old data from sheet.
*/
private dataSourceChangedHandler(
args: { oldProp: Workbook, sheetIdx: string, rangeIdx: string, isLastRange: boolean, changedData: Object[] }): void {
let row: RowModel;
const sheet: SheetModel = this.parent.sheets[args.sheetIdx];
const range: ExtendedRange = sheet.ranges[args.rangeIdx];
if (range && (this.checkRangeHasChanges(sheet, args.rangeIdx) || !range.info)) {
const showFieldAsHeader: boolean = range.showFieldAsHeader;
const indexes: number[] = getCellIndexes(range.startCell);
if (range.info) {
range.info.loadedRange.forEach((loadedRange: number[]) => {
for (let i: number = loadedRange[0]; i <= loadedRange[1] && (i < range.info.count + (showFieldAsHeader ? 1 : 0)); i++) {
row = sheet.rows[i + indexes[0]];
if (row) {
for (let j: number = indexes[1]; j < indexes[1] + range.info.fldLen; j++) {
if (row.cells && row.cells[j]) {
delete row.cells[j];
}
}
}
}
});
range.info = null;
}
interface Viewport { topIndex: number; bottomIndex: number; leftIndex: number; rightIndex: number; }
const viewport: Viewport = (this.parent as unknown as { viewport: Viewport }).viewport;
const refreshRange: number[] = [viewport.topIndex, viewport.leftIndex, viewport.bottomIndex, viewport.rightIndex];
const eventArgs: { sheet: ExtendedSheet, indexes: number[], promise: Promise<CellModel>, dataSourceChange?: boolean } = {
sheet: sheet as ExtendedSheet, indexes: refreshRange, dataSourceChange: true, promise:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
new Promise((resolve: Function, reject: Function) => { resolve((() => { /** */ })()); })
};
this.updateSheetFromDataSourceHandler(eventArgs);
eventArgs.promise.then(() => {
this.parent.notify('updateView', { indexes: refreshRange, checkWrap: true });
this.parent.trigger(
'dataSourceChanged',
{ data: args.changedData, action: 'dataSourceChanged', rangeIndex: Number(args.rangeIdx), sheetIndex:
Number(args.sheetIdx) });
});
}
}
private checkRangeHasChanges(sheet: SheetModel, rangeIdx: string): boolean {
if ((this.parent as unknown as { isAngular: boolean }).isAngular) {
const changedRangeIdx: string = 'changedRangeIdx';
if (sheet[changedRangeIdx] === parseInt(rangeIdx, 10)) {
delete sheet[changedRangeIdx];
return true;
}
return false;
} else {
return true;
}
}
/**
* Triggers dataSourceChange event when cell data changes
*
* @param {Object} args - Specify the args.
* @param {number} args.sheetIdx - Specify the sheetIdx.
* @param {number} args.activeSheetIndex - Specify the activeSheetIndex.
* @param {string} args.address - Specify the address.
* @param {number} args.startIndex - Specify the startIndex.
* @param {number} args.endIndex - Specify the endIndex.
* @param {string} args.modelType - Specify the modelType.
* @param {RowModel[]} args.deletedModel - Specify the deletedModel.
* @param {RowModel[]} args.model - Specify the model.
* @param {string} args.insertType - Specify the insertType.
* @param {number} args.index - Specify the index.
* @param {string} args.type - Specify the type.
* @param {string} args.pastedRange - Specify the pasted range.
* @param {string} args.range - Specify the range.
* @param {boolean} args.isUndoRedo - Specify the boolean value.
* @param {string} args.requestType - Specify the requestType.
* @returns {void} - Triggers dataSourceChange event when cell data changes
*/
private dataChangedHandler(args: {
sheetIdx: number, activeSheetIndex: number, address: string, startIndex: number, endIndex: number, modelType: string,
deletedModel: RowModel[], model: RowModel[], insertType: string, index: number, type: string, pastedRange: string,
range: string, isUndoRedo: boolean, requestType: string, data?: Object[], isDataRequest?: boolean, isMethod?: boolean
}): void {
const changedData: Object[] = [{}];
let action: string;
let cell: CellModel;
let dataRange: number[];
let startCell: number[];
let inRange: boolean;
let inRangeCut: boolean;
let deleteRowDetails: { count: number, index: number };
const sheetIdx: number = args.sheetIdx === undefined ? this.parent.activeSheetIndex : args.sheetIdx;
const sheet: SheetModel = this.parent.sheets[sheetIdx];
let cellIndices: number[];
let cutIndices: number[];
sheet.ranges.forEach((range: ExtendedRange, idx: number) => {
if (range.dataSource) {
let isNewRow: boolean;
startCell = getCellIndexes(range.startCell);
dataRange = [...startCell, startCell[0] + range.info.count + (range.showFieldAsHeader ? 0 : -1),
startCell[1] + range.info.fldLen - 1];
if (args.modelType === 'Row' || args.modelType === 'Column') {
if (args.modelType === 'Column') {
if (args.insertType) {
inRange = dataRange[1] < args.index && dataRange[3] >= args.index;
cellIndices = [args.index];
if (!inRange) {
if ((dataRange[3] + 1 === args.index && args.insertType === 'after')) {
args.model.forEach((): void => {
range.info.flds.splice(args.index - startCell[1], 0, '');
});
range.info.fldLen += args.model.length;
} else if (dataRange[1] >= args.index) {
range.startCell = getCellAddress(startCell[0], startCell[1] + args.model.length);
}
} else {
args.model.forEach((): void => {
range.info.flds.splice(args.index - startCell[1], 0, '');
});
range.info.fldLen += args.model.length;
}
} else {
inRange = dataRange[1] <= args.startIndex && dataRange[3] >= args.startIndex;
if (inRange) {
for (let i: number = args.startIndex; i <= args.endIndex; i++) {
if (i <= dataRange[3]) {
range.info.flds.splice(args.startIndex, 1);
range.info.fldLen -= 1;
}
}
}
}
return;
} else {
if (args.insertType) {
inRange = ((!range.showFieldAsHeader && args.insertType === 'above') ? dataRange[0] <= args.index
: dataRange[0] < args.index) && dataRange[2] >= args.index;
cellIndices = [args.index];
if (!inRange) {
if ((dataRange[2] + 1 === args.index && args.insertType === 'below')) {
isNewRow = true;
range.info.count += args.model.length;
} else if (dataRange[0] >= args.index) {
range.startCell = getCellAddress(startCell[0] + args.model.length, startCell[1]);
}
} else {
isNewRow = true;
range.info.count += args.model.length;
}
if (args.isMethod) { return; }
} else {
inRange = dataRange[0] <= args.startIndex && dataRange[2] >= args.startIndex;
if (args.isDataRequest) {
cellIndices = [args.startIndex, dataRange[1], args.startIndex, dataRange[1]];
} else {
action = 'delete';
}
}
}
} else {
cellIndices = getRangeIndexes(
args.requestType === 'paste' ? args.pastedRange.split('!')[1] : args.sheetIdx > -1 ? args.address :
(args.address || args.range).split('!')[1]);
const dataRangeIndices: number[] =
[...[range.showFieldAsHeader ? dataRange[0] + 1 : dataRange[0]], ...dataRange.slice(1, 4)];
if (cellIndices[0] === startCell[0]) {
for (let i: number = cellIndices[1]; i <= cellIndices[3]; i++) {
if (i >= dataRangeIndices[1] && i <= dataRangeIndices[3]) {
range.info.flds[i - startCell[1]] = getCell(startCell[0], i, sheet, false, true).value || '';
}
}
}
inRange = isInRange(dataRangeIndices, cellIndices, true);
if (args.requestType === 'paste' && (args as unknown as { copiedInfo: { isCut: boolean } }).copiedInfo.isCut) {
cutIndices = [].slice.call((args as unknown as { copiedInfo: { range: number[] } }).copiedInfo.range);
if (cutIndices[0] === startCell[0]) {
for (let i: number = cutIndices[1]; i <= cutIndices[3]; i++) {
if (i >= dataRangeIndices[1] && i <= dataRangeIndices[3]) {
range.info.flds[i - startCell[1]] = '';
}
}
inRange = false;
}
inRangeCut = isInRange(dataRangeIndices, cutIndices, true);
}
}
if (inRange || isNewRow || inRangeCut) {
if (args.modelType === 'Row' && !args.insertType && !args.isDataRequest) {
args.deletedModel.forEach((row: RowModel, rowIdx: number) => {
changedData[rowIdx] = {};
range.info.flds.forEach((fld: string, idx: number) => {
if (row.cells) {
cell = row.cells[startCell[1] + idx];
changedData[rowIdx][fld] = this.getFormattedValue(cell);
} else {
changedData[rowIdx][fld] = null;
}
});
range.info.count -= 1;
});
if (args.isMethod) { return; }
deleteRowDetails = { count: args.deletedModel.length, index: args.endIndex };
} else {
action = isNewRow ? 'add' : 'edit';
let addedCutData: number = 0;
if (inRangeCut) {
addedCutData = cutIndices[2] - cutIndices[0] + 1;
for (let i: number = 0; i < addedCutData; i++) {
changedData[i] = {};
range.info.flds.forEach((fld: string, idx: number) => {
if (fld) {
cell = getCell(cutIndices[0] + i, startCell[1] + idx, sheet);
changedData[i][fld] = this.getFormattedValue(cell);
}
});
}
}
if (inRange || isNewRow) {
for (let i: number = 0; i < (isNewRow ? args.model.length : (cellIndices[2] - cellIndices[0]) + 1 || 1); i++) {
changedData[i + addedCutData] = {};
range.info.flds.forEach((fld: string, idx: number) => {
if (fld) {
cell = getCell(cellIndices[0] + i, startCell[1] + idx, sheet);
changedData[i + addedCutData][fld] = this.getFormattedValue(cell);
}
});
}
}
}
if (args.isDataRequest) {
args.data = changedData;
} else {
this.parent.trigger(
'dataSourceChanged', { data: changedData, action: action, rangeIndex: idx, sheetIndex: sheetIdx });
}
} else if (deleteRowDetails && deleteRowDetails.count && dataRange[0] > deleteRowDetails.index) {
range.startCell = getCellAddress(startCell[0] - deleteRowDetails.count, startCell[1]);
}
}
});
}
private getFormattedValue(cell: CellModel): string {
const value: string = this.parent.getDisplayText(cell);
if (value === '') {
return null;
} else if (cell && !cell.format && typeof cell.value === 'number') {
return cell.value;
}
return value;
}
private triggerDataChangeHandler(args: {
action: string, isUndo: boolean, eventArgs: {
modelType: string, type: string, index: number,
startIndex: number, endIndex: number, model: object[], deletedModel: object[], insertType: string, requestType: string
}
}): void {
const dataChangingActions: string[] = ['insert', 'delete', 'edit', 'cellDelete', 'cellSave', 'clipboard', 'clear'];
let triggerDataChange: boolean = true;
if ((args.action === 'delete' || args.action === 'insert') && ['Sheet'].indexOf(args.eventArgs.modelType) > -1) {
triggerDataChange = false;
} else if (args.action === 'clear' && ['Clear Formats', 'Clear Hyperlinks'].indexOf(args.eventArgs.type) > -1) {
triggerDataChange = false;
} else if (args.action === 'clipboard' && args.eventArgs.requestType === 'Formats') {
triggerDataChange = false;
}
if (args.isUndo && (args.action === 'delete' || args.action === 'insert')) {
if (args.action === 'delete') {
args.eventArgs.index = args.eventArgs.startIndex;
args.eventArgs.model = args.eventArgs.deletedModel;
args.eventArgs.insertType = 'below';
} else {
args.eventArgs.startIndex = args.eventArgs.index;
args.eventArgs.endIndex = args.eventArgs.index + args.eventArgs.model.length - 1;
args.eventArgs.deletedModel = args.eventArgs.model;
delete args.eventArgs.insertType;
}
}
if (triggerDataChange && dataChangingActions.indexOf(args.action) > -1) {
this.parent.notify(dataChanged, args.eventArgs);
}
}
/**
* For internal use only - Get the module name.
*
* @returns {string} - Get the module name.
* @private
*/
protected getModuleName(): string {
return 'dataBind';
}
/**
* Destroys the Data binding module.
*
* @returns {void} - Destroys the Data binding module.
*/
public destroy(): void {
this.removeEventListener();
this.parent = null;
this.requestedInfo = [];
}
}
interface RequestedInfo {
deferred: Deferred;
indexes: number[];
isLoaded?: boolean;
isNotLoaded?: boolean;
} | the_stack |
import * as React from 'react';
import { LogHelper, ErrorHelper, FormMode, DiscussionType, ApplicationPages, DateUtility, Parameters } from 'utilities';
import styles from './Question.module.scss';
import * as strings from 'QuestionsWebPartStrings';
// redux related
import { connect } from 'react-redux';
import { IApplicationState } from 'webparts/questions/redux/reducers/appReducer';
import { getSelectedQuestion, likeQuestion, followQuestion, updateDiscussionType, isDuplicateQuestion, deleteQuestion, saveQuestion } from 'webparts/questions/redux/actions/actions';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
// models
import { IFileAttachment, IQuestionItem } from 'models';
// controls
import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar';
import { Persona, PersonaSize } from 'office-ui-fabric-react/lib/Persona';
import { ActionButton, PrimaryButton, DefaultButton, IconButton } from 'office-ui-fabric-react/lib/Button';
import RichTextEditorComponent from '../RichTextEditor';
import AttachmentsComponent from '../Attachments/Attachments';
import { Icon } from 'office-ui-fabric-react/lib/Icon';
import { DirectionalHint } from 'office-ui-fabric-react/lib/Callout';
import ReplyListComponent from '../ReplyList/ReplyList';
import ReplyComponent from '../Reply/Reply';
import { IContextualMenuItem } from 'office-ui-fabric-react/lib/ContextualMenu';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import CategoryLabel from '../CategoryLabel/CategoryLabel';
import { LivePersonaCard } from '../LivePersonaCard';
interface IConnectedDispatch {
getSelectedQuestion: (questionId?: number) => void;
likeQuestion: (question: IQuestionItem) => Promise<void>;
followQuestion: (question: IQuestionItem) => Promise<void>;
updateDiscussionType: (question: IQuestionItem) => Promise<void>;
deleteQuestion: (question: IQuestionItem) => Promise<void>;
isDuplicateQuestion: (question: IQuestionItem) => Promise<boolean>;
saveQuestion: (question: IQuestionItem) => Promise<number>;
}
interface IConnectedState {
selectedQuestion: IQuestionItem | null;
type: DiscussionType;
webPartContext?: WebPartContext;
themeVariant: IReadonlyTheme | undefined;
applicationPage: string;
}
// map the application state to properties on this component so they can be used
function mapStateToProps(state: IApplicationState, ownProps: IQuestionProps): IConnectedState {
return {
selectedQuestion: state.selectedQuestion,
type: DiscussionType[state.discussionType],
webPartContext: state.webPartContext,
themeVariant: state.themeVariant,
applicationPage: state.applicationPage
};
}
// map actions to properties so they can be invoked
const mapDispatchToProps = {
getSelectedQuestion,
likeQuestion,
followQuestion,
updateDiscussionType,
deleteQuestion,
saveQuestion,
isDuplicateQuestion
};
export interface IQuestionProps {
show: boolean;
}
interface IQuestionState {
formMode: FormMode;
question?: IQuestionItem;
isChanged: boolean;
showUndoConfirm: boolean;
showDeleteConfirm: boolean;
showNotification: boolean;
closeOnUndoConfirm: boolean;
notificationMessage?: string;
notificationType?: MessageBarType;
disablePost: boolean;
showNewReply: boolean;
expectedApplicationPage: string | undefined;
}
class QuestionComponent extends React.Component<IQuestionProps & IConnectedState & IConnectedDispatch, IQuestionState> {
constructor(props: IQuestionProps & IConnectedState & IConnectedDispatch) {
super(props);
LogHelper.verbose(this.constructor.name, 'ctor', 'start');
this.state = {
formMode: FormMode.View,
isChanged: false,
showUndoConfirm: false,
closeOnUndoConfirm: false,
showDeleteConfirm: false,
showNotification: false,
showNewReply: false,
disablePost: false,
expectedApplicationPage: undefined
};
}
public componentDidMount() {
// check if we are on an application page with a query string to see if we even care to deal with people coming in on the 'wrong' url
if(window.location.search.length > 0) {
if(window.location.pathname.toLowerCase().endsWith(ApplicationPages.QUESTIONS.toLowerCase())) {
this.setState({expectedApplicationPage: ApplicationPages.QUESTIONS});
}
if(window.location.pathname.toLowerCase().endsWith(ApplicationPages.CONVERSATIONS.toLowerCase())) {
this.setState({expectedApplicationPage: ApplicationPages.CONVERSATIONS});
}
}
window.addEventListener('beforeunload', this.beforeunload.bind(this));
}
public componentWillUnmount() {
window.removeEventListener('beforeunload', this.beforeunload.bind(this));
}
public componentDidUpdate(prevProps: IQuestionProps & IConnectedState & IConnectedDispatch, prevState: IQuestionState): void {
// if our question has changed
if (this.props.selectedQuestion && this.props.selectedQuestion !== prevProps.selectedQuestion) {
// reset our question in state managed by this component
this.setState({ question: this.props.selectedQuestion });
if(this.state.expectedApplicationPage === ApplicationPages.QUESTIONS
&& this.props.selectedQuestion.discussionType === DiscussionType.Conversation) {
// we came in on Questions.aspx for an item that is a conversation so redirect
window.location.replace(window.location.href.replace(new RegExp(ApplicationPages.QUESTIONS, "gi"), ApplicationPages.CONVERSATIONS));
}
else if(this.state.expectedApplicationPage === ApplicationPages.CONVERSATIONS
&& this.props.selectedQuestion.discussionType === DiscussionType.Question) {
// we came in on Conversations.aspx for an item that is a question so redirect
window.location.replace(window.location.href.replace(new RegExp(ApplicationPages.CONVERSATIONS, "gi"), ApplicationPages.QUESTIONS));
}
else {
// ensure we don't execute the logic above after any further state changes
this.setState({ expectedApplicationPage: undefined });
}
// and previously it was null or undefined
if (!prevProps.selectedQuestion) {
// determine and set the appropriate initial form mode
if (this.props.selectedQuestion.id && this.props.selectedQuestion.id > 0) {
this.setState({ formMode: FormMode.View });
}
else {
this.setState({ formMode: FormMode.New });
}
}
}
}
public render(): React.ReactElement<IQuestionProps> {
const { question, showNewReply: showNewReply } = this.state;
let id: string = question ? `question-${question.id}` : `question-new`;
let buttonStyle: any = undefined;
if (this.props.themeVariant) {
buttonStyle = { color: this.props.themeVariant.semanticColors.link };
}
if (question) {
return (
<div id={id} className={styles.question}
style={{ display: this.props.show === true ? 'block' : 'none' }}>
<div className={styles.containerHeader}>
<ActionButton id="closePanel" text={strings.ButtonText_Close}
style={buttonStyle}
iconProps={{ iconName: 'ChromeClose', style : buttonStyle }}
onClick={(ev: any) => this.handleCloseClick()} />
</div>
<div className={styles.container}>
{this.renderQuestion()}
{question.isAnswered === true && question.answerReply !== undefined &&
<ReplyComponent
show={true}
readOnlyMode={true}
formMode={FormMode.View}
answerMode={true}
reply={question.answerReply}
parentQuestion={question} />
}
<ReplyComponent
show={showNewReply}
formMode={FormMode.New}
parentQuestion={question}
onActionCompleted={() => this.setState({ showNewReply: false })} />
<ReplyListComponent
replies={question.replies}
parentQuestion={question} />
{this.getUndoConfirmDialog()}
{this.getUndoDeleteConfirmDialog()}
</div>
</div>
);
}
else {
return (<div id={id}></div>);
}
}
private renderQuestion(): JSX.Element | undefined {
const { question, formMode, showNotification, notificationType, notificationMessage, disablePost } = this.state;
const { webPartContext } = this.props;
if (question) {
return (
<div className={styles.questionContainer}>
<div className={styles.questionItem}>
{this.renderQuestionAdminActions()}
{this.renderIsAnswered(question)}
{this.renderQuestionTitle(question)}
{formMode === FormMode.View && question.author && question.createdDate &&
<div className={styles.questionPersonaContainer}>
<span>
{(webPartContext !== null && webPartContext !== undefined ?
<LivePersonaCard
serviceScope={webPartContext.serviceScope}
user={{
displayName: (question.author === null || question.author === undefined ? '' : (question.author.text === undefined ? '' : question.author.text)),
email: (question.author === null || question.author === undefined ? '' : (question.author.id === undefined ? '' : question.author.id.replace("i:0#.f|membership|", "")))
}}
>
<Persona size={PersonaSize.size32}
text={question.author.text}
showSecondaryText={true}
onRenderSecondaryText={props => this.onRenderSecondaryText(question)} />
</LivePersonaCard>
:
<Persona size={PersonaSize.size32}
text={question.author.text}
showSecondaryText={true}
onRenderSecondaryText={props => this.onRenderSecondaryText(question)} />
)}
</span>
<span>
<CategoryLabel category={question.category} style={{ float: 'right' }}></CategoryLabel>
</span>
</div>
}
{this.renderQuestionDetails(question)}
<AttachmentsComponent item={question}
disabled={formMode === FormMode.View}
attachmentsChanged={(attachments: IFileAttachment[]) => { this.attachmentsChanged(attachments); }}
newAttachmentsChanged={(newAttachments: File[]) => { this.newAttachmentsChanged(newAttachments); }}
removeAttachmentsChanged={(removedAttachments: string[]) => { this.removeAttachmentsChanged(removedAttachments); }} />
{this.renderQuestionUserActions()}
{formMode !== FormMode.View &&
<div className={styles.userActions}>
<span>
<CategoryLabel category={question.category} style={{ float: 'left' }}></CategoryLabel>
</span>
<PrimaryButton id='Post' text={strings.ButtonText_Post}
iconProps={{ iconName: 'Send' }} onClick={() => this.handleSaveClick()} disabled={disablePost} />
<DefaultButton id='Undo' text={strings.ButtonText_Cancel}
iconProps={{ iconName: 'Undo' }} onClick={() => this.handleCancelClick()} disabled={disablePost} />
</div>
}
{
showNotification &&
<div className={styles.messagebarContainer}>
<MessageBar messageBarType={notificationType}>{notificationMessage}</MessageBar>
</div>
}
</div>
</div>
);
}
}
private renderQuestionAdminActions(): JSX.Element | undefined {
const { question } = this.state;
const { formMode } = this.state;
const changeDiscussionTypeText = this.props.type === DiscussionType.Question ? strings.MenuText_ChangeToConversation : strings.MenuText_ChangeToQuestion;
let items: IContextualMenuItem[] = [];
if (question) {
if (question.canEdit) {
items.push({
key: 'editQuestion', name: (strings.MenuText_Edit), iconProps: { iconName: 'Edit' },
onClick: (ev: any) => this.handleEditClick()
});
}
if (question.canDelete) {
items.push({
key: 'deleteQuestion', name: (strings.MenuText_Delete), iconProps: { iconName: 'Delete' },
onClick: (ev: any) => this.setState({ showDeleteConfirm: true })
});
}
if(question.canEdit) {
items.push({
key: 'changeDiscussionType', name: (changeDiscussionTypeText), iconProps: { iconName: 'Switch' },
onClick: (ev: any) => this.handleDiscussionTypeChangeClick()
});
}
}
if (formMode === FormMode.View && items.length > 0) {
return (
<div className={styles.adminActionsContainer}>
<IconButton id="questionSettings"
iconProps={{ iconName: 'Settings' }}
menuProps={{
directionalHint: DirectionalHint.bottomRightEdge,
items: items
}}
/>
</div>
);
}
}
private renderQuestionUserActions(): JSX.Element | undefined {
const { question } = this.state;
const { formMode } = this.state;
if (question && formMode === FormMode.View) {
return (
<div className={styles.userActions}>
<ActionButton id="copyLink"
text={strings.ButtonText_CopyLink}
title={strings.ButtonText_CopyLink}
iconProps={{ iconName: 'Link' }}
onClick={() => this.handleCopyLinkClick(question.id) } />
{question.canReact === true &&
<ActionButton id="followQuestion"
text={` ${question.followedByCurrentUser ? strings.ButtonText_Following : strings.ButtonText_NotFollowing}`}
title={strings.ButtonTitle_Following}
iconProps={{ iconName: question.followedByCurrentUser === true ? 'MailSolid' : 'Mail' }}
onClick={() => this.props.followQuestion(question)} />
}
{question.canReact === true &&
<ActionButton id="likeQuestion"
text={` ${strings.ButtonText_Like} (${question.likeCount ? question.likeCount : 0})`}
iconProps={{ iconName: question.likedByCurrentUser === true ? 'LikeSolid' : 'Like' }}
onClick={() => this.props.likeQuestion(question)} />
}
{question.canReply === true &&
<ActionButton id="addReply"
text={` ${strings.ButtonText_Reply} (${question.totalReplyCount ? question.totalReplyCount : 0})`}
iconProps={{ iconName: 'CommentAdd' }}
onClick={() => this.setState({ showNewReply: true })} />
}
</div>
);
}
}
private renderIsAnswered(question: IQuestionItem): JSX.Element | undefined {
if (question.isAnswered === true && question.discussionType === DiscussionType.Question) {
return (
<div>
<span className={styles.questionIsAnsweredContainer}>
<Icon iconName={'CheckMark'} />
{strings.Message_IsAnswered}
</span>
</div>
);
}
}
private renderQuestionTitle(question: IQuestionItem): JSX.Element {
const { formMode } = this.state;
if (formMode === FormMode.View) {
return (
<div className={styles.questionTitle}>
{question.title}
</div>
);
}
else {
return (
<div className={styles.questionTitle}>
<textarea placeholder={(this.props.type === DiscussionType.Question ? strings.Placeholder_QuestionTitle : strings.Placeholder_ConversationTitle)}
value={question.title}
maxLength={255}
autoFocus={true}
onKeyPress={this.handleOnKeyPress}
onChange={(e) => this.handleTextChanged('title', e.target.value)}></textarea>
<div className={styles.errorMessage}>{ErrorHelper.getUIError(question, 'title')}</div>
</div>
);
}
}
private renderQuestionDetails(question: IQuestionItem): JSX.Element {
const { formMode } = this.state;
if (formMode === FormMode.View) {
return (
<div className={styles.questionBodyContainer}>
<div dangerouslySetInnerHTML={{ __html: question.details }}></div>
</div>
);
}
else {
return (
<div className={styles.questionBodyContainer}>
<RichTextEditorComponent id="details"
value={question.details}
questionTitle={question.title ? question.title : ''}
placeholder={(this.props.type === DiscussionType.Question ? strings.Placeholder_QuestionDetails : strings.Placeholder_ConversationDetails)}
onTextChange={(htmlValue, textValue) => this.handleEditorChanged('details', htmlValue, 'detailsText', textValue)}
/>
<div className={styles.errorMessage}>{ErrorHelper.getUIError(question, 'details')}</div>
</div>
);
}
}
private onRenderSecondaryText = (question: IQuestionItem): JSX.Element => {
return (
<div>
<Icon iconName={'Comment'} />
{strings.Message_PostedOn} {DateUtility.getFriendlyDate(question.createdDate, true)}
</div>
);
}
private handleOnKeyPress = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
}
}
private handleTextChanged = (propertyName: string, newValue: string) => {
const { question } = this.state;
if (question) {
question[propertyName] = newValue;
ErrorHelper.removeUIError(question, propertyName);
this.setState({ question });
this.handleOnChanged(true);
}
}
private handleEditorChanged = (htmlPropertyName: string, htmlValue: string | null, textPropertyName: string, textValue: string) => {
const { question } = this.state;
if (question) {
question[htmlPropertyName] = htmlValue;
question[textPropertyName] = textValue;
ErrorHelper.removeUIError(question, htmlPropertyName);
this.setState({ question });
this.handleOnChanged(true);
}
}
private handleEditClick = (): void => {
const { question } = this.state;
if (question) {
// this is a refetch but we want to get the latest version when going to edit in case they've been on view awhile
this.props.getSelectedQuestion(question.id);
this.setState({ formMode: FormMode.Edit });
}
}
private handleConfirmDeleteClick = (): void => {
const { question } = this.state;
if (question) {
this.props.deleteQuestion(question).then(() => {
this.setState({ showDeleteConfirm: false });
});
}
}
private handleCloseClick = (): void => {
let { isChanged } = this.state;
if (isChanged === true) {
// show a confirmation
this.setState({ showUndoConfirm: true, closeOnUndoConfirm: true });
}
else {
this.props.getSelectedQuestion();
this.setState({
formMode: FormMode.View,
showUndoConfirm: false,
showNotification: false
});
this.handleOnChanged(false);
}
}
private handleCancelClick = (): void => {
let { isChanged, formMode } = this.state;
if (isChanged === true) {
// show a confirmation
this.setState({ showUndoConfirm: true });
}
else {
if (formMode === FormMode.New) {
this.props.getSelectedQuestion();
}
this.setState({
formMode: FormMode.View,
showUndoConfirm: false,
showNotification: false
});
this.handleOnChanged(false);
}
}
private handleUndoChangesClick = (): void => {
let { formMode, question, closeOnUndoConfirm } = this.state;
if (formMode === FormMode.New || closeOnUndoConfirm === true) {
this.props.getSelectedQuestion();
}
else {
/* revisit this to improve responsiveness
selectedQuestion = this.props.selectedQuestion;
this.setState({ question });
*/
if (question) {
this.props.getSelectedQuestion(question.id);
}
}
this.setState({
formMode: FormMode.View,
showUndoConfirm: false,
showNotification: false,
closeOnUndoConfirm: false
});
this.handleOnChanged(false);
}
private handleSaveClick = async (): Promise<void> => {
const { question } = this.state;
this.setState({ disablePost: true });
let isQuestionValid = await this.isQuestionValid();
if (isQuestionValid) {
this.setState({
showNotification: true,
notificationType: MessageBarType.info,
notificationMessage: (this.props.type === DiscussionType.Question ? strings.Message_SavingQuestion : strings.Message_SavingConversation)
});
if (question) {
this.props.saveQuestion(question).then(id => {
this.setState({
disablePost: false,
formMode: FormMode.View,
showUndoConfirm: false,
notificationType: MessageBarType.success,
notificationMessage: (this.props.type === DiscussionType.Question ? strings.Message_SavedQuestion : strings.Message_SavedConversation )
});
this.handleOnChanged(false);
// after 5 seconds hide the notification
setTimeout(() => { this.setState({ showNotification: false, notificationMessage: undefined }); }, 5000);
}).catch((e) => {
this.setState({
disablePost: false,
showNotification: true,
notificationType: MessageBarType.error,
notificationMessage: e.message
});
});
}
}
else {
this.setState({ disablePost: false });
}
}
private handleDiscussionTypeChangeClick = (): void => {
const { question } = this.state;
if(question) {
question.discussionType = question.discussionType === DiscussionType.Question ? DiscussionType.Conversation : DiscussionType.Question;
this.props.updateDiscussionType(question);
}
}
private handleCopyLinkClick = (questionId?: number): void => {
debugger;
if(this.props.webPartContext && questionId) {
const el = document.createElement('textarea');
el.value = `${this.props.webPartContext.pageContext.web.absoluteUrl}/SitePages/${this.props.applicationPage}?${Parameters.QUESTIONID}=${questionId}`;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
}
private isQuestionValid = async (): Promise<boolean> => {
const { question } = this.state;
let isValid: boolean = true;
if (question) {
question.uiErrors = new Map<string, string>();
if (question.title) {
let isDuplicate = await this.props.isDuplicateQuestion(question);
if (isDuplicate === true) {
ErrorHelper.setUIError(question, 'title', strings.ErrorMessage_DuplicateQuestion);
isValid = false;
}
}
else {
isValid = false;
ErrorHelper.setUIError(question, 'title', question.discussionType === DiscussionType.Question ? strings.ErrorMessage_QuestionRequired : strings.ErrorMessage_ConversationRequired);
}
if (!question.details) {
isValid = false;
ErrorHelper.setUIError(question, 'details', strings.ErrorMessage_DetailsRequired);
}
}
this.setState({
showNotification: !isValid,
notificationType: MessageBarType.error,
notificationMessage: isValid === false ? strings.MessageBar_QuestionSaveErrors : undefined
});
return isValid;
}
private handleOnChanged = (changed: boolean): void => {
this.setState({ isChanged: changed });
}
private attachmentsChanged = (attachments: IFileAttachment[]): void => {
const { question } = this.state;
if (question) {
question.attachments = attachments;
this.setState({ question: question });
this.handleOnChanged(true);
}
}
private newAttachmentsChanged = (newAttachments: File[]): void => {
const { question } = this.state;
if (question) {
question.newAttachments = newAttachments;
this.setState({ question: question });
this.handleOnChanged(true);
}
}
private removeAttachmentsChanged = (removedAttachments: string[]): void => {
const { question } = this.state;
if (question) {
question.removedAttachments = removedAttachments;
this.setState({ question: question });
this.handleOnChanged(true);
}
}
// future common
private getUndoConfirmDialog = (): JSX.Element | undefined => {
const { showUndoConfirm } = this.state;
if (showUndoConfirm === true) {
return (
<Dialog
hidden={!showUndoConfirm}
dialogContentProps={{
type: DialogType.normal,
title: (strings.Dialog_UnsavedChangesTitle),
subText: (strings.Dialog_UnsavedChangedSubText)
}}
modalProps={{ isBlocking: true }}>
<DialogFooter>
<PrimaryButton text={strings.ButtonText_Continue}
onClick={this.handleUndoChangesClick} />
<DefaultButton text={strings.ButtonText_ResumeEdit}
onClick={() => this.setState({ showUndoConfirm: false })} />
</DialogFooter>
</Dialog>
);
}
}
private getUndoDeleteConfirmDialog = (): JSX.Element | undefined => {
const { showDeleteConfirm } = this.state;
if (showDeleteConfirm === true) {
return (
<Dialog
hidden={!showDeleteConfirm}
dialogContentProps={{
type: DialogType.normal,
title: (strings.Dialog_DeleteConfirmTitle),
subText: (strings.Dialog_DeleteConfirmSubText)
}}
modalProps={{ isBlocking: true }}>
<DialogFooter>
<PrimaryButton text={strings.ButtonText_Yes}
onClick={this.handleConfirmDeleteClick} />
<DefaultButton text={strings.ButtonText_No}
onClick={() => this.setState({ showDeleteConfirm: false })} />
</DialogFooter>
</Dialog>
);
}
}
private beforeunload = (e) => {
let { isChanged } = this.state;
if (isChanged === true) {
e.preventDefault();
e.returnValue = true;
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(QuestionComponent); | the_stack |
import * as Utils from './utils/utils.js';
let iconConstructor: (() => Element)|null = null;
export class Icon extends HTMLSpanElement {
private descriptor: Descriptor|null;
private spriteSheet: SpriteSheet|null;
private iconType: string;
constructor() {
super();
this.descriptor = null;
this.spriteSheet = null;
this.iconType = '';
}
static create(iconType?: string, className?: string): Icon {
if (!iconConstructor) {
iconConstructor = Utils.registerCustomElement('span', 'ui-icon', Icon);
}
const icon = (iconConstructor() as Icon);
if (className) {
icon.className = className;
}
if (iconType) {
icon.setIconType(iconType);
}
return icon;
}
setIconType(iconType: string): void {
if (this.descriptor) {
this.style.removeProperty('--spritesheet-position');
this.style.removeProperty('width');
this.style.removeProperty('height');
this.toggleClasses(false);
this.iconType = '';
this.descriptor = null;
this.spriteSheet = null;
}
const descriptor = descriptors.get(iconType) || null;
if (descriptor) {
this.iconType = iconType;
this.descriptor = descriptor;
this.spriteSheet = spriteSheets.get(this.descriptor.spritesheet) || null;
if (!this.spriteSheet) {
throw new Error(`ERROR: icon ${this.iconType} has unknown spritesheet: ${this.descriptor.spritesheet}`);
}
this.style.setProperty('--spritesheet-position', this.propertyValue());
this.style.setProperty('width', this.spriteSheet.cellWidth + 'px');
this.style.setProperty('height', this.spriteSheet.cellHeight + 'px');
this.toggleClasses(true);
} else if (iconType) {
throw new Error(`ERROR: failed to find icon descriptor for type: ${iconType}`);
}
}
private toggleClasses(value: boolean): void {
if (this.descriptor) {
this.classList.toggle('spritesheet-' + this.descriptor.spritesheet, value);
this.classList.toggle(this.iconType, value);
this.classList.toggle('icon-mask', value && Boolean(this.descriptor.isMask));
this.classList.toggle('icon-invert', value && Boolean(this.descriptor.invert));
}
}
private propertyValue(): string {
if (!this.descriptor || !this.spriteSheet) {
throw new Error('Descriptor and spriteSheet expected to be present');
}
if (!this.descriptor.coordinates) {
if (!this.descriptor.position || !_positionRegex.test(this.descriptor.position)) {
throw new Error(`ERROR: icon '${this.iconType}' has malformed position: '${this.descriptor.position}'`);
}
const column = this.descriptor.position[0].toLowerCase().charCodeAt(0) - 97;
const row = parseInt(this.descriptor.position.substring(1), 10) - 1;
this.descriptor.coordinates = {
x: -(this.spriteSheet.cellWidth + this.spriteSheet.padding) * column,
y: (this.spriteSheet.cellHeight + this.spriteSheet.padding) * (row + 1) - this.spriteSheet.padding,
};
}
return `${this.descriptor.coordinates.x}px ${this.descriptor.coordinates.y}px`;
}
}
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration
// eslint-disable-next-line @typescript-eslint/naming-convention
const _positionRegex = /^[a-z][1-9][0-9]*$/;
const spriteSheets = new Map<string, SpriteSheet>([
['smallicons', {cellWidth: 10, cellHeight: 10, padding: 10}],
['mediumicons', {cellWidth: 16, cellHeight: 16, padding: 0}],
['largeicons', {cellWidth: 28, cellHeight: 24, padding: 0}],
['arrowicons', {cellWidth: 19, cellHeight: 19, padding: 0}],
]);
const initialDescriptors = new Map<string, Descriptor>([
['smallicon-bezier', {position: 'a5', spritesheet: 'smallicons', isMask: true}],
['smallicon-checkmark', {position: 'b5', spritesheet: 'smallicons'}],
['smallicon-checkmark-square', {position: 'b6', spritesheet: 'smallicons', isMask: true}],
['smallicon-checkmark-behind', {position: 'd6', spritesheet: 'smallicons', isMask: true}],
['smallicon-command-result', {position: 'a4', spritesheet: 'smallicons'}],
['smallicon-contrast-ratio', {position: 'a6', spritesheet: 'smallicons', isMask: true}],
['smallicon-cross', {position: 'b4', spritesheet: 'smallicons'}],
['smallicon-device', {position: 'c5', spritesheet: 'smallicons'}],
['smallicon-error', {position: 'c4', spritesheet: 'smallicons'}],
['smallicon-expand-less', {position: 'f5', spritesheet: 'smallicons', isMask: true}],
['smallicon-expand-more', {position: 'e6', spritesheet: 'smallicons', isMask: true}],
['smallicon-green-arrow', {position: 'a3', spritesheet: 'smallicons'}],
['smallicon-green-ball', {position: 'b3', spritesheet: 'smallicons'}],
['smallicon-info', {position: 'c3', spritesheet: 'smallicons'}],
['smallicon-inline-breakpoint-conditional', {position: 'd4', spritesheet: 'smallicons'}],
['smallicon-inline-breakpoint', {position: 'd5', spritesheet: 'smallicons'}],
['smallicon-no', {position: 'c6', spritesheet: 'smallicons', isMask: true}],
['smallicon-orange-ball', {position: 'd3', spritesheet: 'smallicons'}],
['smallicon-red-ball', {position: 'a2', spritesheet: 'smallicons'}],
['smallicon-shadow', {position: 'b2', spritesheet: 'smallicons', isMask: true}],
['smallicon-step-in', {position: 'c2', spritesheet: 'smallicons'}],
['smallicon-step-out', {position: 'd2', spritesheet: 'smallicons'}],
['smallicon-text-prompt', {position: 'e5', spritesheet: 'smallicons'}],
['smallicon-thick-left-arrow', {position: 'e4', spritesheet: 'smallicons'}],
['smallicon-thick-right-arrow', {position: 'e3', spritesheet: 'smallicons'}],
['smallicon-triangle-down', {position: 'e2', spritesheet: 'smallicons', isMask: true}],
['smallicon-triangle-right', {position: 'a1', spritesheet: 'smallicons', isMask: true}],
['smallicon-triangle-up', {position: 'b1', spritesheet: 'smallicons', isMask: true}],
['smallicon-user-command', {position: 'c1', spritesheet: 'smallicons'}],
['smallicon-warning', {position: 'd1', spritesheet: 'smallicons'}],
['smallicon-network-product', {position: 'e1', spritesheet: 'smallicons'}],
['smallicon-clear-warning', {position: 'f1', spritesheet: 'smallicons', isMask: true}],
['smallicon-clear-info', {position: 'f2', spritesheet: 'smallicons'}],
['smallicon-clear-error', {position: 'f3', spritesheet: 'smallicons'}],
['smallicon-account-circle', {position: 'f4', spritesheet: 'smallicons'}],
['smallicon-videoplayer-paused', {position: 'f6', spritesheet: 'smallicons', isMask: true}],
['smallicon-videoplayer-playing', {position: 'g6', spritesheet: 'smallicons', isMask: true}],
['smallicon-videoplayer-destroyed', {position: 'g5', spritesheet: 'smallicons', isMask: true}],
['smallicon-issue-yellow-text', {position: 'g1', spritesheet: 'smallicons'}],
['smallicon-issue-blue-text', {position: 'g2', spritesheet: 'smallicons'}],
['mediumicon-clear-storage', {position: 'a4', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-cookie', {position: 'b4', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-database', {position: 'c4', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-info', {position: 'c1', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-manifest', {position: 'd4', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-service-worker', {position: 'a3', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-table', {position: 'b3', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-arrow-in-circle', {position: 'c3', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-file-sync', {position: 'd3', spritesheet: 'mediumicons', invert: true}],
['mediumicon-file', {position: 'a2', spritesheet: 'mediumicons', invert: true}],
['mediumicon-gray-cross-active', {position: 'b2', spritesheet: 'mediumicons'}],
['mediumicon-gray-cross-hover', {position: 'c2', spritesheet: 'mediumicons'}],
['mediumicon-red-cross-active', {position: 'd2', spritesheet: 'mediumicons'}],
['mediumicon-red-cross-hover', {position: 'a1', spritesheet: 'mediumicons'}],
['mediumicon-search', {position: 'b1', spritesheet: 'mediumicons'}],
['mediumicon-replace', {position: 'c5', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-account-circle', {position: 'e4', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-warning-triangle', {position: 'e1', spritesheet: 'mediumicons'}],
['mediumicon-error-circle', {position: 'e3', spritesheet: 'mediumicons'}],
['mediumicon-info-circle', {position: 'e2', spritesheet: 'mediumicons'}],
['mediumicon-bug', {position: 'd1', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-list', {position: 'e5', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-warning', {position: 'd5', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-sync', {position: 'a5', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-fetch', {position: 'b5', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-cloud', {position: 'a6', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-bell', {position: 'b6', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-payment', {position: 'c6', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-schedule', {position: 'd6', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-frame', {position: 'e6', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-frame-embedded', {position: 'f6', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-frame-opened', {position: 'f5', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-frame-embedded-blocked', {position: 'f4', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-frame-blocked', {position: 'g4', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-elements-panel', {position: 'f3', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-network-panel', {position: 'f2', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-sources-panel', {position: 'g1', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-frame-top', {position: 'f1', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-checkmark', {position: 'g2', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-not-available', {position: 'g3', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-warning-circle', {position: 'g5', spritesheet: 'mediumicons', isMask: true}],
['mediumicon-feedback', {position: 'g6', spritesheet: 'mediumicons', isMask: true}],
['badge-navigator-file-sync', {position: 'a9', spritesheet: 'largeicons'}],
['largeicon-add', {position: 'a8', spritesheet: 'largeicons', isMask: true}],
['largeicon-camera', {position: 'b7', spritesheet: 'largeicons', isMask: true}],
['largeicon-center', {position: 'c9', spritesheet: 'largeicons', isMask: true}],
['largeicon-checkmark', {position: 'c8', spritesheet: 'largeicons', isMask: true}],
['largeicon-chevron', {position: 'c7', spritesheet: 'largeicons', isMask: true}],
['largeicon-clear', {position: 'a6', spritesheet: 'largeicons', isMask: true}],
['largeicon-copy', {position: 'b6', spritesheet: 'largeicons', isMask: true}],
['largeicon-deactivate-breakpoints', {position: 'c6', spritesheet: 'largeicons', isMask: true}],
['largeicon-delete', {position: 'd9', spritesheet: 'largeicons', isMask: true}],
['largeicon-delete-filter', {position: 'i5', spritesheet: 'largeicons', isMask: true}],
['largeicon-delete-list', {position: 'i6', spritesheet: 'largeicons', isMask: true}],
['largeicon-dock-to-bottom', {position: 'd8', spritesheet: 'largeicons', isMask: true}],
['largeicon-dock-to-left', {position: 'd7', spritesheet: 'largeicons', isMask: true}],
['largeicon-dock-to-right', {position: 'd6', spritesheet: 'largeicons', isMask: true}],
['largeicon-download', {position: 'h6', spritesheet: 'largeicons', isMask: true}],
['largeicon-edit', {position: 'a5', spritesheet: 'largeicons', isMask: true}],
['largeicon-eyedropper', {position: 'b5', spritesheet: 'largeicons', isMask: true}],
['largeicon-filter', {position: 'c5', spritesheet: 'largeicons', isMask: true}],
['largeicon-font-editor', {position: 'i7', spritesheet: 'largeicons', isMask: true}],
['largeicon-hide-bottom-sidebar', {position: 'e9', spritesheet: 'largeicons', isMask: true}],
['largeicon-hide-left-sidebar', {position: 'e8', spritesheet: 'largeicons', isMask: true}],
['largeicon-hide-right-sidebar', {position: 'e7', spritesheet: 'largeicons', isMask: true}],
['largeicon-hide-top-sidebar', {position: 'e6', spritesheet: 'largeicons', isMask: true}],
['largeicon-large-list', {position: 'e5', spritesheet: 'largeicons', isMask: true}],
['largeicon-layout-editor', {position: 'a4', spritesheet: 'largeicons', isMask: true}],
['largeicon-load', {position: 'h5', spritesheet: 'largeicons', isMask: true}],
['largeicon-longclick-triangle', {position: 'b4', spritesheet: 'largeicons', isMask: true}],
['largeicon-menu', {position: 'c4', spritesheet: 'largeicons', isMask: true}],
['largeicon-navigator-domain', {position: 'd4', spritesheet: 'largeicons', isMask: true}],
['largeicon-navigator-file', {position: 'e4', spritesheet: 'largeicons', isMask: true}],
['largeicon-navigator-file-sync', {position: 'f9', spritesheet: 'largeicons', isMask: true}],
['largeicon-navigator-folder', {position: 'f8', spritesheet: 'largeicons', isMask: true}],
['largeicon-navigator-frame', {position: 'f7', spritesheet: 'largeicons', isMask: true}],
['largeicon-navigator-snippet', {position: 'f6', spritesheet: 'largeicons', isMask: true}],
['largeicon-navigator-worker', {position: 'f5', spritesheet: 'largeicons', isMask: true}],
['largeicon-node-search', {position: 'f4', spritesheet: 'largeicons', isMask: true}],
['largeicon-pan', {position: 'a3', spritesheet: 'largeicons', isMask: true}],
['largeicon-pause-animation', {position: 'b3', spritesheet: 'largeicons', isMask: true}],
['largeicon-pause', {position: 'c3', spritesheet: 'largeicons', isMask: true}],
['largeicon-pause-on-exceptions', {position: 'd3', spritesheet: 'largeicons', isMask: true}],
['largeicon-phone', {position: 'e3', spritesheet: 'largeicons', isMask: true}],
['largeicon-play-animation', {position: 'f3', spritesheet: 'largeicons', isMask: true}],
['largeicon-play-back', {position: 'a2', spritesheet: 'largeicons', isMask: true}],
['largeicon-play', {position: 'b2', spritesheet: 'largeicons', isMask: true}],
['largeicon-pretty-print', {position: 'c2', spritesheet: 'largeicons', isMask: true}],
['largeicon-refresh', {position: 'd2', spritesheet: 'largeicons', isMask: true}],
['largeicon-replay-animation', {position: 'e2', spritesheet: 'largeicons', isMask: true}],
['largeicon-resume', {position: 'f2', spritesheet: 'largeicons', isMask: true}],
['largeicon-rotate', {position: 'g9', spritesheet: 'largeicons', isMask: true}],
['largeicon-rotate-screen', {position: 'g8', spritesheet: 'largeicons', isMask: true}],
['largeicon-search', {position: 'h4', spritesheet: 'largeicons', isMask: true}],
['largeicon-settings-gear', {position: 'g7', spritesheet: 'largeicons', isMask: true}],
['largeicon-shortcut-changed', {position: 'i4', spritesheet: 'largeicons', isMask: true}],
['largeicon-show-bottom-sidebar', {position: 'g6', spritesheet: 'largeicons', isMask: true}],
['largeicon-show-left-sidebar', {position: 'g5', spritesheet: 'largeicons', isMask: true}],
['largeicon-show-right-sidebar', {position: 'g4', spritesheet: 'largeicons', isMask: true}],
['largeicon-show-top-sidebar', {position: 'g3', spritesheet: 'largeicons', isMask: true}],
['largeicon-start-recording', {position: 'g2', spritesheet: 'largeicons', isMask: true}],
['largeicon-step-into', {position: 'a1', spritesheet: 'largeicons', isMask: true}],
['largeicon-step-out', {position: 'b1', spritesheet: 'largeicons', isMask: true}],
['largeicon-step-over', {position: 'c1', spritesheet: 'largeicons', isMask: true}],
['largeicon-step', {position: 'h1', spritesheet: 'largeicons', isMask: true}],
['largeicon-stop-recording', {position: 'd1', spritesheet: 'largeicons', isMask: true}],
['largeicon-terminate-execution', {position: 'h2', spritesheet: 'largeicons', isMask: true}],
['largeicon-trash-bin', {position: 'f1', spritesheet: 'largeicons', isMask: true}],
['largeicon-undo', {position: 'h7', spritesheet: 'largeicons', isMask: true}],
['largeicon-undock', {position: 'g1', spritesheet: 'largeicons', isMask: true}],
['largeicon-visibility', {position: 'h9', spritesheet: 'largeicons', isMask: true}],
['largeicon-waterfall', {position: 'h8', spritesheet: 'largeicons', isMask: true}],
['largeicon-breaking-change', {position: 'h3', spritesheet: 'largeicons'}],
['largeicon-link', {position: 'i1', spritesheet: 'largeicons', isMask: true}],
['largeicon-dual-screen', {position: 'i2', spritesheet: 'largeicons', isMask: true}],
['largeicon-experimental-api', {position: 'i3', spritesheet: 'largeicons', isMask: true}],
['mediumicon-arrow-top', {position: 'a4', spritesheet: 'arrowicons'}],
['mediumicon-arrow-bottom', {position: 'a3', spritesheet: 'arrowicons'}],
['mediumicon-arrow-left', {position: 'a2', spritesheet: 'arrowicons'}],
['mediumicon-arrow-right', {position: 'a1', spritesheet: 'arrowicons'}],
]);
const descriptors = (initialDescriptors as Map<string, Descriptor>);
export interface Descriptor {
position: string;
spritesheet: string;
isMask?: boolean;
coordinates?: {
x: number,
y: number,
};
invert?: boolean;
}
export interface SpriteSheet {
cellWidth: number;
cellHeight: number;
padding: number;
} | the_stack |
import "../Operator"
import * as AR from "../Collections/Immutable/Array"
import * as Chunk from "../Collections/Immutable/Chunk"
import * as Tp from "../Collections/Immutable/Tuple"
import * as HS from "../Collections/Mutable/HashSet"
import * as T from "../Effect"
import * as ES from "../Effect/ExecutionStrategy"
import * as Ex from "../Exit"
import * as F from "../Fiber"
import { pipe } from "../Function"
import * as M from "../Managed"
import * as RM from "../Managed/ReleaseMap"
import * as P from "../Promise"
import * as Q from "../Queue"
import { XQueueInternal } from "../Queue"
import * as Ref from "../Ref"
import * as AB from "../Support/AtomicBoolean"
import * as MQ from "../Support/MutableQueue"
import type * as InternalHub from "./_internal/Hub"
import * as HF from "./_internal/hubFactory"
import * as U from "./_internal/unsafe"
import * as PR from "./primitives"
import * as S from "./Strategy"
export type HubDequeue<R, E, A> = Q.XQueue<never, R, unknown, E, never, A>
export type HubEnqueue<R, E, A> = Q.XQueue<R, never, E, unknown, A, never>
export type Hub<A> = XHub<unknown, unknown, never, never, A, A>
export const HubTypeId = Symbol()
/**
* A `Hub<RA, RB, EA, EB, A, B>` is an asynchronous message hub. Publishers
* can publish messages of type `A` to the hub and subscribers can subscribe to
* take messages of type `B` from the hub. Publishing messages can require an
* environment of type `RA` and fail with an error of type `EA`. Taking
* messages can require an environment of type `RB` and fail with an error of
* type `EB`.
*/
export interface XHub<RA, RB, EA, EB, A, B> {
readonly typeId: typeof HubTypeId
readonly [PR._RA]: (_: RA) => void
readonly [PR._RB]: (_: RB) => void
readonly [PR._EA]: () => EA
readonly [PR._EB]: () => EB
readonly [PR._A]: (_: A) => void
readonly [PR._B]: () => B
}
export abstract class XHubInternal<RA, RB, EA, EB, A, B>
implements XHub<RA, RB, EA, EB, A, B>
{
readonly typeId: typeof HubTypeId = HubTypeId;
readonly [PR._RA]!: (_: RA) => void;
readonly [PR._RB]!: (_: RB) => void;
readonly [PR._EA]!: () => EA;
readonly [PR._EB]!: () => EB;
readonly [PR._A]!: (_: A) => void;
readonly [PR._B]!: () => B
/**
* Waits for the hub to be shut down.
*/
abstract awaitShutdown: T.UIO<void>
/**
* The maximum capacity of the hub.
*/
abstract capacity: number
/**
* Checks whether the hub is shut down.
*/
abstract isShutdown: T.UIO<boolean>
/**
* Publishes a message to the hub, returning whether the message was
* published to the hub.
*/
abstract publish(a: A): T.Effect<RA, EA, boolean>
/**
* Publishes all of the specified messages to the hub, returning whether
* they were published to the hub.
*/
abstract publishAll(as: Iterable<A>): T.Effect<RA, EA, boolean>
/**
* Shuts down the hub.
*/
abstract shutdown: T.UIO<void>
/**
* The current number of messages in the hub.
*/
abstract size: T.UIO<number>
/**
* Subscribes to receive messages from the hub. The resulting subscription
* can be evaluated multiple times within the scope of the managed to take a
* message from the hub each time.
*/
abstract subscribe: M.Managed<unknown, never, HubDequeue<RB, EB, B>>
}
/**
* @ets_optimize remove
*/
export function concrete<RA, RB, EA, EB, A, B>(
_: XHub<RA, RB, EA, EB, A, B>
): asserts _ is XHubInternal<RA, RB, EA, EB, A, B> {
//
}
/**
* Waits for the hub to be shut down.
*/
export function awaitShutdown<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>
): T.UIO<void> {
concrete(self)
return self.awaitShutdown
}
/**
* The maximum capacity of the hub.
*/
export function capacity<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>
): number {
concrete(self)
return self.capacity
}
/**
* Checks whether the hub is shut down.
*/
export function isShutdown<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>
): T.UIO<boolean> {
concrete(self)
return self.isShutdown
}
/**
* Publishes a message to the hub, returning whether the message was
* published to the hub.
*/
export function publish_<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>,
a: A
): T.Effect<RA, EA, boolean> {
concrete(self)
return self.publish(a)
}
/**
* Publishes a message to the hub, returning whether the message was
* published to the hub.
*
* @ets_data_first publish_
*/
export function publish<A>(a: A) {
return <RA, RB, EA, EB, B>(self: XHub<RA, RB, EA, EB, A, B>) => publish_(self, a)
}
/**
* Publishes all of the specified messages to the hub, returning whether
* they were published to the hub.
*/
export function publishAll_<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>,
as: Iterable<A>
): T.Effect<RA, EA, boolean> {
concrete(self)
return self.publishAll(as)
}
/**
* Publishes all of the specified messages to the hub, returning whether
* they were published to the hub.
*
* @ets_data_first publishAll_
*/
export function publishAll<A>(as: Iterable<A>) {
return <RA, RB, EA, EB, B>(self: XHub<RA, RB, EA, EB, A, B>) => publishAll_(self, as)
}
/**
* Shuts down the hub.
*/
export function shutdown<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>
): T.UIO<void> {
concrete(self)
return self.shutdown
}
/**
* The current number of messages in the hub.
*/
export function size<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>
): T.UIO<number> {
concrete(self)
return self.size
}
/**
* Subscribes to receive messages from the hub. The resulting subscription
* can be evaluated multiple times within the scope of the managed to take a
* message from the hub each time.
*/
export function subscribe<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>
): M.Managed<unknown, never, HubDequeue<RB, EB, B>> {
concrete(self)
return self.subscribe
}
/**
* Transforms messages published to the hub using the specified effectual
* function.
*/
export function contramapM_<RA, RB, RC, EA, EB, EC, A, B, C>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (c: C) => T.Effect<RC, EC, A>
): XHub<RC & RA, RB, EA | EC, EB, C, B> {
return dimapM_(self, f, T.succeed)
}
/**
* Transforms messages published to the hub using the specified effectual
* function.
*
* @ets_data_first contramapM_
*/
export function contramapM<RC, EC, A, C>(f: (c: C) => T.Effect<RC, EC, A>) {
return <RA, RB, EA, EB, B>(self: XHub<RA, RB, EA, EB, A, B>) => contramapM_(self, f)
}
/**
* Transforms messages published to and taken from the hub using the
* specified functions.
*/
export function dimap_<RA, RB, EA, EB, A, B, C, D>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (c: C) => A,
g: (b: B) => D
): XHub<RA, RB, EA, EB, C, D> {
return dimapM_(
self,
(c) => T.succeed(f(c)),
(b) => T.succeed(g(b))
)
}
/**
* Transforms messages published to and taken from the hub using the
* specified functions.
*
* @ets_data_first dimap_
*/
export function dimap<A, B, C, D>(f: (c: C) => A, g: (b: B) => D) {
return <RA, RB, EA, EB>(self: XHub<RA, RB, EA, EB, A, B>) => dimap_(self, f, g)
}
class DimapMImplementation<
RA,
RB,
RC,
RD,
EA,
EB,
EC,
ED,
A,
B,
C,
D
> extends XHubInternal<RC & RA, RD & RB, EA | EC, EB | ED, C, D> {
awaitShutdown: T.UIO<void>
capacity: number
isShutdown: T.UIO<boolean>
shutdown: T.UIO<void>
size: T.UIO<number>
subscribe: M.Managed<unknown, never, HubDequeue<RD & RB, ED | EB, D>>
constructor(
readonly source: XHubInternal<RA, RB, EA, EB, A, B>,
readonly f: (c: C) => T.Effect<RC, EC, A>,
g: (b: B) => T.Effect<RD, ED, D>
) {
super()
this.awaitShutdown = source.awaitShutdown
this.capacity = source.capacity
this.isShutdown = source.isShutdown
this.shutdown = source.shutdown
this.size = source.size
this.subscribe = M.map_(source.subscribe, Q.mapM(g))
}
publish(c: C) {
return T.chain_(this.f(c), (a) => this.source.publish(a))
}
publishAll(cs: Iterable<C>) {
return T.chain_(T.forEach_(cs, this.f), (as) => this.source.publishAll(as))
}
}
/**
* Transforms messages published to and taken from the hub using the
* specified effectual functions.
*/
export function dimapM_<RA, RB, RC, RD, EA, EB, EC, ED, A, B, C, D>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (c: C) => T.Effect<RC, EC, A>,
g: (b: B) => T.Effect<RD, ED, D>
): XHub<RC & RA, RD & RB, EA | EC, EB | ED, C, D> {
concrete(self)
return new DimapMImplementation(self, f, g)
}
/**
* Transforms messages published to and taken from the hub using the
* specified effectual functions.
*
* @ets_data_first dimapM_
*/
export function dimapM<A, B, C, D, EC, ED, RC, RD>(
f: (c: C) => T.Effect<RC, EC, A>,
g: (b: B) => T.Effect<RD, ED, D>
) {
return <RA, RB, EA, EB>(self: XHub<RA, RB, EA, EB, A, B>) => dimapM_(self, f, g)
}
class filterInputMImplementation<RA, RA1, RB, EA, EA1, EB, A, B> extends XHubInternal<
RA & RA1,
RB,
EA | EA1,
EB,
A,
B
> {
awaitShutdown: T.UIO<void>
capacity: number
isShutdown: T.UIO<boolean>
shutdown: T.UIO<void>
size: T.UIO<number>
subscribe: M.Managed<unknown, never, HubDequeue<RB, EB, B>>
constructor(
readonly source: XHubInternal<RA, RB, EA, EB, A, B>,
readonly f: (a: A) => T.Effect<RA1, EA1, boolean>
) {
super()
this.awaitShutdown = source.awaitShutdown
this.capacity = source.capacity
this.isShutdown = source.isShutdown
this.shutdown = source.shutdown
this.size = source.size
this.subscribe = source.subscribe
}
publish(a: A) {
return T.chain_(this.f(a), (b) => (b ? this.source.publish(a) : T.succeed(false)))
}
publishAll(as: Iterable<A>) {
return T.chain_(T.filter_(as, this.f), (as) =>
AR.isNonEmpty(as) ? this.source.publishAll(as) : T.succeed(false)
)
}
}
/**
* Filters messages published to the hub using the specified function.
*/
export function filterInput_<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (a: A) => boolean
) {
return filterInputM_(self, (a) => T.succeed(f(a)))
}
/**
* Filters messages published to the hub using the specified function.
*
* @ets_data_first filterInput_
*/
export function filterInput<A>(f: (a: A) => boolean) {
return <RA, RB, EA, EB, B>(self: XHub<RA, RB, EA, EB, A, B>) => filterInput_(self, f)
}
/**
* Filters messages published to the hub using the specified effectual
* function.
*/
export function filterInputM_<RA, RA1, RB, EA, EA1, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (a: A) => T.Effect<RA1, EA1, boolean>
): XHub<RA & RA1, RB, EA | EA1, EB, A, B> {
concrete(self)
return new filterInputMImplementation(self, f)
}
/**
* Filters messages published to the hub using the specified effectual
* function.
*
* @ets_data_first filterInputM_
*/
export function filterInputM<RA1, EA1, A>(f: (a: A) => T.Effect<RA1, EA1, boolean>) {
return <RA, RB, EA, EB, B>(self: XHub<RA, RB, EA, EB, A, B>) => filterInputM_(self, f)
}
/**
* Filters messages taken from the hub using the specified function.
*/
export function filterOutput_<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (b: B) => boolean
): XHub<RA, RB, EA, EB, A, B> {
return filterOutputM_(self, (b) => T.succeed(f(b)))
}
/**
* Filters messages taken from the hub using the specified function.
*
* @ets_data_first filterOutput_
*/
export function filterOutput<B>(f: (b: B) => boolean) {
return <RA, RB, EA, EB, A>(self: XHub<RA, RB, EA, EB, A, B>) => filterOutput_(self, f)
}
class filterOutputMImplementation<RA, RB, RB1, EA, EB, EB1, A, B> extends XHubInternal<
RA,
RB & RB1,
EA,
EB | EB1,
A,
B
> {
awaitShutdown: T.UIO<void>
capacity: number
isShutdown: T.UIO<boolean>
shutdown: T.UIO<void>
size: T.UIO<number>
subscribe: M.Managed<unknown, never, HubDequeue<RB & RB1, EB | EB1, B>>
constructor(
readonly source: XHubInternal<RA, RB, EA, EB, A, B>,
readonly f: (b: B) => T.Effect<RB1, EB1, boolean>
) {
super()
this.awaitShutdown = source.awaitShutdown
this.capacity = source.capacity
this.isShutdown = source.isShutdown
this.shutdown = source.shutdown
this.size = source.size
this.subscribe = M.map_(source.subscribe, Q.filterOutputM(f))
}
publish(a: A) {
return this.source.publish(a)
}
publishAll(as: Iterable<A>) {
return this.source.publishAll(as)
}
}
/**
* Filters messages taken from the hub using the specified effectual
* function.
*/
export function filterOutputM_<RA, RB, RB1, EA, EB, EB1, A, B>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (a: B) => T.Effect<RB1, EB1, boolean>
): XHub<RA, RB & RB1, EA, EB | EB1, A, B> {
concrete(self)
return new filterOutputMImplementation(self, f)
}
/**
* Filters messages taken from the hub using the specified effectual
* function.
*
* @ets_data_first filterOutputM_
*/
export function filterOutputM<RB1, EB1, B>(f: (a: B) => T.Effect<RB1, EB1, boolean>) {
return <RA, RB, EA, EB, A>(self: XHub<RA, RB, EA, EB, A, B>) =>
filterOutputM_(self, f)
}
/**
* Transforms messages taken from the hub using the specified function.
*/
export function map_<RA, RB, EA, EB, A, B, C>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (b: B) => C
): XHub<RA, RB, EA, EB, A, C> {
return mapM_(self, (b) => T.succeed(f(b)))
}
/**
* Transforms messages taken from the hub using the specified function.
*
* @ets_data_first map_
*/
export function map<B, C>(f: (b: B) => C) {
return <RA, RB, EA, EB, A>(self: XHub<RA, RB, EA, EB, A, B>) => map_(self, f)
}
/**
* Transforms messages taken from the hub using the specified effectual
* function.
*/
export function mapM_<RA, RB, RC, EA, EB, EC, A, B, C>(
self: XHub<RA, RB, EA, EB, A, B>,
f: (b: B) => T.Effect<RC, EC, C>
): XHub<RA, RC & RB, EA, EB | EC, A, C> {
return dimapM_(self, (a) => T.succeed<A>(a), f)
}
/**
* Transforms messages taken from the hub using the specified effectual
* function.
*
* @ets_data_first mapM_
*/
export function mapM<B, C, EC, RC>(f: (b: B) => T.Effect<RC, EC, C>) {
return <A, EA, EB, RA, RB>(self: XHub<RA, RB, EA, EB, A, B>) => mapM_(self, f)
}
class ToQueueImplementation<RA, RB, EA, EB, A, B> extends XQueueInternal<
RA,
never,
EA,
unknown,
A,
never
> {
awaitShutdown: T.UIO<void>
capacity: number
isShutdown: T.UIO<boolean>
shutdown: T.UIO<void>
size: T.UIO<number>
take: T.Effect<unknown, never, never>
takeAll: T.Effect<unknown, never, Chunk.Chunk<never>>
constructor(readonly source: XHubInternal<RA, RB, EA, EB, A, B>) {
super()
this.awaitShutdown = source.awaitShutdown
this.capacity = source.capacity
this.isShutdown = source.isShutdown
this.shutdown = source.shutdown
this.size = source.size
this.take = T.never
this.takeAll = T.succeed(Chunk.empty())
}
offer(a: A): T.Effect<RA, EA, boolean> {
return this.source.publish(a)
}
offerAll(as: Iterable<A>): T.Effect<RA, EA, boolean> {
return this.source.publishAll(as)
}
takeUpTo(): T.Effect<unknown, never, Chunk.Chunk<never>> {
return T.succeed(Chunk.empty())
}
}
/**
* Views the hub as a queue that can only be written to.
*/
export function toQueue<RA, RB, EA, EB, A, B>(
self: XHub<RA, RB, EA, EB, A, B>
): HubEnqueue<RA, EA, A> {
concrete(self)
return new ToQueueImplementation(self)
}
/**
* Creates a bounded hub with the back pressure strategy. The hub will retain
* messages until they have been taken by all subscribers, applying back
* pressure to publishers if the hub is at capacity.
*
* For best performance use capacities that are powers of two.
*/
export function makeBounded<A>(requestedCapacity: number): T.UIO<Hub<A>> {
return T.chain_(
T.succeedWith(() => HF.makeBounded<A>(requestedCapacity)),
(_) => makeHub(_, new S.BackPressure())
)
}
/**
* Creates a bounded hub with the back pressure strategy. The hub will retain
* messages until they have been taken by all subscribers, applying back
* pressure to publishers if the hub is at capacity.
*
* For best performance use capacities that are powers of two.
*/
export function unsafeMakeBounded<A>(requestedCapacity: number): Hub<A> {
const releaseMap = new RM.ReleaseMap(
Ref.unsafeMakeRef<RM.State>(new RM.Running(0, new Map()))
)
return unsafeMakeHub(
HF.makeBounded<A>(requestedCapacity),
makeSubscribersHashSet<A>(),
releaseMap,
P.unsafeMake<never, void>(F.None),
new AB.AtomicBoolean(false),
new S.BackPressure()
)
}
/**
* Creates a bounded hub with the dropping strategy. The hub will drop new
* messages if the hub is at capacity.
*
* For best performance use capacities that are powers of two.
*/
export function makeDropping<A>(requestedCapacity: number): T.UIO<Hub<A>> {
return T.chain_(
T.succeedWith(() => {
return HF.makeBounded<A>(requestedCapacity)
}),
(_) => makeHub(_, new S.Dropping())
)
}
/**
* Creates a bounded hub with the dropping strategy. The hub will drop new
* messages if the hub is at capacity.
*
* For best performance use capacities that are powers of two.
*/
export function unsafeMakeDropping<A>(requestedCapacity: number): Hub<A> {
const releaseMap = new RM.ReleaseMap(
Ref.unsafeMakeRef<RM.State>(new RM.Running(0, new Map()))
)
return unsafeMakeHub(
HF.makeBounded<A>(requestedCapacity),
makeSubscribersHashSet<A>(),
releaseMap,
P.unsafeMake<never, void>(F.None),
new AB.AtomicBoolean(false),
new S.Dropping()
)
}
/**
* Creates a bounded hub with the sliding strategy. The hub will add new
* messages and drop old messages if the hub is at capacity.
*
* For best performance use capacities that are powers of two.
*/
export function makeSliding<A>(requestedCapacity: number): T.UIO<Hub<A>> {
return T.chain_(
T.succeedWith(() => {
return HF.makeBounded<A>(requestedCapacity)
}),
(_) => makeHub(_, new S.Sliding())
)
}
/**
* Creates a bounded hub with the sliding strategy. The hub will add new
* messages and drop old messages if the hub is at capacity.
*
* For best performance use capacities that are powers of two.
*/
export function unsafeMakeSliding<A>(requestedCapacity: number): Hub<A> {
const releaseMap = new RM.ReleaseMap(
Ref.unsafeMakeRef<RM.State>(new RM.Running(0, new Map()))
)
return unsafeMakeHub(
HF.makeBounded<A>(requestedCapacity),
makeSubscribersHashSet<A>(),
releaseMap,
P.unsafeMake<never, void>(F.None),
new AB.AtomicBoolean(false),
new S.Sliding()
)
}
/**
* Creates an unbounded hub.
*/
export function makeUnbounded<A>(): T.UIO<Hub<A>> {
return T.chain_(
T.succeedWith(() => {
return HF.makeUnbounded<A>()
}),
(_) => makeHub(_, new S.Dropping())
)
}
/**
* Creates an unbounded hub.
*/
export function unsafeMakeUnbounded<A>(): Hub<A> {
const releaseMap = new RM.ReleaseMap(
Ref.unsafeMakeRef<RM.State>(new RM.Running(0, new Map()))
)
return unsafeMakeHub(
HF.makeUnbounded<A>(),
makeSubscribersHashSet<A>(),
releaseMap,
P.unsafeMake<never, void>(F.None),
new AB.AtomicBoolean(false),
new S.Dropping()
)
}
class UnsafeMakeHubImplementation<A> extends XHubInternal<
unknown,
unknown,
never,
never,
A,
A
> {
awaitShutdown: T.UIO<void>
capacity: number
isShutdown: T.UIO<boolean>
shutdown: T.UIO<void>
size: T.UIO<number>
subscribe: M.Managed<unknown, never, HubDequeue<unknown, never, A>>
constructor(
private hub: InternalHub.Hub<A>,
private subscribers: HS.HashSet<
Tp.Tuple<[InternalHub.Subscription<A>, MQ.MutableQueue<P.Promise<never, A>>]>
>,
releaseMap: RM.ReleaseMap,
shutdownHook: P.Promise<never, void>,
private shutdownFlag: AB.AtomicBoolean,
private strategy: S.Strategy<A>
) {
super()
this.awaitShutdown = P.await(shutdownHook)
this.capacity = hub.capacity
this.isShutdown = T.succeedWith(() => shutdownFlag.get)
this.shutdown = T.uninterruptible(
T.suspend((_, fiberId) => {
shutdownFlag.set(true)
return T.asUnit(
T.whenM_(
T.zipRight_(
RM.releaseAll(Ex.interrupt(fiberId), ES.parallel)(releaseMap),
strategy.shutdown
),
P.succeed_(shutdownHook, undefined)
)
)
})
)
this.size = T.suspend(() => {
if (shutdownFlag.get) {
return T.interrupt
}
return T.succeed(hub.size())
})
this.subscribe = pipe(
M.do,
M.bind("dequeue", () =>
T.toManaged(makeSubscription(hub, subscribers, strategy))
),
M.tap(({ dequeue }) =>
M.makeExit_(RM.add((_) => Q.shutdown(dequeue))(releaseMap), (finalizer, exit) =>
finalizer(exit)
)
),
M.map(({ dequeue }) => dequeue)
)
}
publish(a: A): T.Effect<unknown, never, boolean> {
return T.suspend(() => {
if (this.shutdownFlag.get) {
return T.interrupt
}
if (this.hub.publish(a)) {
this.strategy.unsafeCompleteSubscribers(this.hub, this.subscribers)
return T.succeed(true)
}
return this.strategy.handleSurplus(
this.hub,
this.subscribers,
Chunk.single(a),
this.shutdownFlag
)
})
}
publishAll(as: Iterable<A>): T.Effect<unknown, never, boolean> {
return T.suspend(() => {
if (this.shutdownFlag.get) {
return T.interrupt
}
const surplus = U.unsafePublishAll(this.hub, as)
this.strategy.unsafeCompleteSubscribers(this.hub, this.subscribers)
if (Chunk.isEmpty(surplus)) {
return T.succeed(true)
}
return this.strategy.handleSurplus(
this.hub,
this.subscribers,
surplus,
this.shutdownFlag
)
})
}
}
function makeHub<A>(hub: InternalHub.Hub<A>, strategy: S.Strategy<A>): T.UIO<Hub<A>> {
return T.chain_(RM.makeReleaseMap, (releaseMap) => {
return T.map_(P.make<never, void>(), (promise) => {
return unsafeMakeHub(
hub,
makeSubscribersHashSet<A>(),
releaseMap,
promise,
new AB.AtomicBoolean(false),
strategy
)
})
})
}
/**
* Unsafely creates a hub with the specified strategy.
*/
function unsafeMakeHub<A>(
hub: InternalHub.Hub<A>,
subscribers: HS.HashSet<
Tp.Tuple<[InternalHub.Subscription<A>, MQ.MutableQueue<P.Promise<never, A>>]>
>,
releaseMap: RM.ReleaseMap,
shutdownHook: P.Promise<never, void>,
shutdownFlag: AB.AtomicBoolean,
strategy: S.Strategy<A>
): Hub<A> {
return new UnsafeMakeHubImplementation(
hub,
subscribers,
releaseMap,
shutdownHook,
shutdownFlag,
strategy
)
}
/**
* Creates a subscription with the specified strategy.
*/
function makeSubscription<A>(
hub: InternalHub.Hub<A>,
subscribers: HS.HashSet<
Tp.Tuple<[InternalHub.Subscription<A>, MQ.MutableQueue<P.Promise<never, A>>]>
>,
strategy: S.Strategy<A>
): T.UIO<Q.Dequeue<A>> {
return T.map_(P.make<never, void>(), (promise) => {
return unsafeMakeSubscription(
hub,
subscribers,
hub.subscribe(),
new MQ.Unbounded<P.Promise<never, A>>(),
promise,
new AB.AtomicBoolean(false),
strategy
)
})
}
class UnsafeMakeSubscriptionImplementation<A> extends XQueueInternal<
never,
unknown,
unknown,
never,
never,
A
> {
constructor(
private hub: InternalHub.Hub<A>,
private subscribers: HS.HashSet<
Tp.Tuple<[InternalHub.Subscription<A>, MQ.MutableQueue<P.Promise<never, A>>]>
>,
private subscription: InternalHub.Subscription<A>,
private pollers: MQ.MutableQueue<P.Promise<never, A>>,
private shutdownHook: P.Promise<never, void>,
private shutdownFlag: AB.AtomicBoolean,
private strategy: S.Strategy<A>
) {
super()
}
awaitShutdown: T.UIO<void> = P.await(this.shutdownHook)
capacity: number = this.hub.capacity
isShutdown: T.UIO<boolean> = T.succeedWith(() => this.shutdownFlag.get)
shutdown: T.UIO<void> = T.uninterruptible(
T.suspend((_, fiberId) => {
this.shutdownFlag.set(true)
return T.asUnit(
T.whenM_(
T.zipRight_(
T.forEachPar_(U.unsafePollAllQueue(this.pollers), (_) => {
return P.interruptAs(fiberId)(_)
}),
T.succeedWith(() => this.subscription.unsubscribe())
),
P.succeed_(this.shutdownHook, undefined)
)
)
})
)
size: T.UIO<number> = T.suspend(() => {
if (this.shutdownFlag.get) {
return T.interrupt
}
return T.succeed(this.subscription.size())
})
offer(_: never): T.Effect<never, unknown, boolean> {
return T.succeed(false)
}
offerAll(_: Iterable<never>): T.Effect<never, unknown, boolean> {
return T.succeed(false)
}
take: T.Effect<unknown, never, A> = T.suspend((_, fiberId) => {
if (this.shutdownFlag.get) {
return T.interrupt
}
const empty = null as unknown as A
const message = this.pollers.isEmpty ? this.subscription.poll(empty) : empty
if (message === null) {
const promise = P.unsafeMake<never, A>(fiberId)
return T.onInterrupt_(
T.suspend(() => {
this.pollers.offer(promise)
this.subscribers.add(Tp.tuple(this.subscription, this.pollers))
this.strategy.unsafeCompletePollers(
this.hub,
this.subscribers,
this.subscription,
this.pollers
)
if (this.shutdownFlag.get) {
return T.interrupt
} else {
return P.await(promise)
}
}),
() =>
T.succeedWith(() => {
U.unsafeRemove(this.pollers, promise)
})
)
} else {
this.strategy.unsafeOnHubEmptySpace(this.hub, this.subscribers)
return T.succeed(message)
}
})
takeAll: T.Effect<unknown, never, Chunk.Chunk<A>> = T.suspend(() => {
if (this.shutdownFlag.get) {
return T.interrupt
}
const as = this.pollers.isEmpty
? U.unsafePollAllSubscription(this.subscription)
: Chunk.empty<A>()
this.strategy.unsafeOnHubEmptySpace(this.hub, this.subscribers)
return T.succeed(as)
})
takeUpTo(n: number): T.Effect<unknown, never, Chunk.Chunk<A>> {
return T.suspend(() => {
if (this.shutdownFlag.get) {
return T.interrupt
}
const as = this.pollers.isEmpty
? U.unsafePollN(this.subscription, n)
: Chunk.empty<A>()
this.strategy.unsafeOnHubEmptySpace(this.hub, this.subscribers)
return T.succeed(as)
})
}
}
/**
* Unsafely creates a subscription with the specified strategy.
*/
function unsafeMakeSubscription<A>(
hub: InternalHub.Hub<A>,
subscribers: HS.HashSet<
Tp.Tuple<[InternalHub.Subscription<A>, MQ.MutableQueue<P.Promise<never, A>>]>
>,
subscription: InternalHub.Subscription<A>,
pollers: MQ.MutableQueue<P.Promise<never, A>>,
shutdownHook: P.Promise<never, void>,
shutdownFlag: AB.AtomicBoolean,
strategy: S.Strategy<A>
): Q.Dequeue<A> {
return new UnsafeMakeSubscriptionImplementation(
hub,
subscribers,
subscription,
pollers,
shutdownHook,
shutdownFlag,
strategy
)
}
function makeSubscribersHashSet<A>(): HS.HashSet<
Tp.Tuple<[InternalHub.Subscription<A>, MQ.MutableQueue<P.Promise<never, A>>]>
> {
return HS.make<
Tp.Tuple<[InternalHub.Subscription<A>, MQ.MutableQueue<P.Promise<never, A>>]>
>()
} | the_stack |
import './VSlideGroup.sass'
// Components
import VIcon from '../VIcon'
import { VFadeTransition } from '../transitions'
// Extensions
import { BaseItemGroup } from '../VItemGroup/VItemGroup'
// Mixins
import Mobile from '../../mixins/mobile'
// Directives
import Resize from '../../directives/resize'
import Touch from '../../directives/touch'
// Utilities
import mixins, { ExtractVue } from '../../util/mixins'
// Types
import Vue, { VNode } from 'vue'
interface TouchEvent {
touchstartX: number
touchmoveX: number
stopPropagation: Function
}
interface Widths {
content: number
wrapper: number
}
interface options extends Vue {
$refs: {
content: HTMLElement
wrapper: HTMLElement
}
}
export const BaseSlideGroup = mixins<options &
/* eslint-disable indent */
ExtractVue<[
typeof BaseItemGroup,
typeof Mobile,
]>
/* eslint-enable indent */
>(
BaseItemGroup,
Mobile,
/* @vue/component */
).extend({
name: 'base-slide-group',
directives: {
Resize,
Touch,
},
props: {
activeClass: {
type: String,
default: 'v-slide-item--active',
},
centerActive: Boolean,
nextIcon: {
type: String,
default: '$next',
},
prevIcon: {
type: String,
default: '$prev',
},
showArrows: {
type: [Boolean, String],
validator: v => (
typeof v === 'boolean' || [
'always',
'desktop',
'mobile',
].includes(v)
),
},
},
data: () => ({
internalItemsLength: 0,
isOverflowing: false,
resizeTimeout: 0,
startX: 0,
scrollOffset: 0,
widths: {
content: 0,
wrapper: 0,
},
}),
computed: {
__cachedNext (): VNode {
return this.genTransition('next')
},
__cachedPrev (): VNode {
return this.genTransition('prev')
},
classes (): object {
return {
...BaseItemGroup.options.computed.classes.call(this),
'v-slide-group': true,
'v-slide-group--has-affixes': this.hasAffixes,
'v-slide-group--is-overflowing': this.isOverflowing,
}
},
hasAffixes (): Boolean {
switch (this.showArrows) {
// Always show arrows on desktop & mobile
case 'always': return true
// Always show arrows on desktop
case 'desktop': return !this.isMobile
// Show arrows on mobile when overflowing.
// This matches the default 2.2 behavior
case true: return this.isOverflowing || Math.abs(this.scrollOffset) > 0
// Always show on mobile
case 'mobile': return (
this.isMobile ||
(this.isOverflowing || Math.abs(this.scrollOffset) > 0)
)
// https://material.io/components/tabs#scrollable-tabs
// Always show arrows when
// overflowed on desktop
default: return (
!this.isMobile &&
(this.isOverflowing || Math.abs(this.scrollOffset) > 0)
)
}
},
hasNext (): boolean {
if (!this.hasAffixes) return false
const { content, wrapper } = this.widths
// Check one scroll ahead to know the width of right-most item
return content > Math.abs(this.scrollOffset) + wrapper
},
hasPrev (): boolean {
return this.hasAffixes && this.scrollOffset !== 0
},
},
watch: {
internalValue: 'setWidths',
// When overflow changes, the arrows alter
// the widths of the content and wrapper
// and need to be recalculated
isOverflowing: 'setWidths',
scrollOffset (val) {
this.$refs.content.style.transform = `translateX(${-val}px)`
},
},
beforeUpdate () {
this.internalItemsLength = (this.$children || []).length
},
updated () {
if (this.internalItemsLength === (this.$children || []).length) return
this.setWidths()
},
methods: {
// Always generate next for scrollable hint
genNext (): VNode | null {
const slot = this.$scopedSlots.next
? this.$scopedSlots.next({})
: this.$slots.next || this.__cachedNext
return this.$createElement('div', {
staticClass: 'v-slide-group__next',
class: {
'v-slide-group__next--disabled': !this.hasNext,
},
on: {
click: () => this.onAffixClick('next'),
},
key: 'next',
}, [slot])
},
genContent (): VNode {
return this.$createElement('div', {
staticClass: 'v-slide-group__content',
ref: 'content',
}, this.$slots.default)
},
genData (): object {
return {
class: this.classes,
directives: [{
name: 'resize',
value: this.onResize,
}],
}
},
genIcon (location: 'prev' | 'next'): VNode | null {
let icon = location
if (this.$vuetify.rtl && location === 'prev') {
icon = 'next'
} else if (this.$vuetify.rtl && location === 'next') {
icon = 'prev'
}
const upperLocation = `${location[0].toUpperCase()}${location.slice(1)}`
const hasAffix = (this as any)[`has${upperLocation}`]
if (
!this.showArrows &&
!hasAffix
) return null
return this.$createElement(VIcon, {
props: {
disabled: !hasAffix,
},
}, (this as any)[`${icon}Icon`])
},
// Always generate prev for scrollable hint
genPrev (): VNode | null {
const slot = this.$scopedSlots.prev
? this.$scopedSlots.prev({})
: this.$slots.prev || this.__cachedPrev
return this.$createElement('div', {
staticClass: 'v-slide-group__prev',
class: {
'v-slide-group__prev--disabled': !this.hasPrev,
},
on: {
click: () => this.onAffixClick('prev'),
},
key: 'prev',
}, [slot])
},
genTransition (location: 'prev' | 'next') {
return this.$createElement(VFadeTransition, [this.genIcon(location)])
},
genWrapper (): VNode {
return this.$createElement('div', {
staticClass: 'v-slide-group__wrapper',
directives: [{
name: 'touch',
value: {
start: (e: TouchEvent) => this.overflowCheck(e, this.onTouchStart),
move: (e: TouchEvent) => this.overflowCheck(e, this.onTouchMove),
end: (e: TouchEvent) => this.overflowCheck(e, this.onTouchEnd),
},
}],
ref: 'wrapper',
}, [this.genContent()])
},
calculateNewOffset (direction: 'prev' | 'next', widths: Widths, rtl: boolean, currentScrollOffset: number) {
const sign = rtl ? -1 : 1
const newAbosluteOffset = sign * currentScrollOffset +
(direction === 'prev' ? -1 : 1) * widths.wrapper
return sign * Math.max(Math.min(newAbosluteOffset, widths.content - widths.wrapper), 0)
},
onAffixClick (location: 'prev' | 'next') {
this.$emit(`click:${location}`)
this.scrollTo(location)
},
onResize () {
/* istanbul ignore next */
if (this._isDestroyed) return
this.setWidths()
},
onTouchStart (e: TouchEvent) {
const { content } = this.$refs
this.startX = this.scrollOffset + e.touchstartX as number
content.style.setProperty('transition', 'none')
content.style.setProperty('willChange', 'transform')
},
onTouchMove (e: TouchEvent) {
this.scrollOffset = this.startX - e.touchmoveX
},
onTouchEnd () {
const { content, wrapper } = this.$refs
const maxScrollOffset = content.clientWidth - wrapper.clientWidth
content.style.setProperty('transition', null)
content.style.setProperty('willChange', null)
if (this.$vuetify.rtl) {
/* istanbul ignore else */
if (this.scrollOffset > 0 || !this.isOverflowing) {
this.scrollOffset = 0
} else if (this.scrollOffset <= -maxScrollOffset) {
this.scrollOffset = -maxScrollOffset
}
} else {
/* istanbul ignore else */
if (this.scrollOffset < 0 || !this.isOverflowing) {
this.scrollOffset = 0
} else if (this.scrollOffset >= maxScrollOffset) {
this.scrollOffset = maxScrollOffset
}
}
},
overflowCheck (e: TouchEvent, fn: (e: TouchEvent) => void) {
e.stopPropagation()
this.isOverflowing && fn(e)
},
scrollIntoView /* istanbul ignore next */ () {
if (!this.selectedItem && this.items.length) {
const lastItemPosition = this.items[this.items.length - 1].$el.getBoundingClientRect()
const wrapperPosition = this.$refs.wrapper.getBoundingClientRect()
if (
(this.$vuetify.rtl && wrapperPosition.right < lastItemPosition.right) ||
(!this.$vuetify.rtl && wrapperPosition.left > lastItemPosition.left)
) {
this.scrollTo('prev')
}
}
if (!this.selectedItem) {
return
}
if (
this.selectedIndex === 0 ||
(!this.centerActive && !this.isOverflowing)
) {
this.scrollOffset = 0
} else if (this.centerActive) {
this.scrollOffset = this.calculateCenteredOffset(
this.selectedItem.$el as HTMLElement,
this.widths,
this.$vuetify.rtl
)
} else if (this.isOverflowing) {
this.scrollOffset = this.calculateUpdatedOffset(
this.selectedItem.$el as HTMLElement,
this.widths,
this.$vuetify.rtl,
this.scrollOffset
)
}
},
calculateUpdatedOffset (selectedElement: HTMLElement, widths: Widths, rtl: boolean, currentScrollOffset: number): number {
const clientWidth = selectedElement.clientWidth
const offsetLeft = rtl
? (widths.content - selectedElement.offsetLeft - clientWidth)
: selectedElement.offsetLeft
if (rtl) {
currentScrollOffset = -currentScrollOffset
}
const totalWidth = widths.wrapper + currentScrollOffset
const itemOffset = clientWidth + offsetLeft
const additionalOffset = clientWidth * 0.4
if (offsetLeft <= currentScrollOffset) {
currentScrollOffset = Math.max(offsetLeft - additionalOffset, 0)
} else if (totalWidth <= itemOffset) {
currentScrollOffset = Math.min(currentScrollOffset - (totalWidth - itemOffset - additionalOffset), widths.content - widths.wrapper)
}
return rtl ? -currentScrollOffset : currentScrollOffset
},
calculateCenteredOffset (selectedElement: HTMLElement, widths: Widths, rtl: boolean): number {
const { offsetLeft, clientWidth } = selectedElement
if (rtl) {
const offsetCentered = widths.content - offsetLeft - clientWidth / 2 - widths.wrapper / 2
return -Math.min(widths.content - widths.wrapper, Math.max(0, offsetCentered))
} else {
const offsetCentered = offsetLeft + clientWidth / 2 - widths.wrapper / 2
return Math.min(widths.content - widths.wrapper, Math.max(0, offsetCentered))
}
},
scrollTo /* istanbul ignore next */ (location: 'prev' | 'next') {
this.scrollOffset = this.calculateNewOffset(location, {
// Force reflow
content: this.$refs.content ? this.$refs.content.clientWidth : 0,
wrapper: this.$refs.wrapper ? this.$refs.wrapper.clientWidth : 0,
}, this.$vuetify.rtl, this.scrollOffset)
},
setWidths /* istanbul ignore next */ () {
window.requestAnimationFrame(() => {
const { content, wrapper } = this.$refs
this.widths = {
content: content ? content.clientWidth : 0,
wrapper: wrapper ? wrapper.clientWidth : 0,
}
this.isOverflowing = this.widths.wrapper < this.widths.content
this.scrollIntoView()
})
},
},
render (h): VNode {
return h('div', this.genData(), [
this.genPrev(),
this.genWrapper(),
this.genNext(),
])
},
})
export default BaseSlideGroup.extend({
name: 'v-slide-group',
provide (): object {
return {
slideGroup: this,
}
},
}) | the_stack |
namespace LiteMol.Viewer.PDBe.Validation {
import Entity = Bootstrap.Entity;
import Transformer = Bootstrap.Entity.Transformer;
export interface Report extends Entity<Entity.Behaviour.Props<Interactivity.Behaviour>> { }
export const Report = Entity.create<Entity.Behaviour.Props<Interactivity.Behaviour>>({ name: 'PDBe Molecule Validation Report', typeClass: 'Behaviour', shortName: 'VR', description: 'Represents PDBe validation report.' });
export namespace Api {
export function getResidueId(seqNumber: number, insCode: string | null) {
var id = seqNumber.toString();
if ((insCode || "").length !== 0 && insCode !== " ") id += " " + insCode;
return id;
}
export function getEntry(report: any, modelId: string, entity: string, asymId: string, residueId: string) {
let e = report[entity];
if (!e) return void 0;
e = e[asymId];
if (!e) return void 0;
e = e[modelId];
if (!e) return void 0;
return e[residueId];
}
export function createReport(data: any) {
const report: any = {};
if (!data.molecules) return report;
for (const entity of data.molecules) {
const chains: any = report[entity.entity_id.toString()] || {};
for (const chain of entity.chains) {
const models: any = chains[chain.struct_asym_id] || {};
for (const model of chain.models) {
const residues: any = models[model.model_id.toString()] || {};
for (const residue of model.residues) {
const id = getResidueId(residue.residue_number, residue.author_insertion_code),
entry = residues[id];
if (entry) {
entry.residues.push(residue);
entry.numIssues = Math.max(entry.numIssues, residue.outlier_types.length);
} else {
residues[id] = {
residues: [residue],
numIssues: residue.outlier_types.length
};
}
}
models[model.model_id.toString()] = residues;
}
chains[chain.struct_asym_id] = models;
}
report[entity.entity_id.toString()] = chains;
}
return report;
}
}
export namespace Interactivity {
export class Behaviour implements Bootstrap.Behaviour.Dynamic {
private provider: Bootstrap.Interactivity.HighlightProvider;
dispose() {
this.context.highlight.removeProvider(this.provider);
}
register(behaviour: any) {
this.context.highlight.addProvider(this.provider);
}
private processInfo(info: Bootstrap.Interactivity.Info): string | undefined {
const i = Bootstrap.Interactivity.Molecule.transformInteraction(info);
if (!i || i.residues.length !== 1) return void 0;
const r = i.residues[0];
const e = Api.getEntry(this.report, i.modelId, r.chain.entity.entityId, r.chain.asymId, Api.getResidueId(r.seqNumber, r.insCode));
if (!e) return void 0;
let label: string;
if (e.residues.length === 1) {
const vr = e.residues[0];
label = 'Validation: ';
if (!vr.outlier_types.length) label += 'no issue';
else label += `<b>${e.residues[0].outlier_types.join(", ")}</b>`;
return label;
} else {
label = '';
let index = 0;
for (const v of e.residues) {
if (index > 0) label += ', ';
label += `Validation (altLoc ${v.alt_code}): <b>${v.outlier_types.join(", ")}</b>`;
index++;
}
return label;
}
}
constructor(public context: Bootstrap.Context, public report: any) {
this.provider = info => {
try {
return this.processInfo(info);
} catch (e) {
console.error('Error showing validation label', e);
return void 0;
}
};
}
}
}
namespace Theme {
const colorMap = (function () {
const colors = Core.Utils.FastMap.create<number, LiteMol.Visualization.Color>();
colors.set(0, { r: 0, g: 1, b: 0 });
colors.set(1, { r: 1, g: 1, b: 0 });
colors.set(2, { r: 1, g: 0.5, b: 0 });
colors.set(3, { r: 1, g: 0, b: 0 });
colors.set(4, { r: 0.7, g: 0.7, b: 0.7 }); // not applicable
return colors;
})();
const defaultColor = <LiteMol.Visualization.Color>{ r: 0.6, g: 0.6, b: 0.6 };
const selectionColor = <LiteMol.Visualization.Color>{ r: 0, g: 0, b: 1 };
const highlightColor = <LiteMol.Visualization.Color>{ r: 1, g: 0, b: 1 };
function createResidueMapNormal(model: LiteMol.Core.Structure.Molecule.Model, report: any) {
const map = new Uint8Array(model.data.residues.count);
const mId = model.modelId;
const { asymId, entityId, seqNumber, insCode, isHet } = model.data.residues;
for (let i = 0, _b = model.data.residues.count; i < _b; i++) {
const entry = Api.getEntry(report, mId, entityId[i], asymId[i], Api.getResidueId(seqNumber[i], insCode[i]));
if (entry) {
map[i] = Math.min(entry.numIssues, 3);
} else if (isHet[i]) {
map[i] = 4;
}
}
return map;
}
function createResidueMapComputed(model: LiteMol.Core.Structure.Molecule.Model, report: any) {
const map = new Uint8Array(model.data.residues.count);
const mId = model.modelId;
const parent = model.parent!;
const { entityId, seqNumber, insCode, chainIndex, isHet } = model.data.residues;
const { sourceChainIndex } = model.data.chains;
const { asymId } = parent.data.chains;
for (let i = 0, _b = model.data.residues.count; i < _b; i++) {
const aId = asymId[sourceChainIndex![chainIndex[i]]];
const e = Api.getEntry(report, mId, entityId[i], aId, Api.getResidueId(seqNumber[i], insCode[i]));
if (e) {
map[i] = Math.min(e.numIssues, 3);
} else if (isHet[i]) {
map[i] = 4;
}
}
return map;
}
export function create(entity: Bootstrap.Entity.Molecule.Model, report: any) {
const model = entity.props.model;
const map = model.source === Core.Structure.Molecule.Model.Source.File
? createResidueMapNormal(model, report)
: createResidueMapComputed(model, report);
const colors = Core.Utils.FastMap.create<string, LiteMol.Visualization.Color>();
colors.set('Uniform', defaultColor)
colors.set('Selection', selectionColor)
colors.set('Highlight', highlightColor);
const residueIndex = model.data.atoms.residueIndex;
const mapping = Visualization.Theme.createColorMapMapping(i => map[residueIndex[i]], colorMap, defaultColor);
return Visualization.Theme.createMapping(mapping, { colors, interactive: true, transparency: { alpha: 1.0 } });
}
}
const Create = Bootstrap.Tree.Transformer.create<Entity.Data.String, Report, { id?: string }>({
id: 'pdbe-validation-create',
name: 'PDBe Validation',
description: 'Create the validation report from a string.',
from: [Entity.Data.String],
to: [Report],
defaultParams: () => ({})
}, (context, a, t) => {
return Bootstrap.Task.create<Report>(`Validation Report (${t.params.id})`, 'Normal', async ctx => {
await ctx.updateProgress('Parsing...');
const data = JSON.parse(a.props.data);
const model = data[t.params.id!];
const report = Api.createReport(model || {});
return Report.create(t, { label: 'Validation Report', behaviour: new Interactivity.Behaviour(context, report) });
}).setReportTime(true);
}
);
export const DownloadAndCreate = Bootstrap.Tree.Transformer.action<Entity.Molecule.Molecule, Entity.Action, { reportRef?: string }>({
id: 'pdbe-validation-download-and-create',
name: 'PDBe Validation Report',
description: 'Download Validation Report from PDBe',
from: [Entity.Molecule.Molecule],
to: [Entity.Action],
defaultParams: () => ({})
}, (context, a, t) => {
const id = a.props.molecule.id.trim().toLocaleLowerCase();
const action = Bootstrap.Tree.Transform.build()
.add(a, Transformer.Data.Download, { url: `https://www.ebi.ac.uk/pdbe/api/validation/residuewise_outlier_summary/entry/${id}`, type: 'String', id, description: 'Validation Data', title: 'Validation' })
.then(Create, { id }, { isBinding: true, ref: t.params.reportRef });
return action;
}, "Validation report loaded. Hovering over residue will now contain validation info. To apply validation coloring, select the entity in the tree and apply it the right panel.");
export const ApplyTheme = Bootstrap.Tree.Transformer.create<Report, Entity.Action, { }>({
id: 'pdbe-validation-apply-theme',
name: 'Apply Coloring',
description: 'Colors all visuals using the validation report.',
from: [Report],
to: [Entity.Action],
defaultParams: () => ({})
}, (context, a, t) => {
return Bootstrap.Task.create<Entity.Action>('Validation Coloring', 'Background', async ctx => {
const molecule = Bootstrap.Tree.Node.findAncestor(a, Bootstrap.Entity.Molecule.Molecule);
if (!molecule) {
throw 'No suitable parent found.';
}
const themes = Core.Utils.FastMap.create<number, Visualization.Theme>();
const visuals = context.select(Bootstrap.Tree.Selection.byValue(molecule).subtree().ofType(Bootstrap.Entity.Molecule.Visual));
for (const v of visuals) {
const model = Bootstrap.Utils.Molecule.findModel(v);
if (!model) continue;
let theme = themes.get(model.id);
if (!theme) {
theme = Theme.create(model, a.props.behaviour.report);
themes.set(model.id, theme);
}
Bootstrap.Command.Visual.UpdateBasicTheme.dispatch(context, { visual: v as any, theme });
}
context.logger.message('Validation coloring applied.');
return Bootstrap.Tree.Node.Null;
});
});
} | the_stack |
import * as bs from "binary-search-bounds";
import PriorityQueue from "priorityqueuejs";
import semaphore from "semaphore";
import { ClientContext } from "../ClientContext";
import { logger } from "../common/logger";
import { StatusCodes, SubStatusCodes } from "../common/statusCodes";
import { FeedOptions, Response } from "../request";
import { PartitionedQueryExecutionInfo } from "../request/ErrorResponse";
import { QueryRange } from "../routing/QueryRange";
import { PARITIONKEYRANGE, SmartRoutingMapProvider } from "../routing/smartRoutingMapProvider";
import { CosmosHeaders } from "./CosmosHeaders";
import { DocumentProducer } from "./documentProducer";
import { ExecutionContext } from "./ExecutionContext";
import { getInitialHeader, mergeHeaders } from "./headerUtils";
/** @hidden */
const log = logger("parallelQueryExecutionContextBase");
/** @hidden */
export enum ParallelQueryExecutionContextBaseStates {
started = "started",
inProgress = "inProgress",
ended = "ended"
}
/** @hidden */
export abstract class ParallelQueryExecutionContextBase implements ExecutionContext {
private static readonly DEFAULT_PAGE_SIZE = 10;
private err: any;
private state: any;
private static STATES = ParallelQueryExecutionContextBaseStates;
private routingProvider: SmartRoutingMapProvider;
protected sortOrders: any;
private pageSize: any;
private requestContinuation: any;
private respHeaders: CosmosHeaders;
private orderByPQ: PriorityQueue<DocumentProducer>;
private sem: any;
private waitingForInternalExecutionContexts: number;
/**
* Provides the ParallelQueryExecutionContextBase.
* This is the base class that ParallelQueryExecutionContext and OrderByQueryExecutionContext will derive from.
*
* When handling a parallelized query, it instantiates one instance of
* DocumentProcuder per target partition key range and aggregates the result of each.
*
* @constructor ParallelQueryExecutionContext
* @param {ClientContext} clientContext - The service endpoint to use to create the client.
* @param {string} collectionLink - The Collection Link
* @param {FeedOptions} [options] - Represents the feed options.
* @param {object} partitionedQueryExecutionInfo - PartitionedQueryExecutionInfo
* @ignore
*/
constructor(
private clientContext: ClientContext,
private collectionLink: string,
private query: any, // TODO: any - It's not SQLQuerySpec
private options: FeedOptions,
private partitionedQueryExecutionInfo: PartitionedQueryExecutionInfo
) {
this.clientContext = clientContext;
this.collectionLink = collectionLink;
this.query = query;
this.options = options;
this.partitionedQueryExecutionInfo = partitionedQueryExecutionInfo;
this.err = undefined;
this.state = ParallelQueryExecutionContextBase.STATES.started;
this.routingProvider = new SmartRoutingMapProvider(this.clientContext);
this.sortOrders = this.partitionedQueryExecutionInfo.queryInfo.orderBy;
if (options === undefined || options["maxItemCount"] === undefined) {
this.pageSize = ParallelQueryExecutionContextBase.DEFAULT_PAGE_SIZE;
this.options["maxItemCount"] = this.pageSize;
} else {
this.pageSize = options["maxItemCount"];
}
this.requestContinuation = options ? options.continuation : null;
// response headers of undergoing operation
this.respHeaders = getInitialHeader();
// Make priority queue for documentProducers
// The comparator is supplied by the derived class
this.orderByPQ = new PriorityQueue<DocumentProducer>((a: DocumentProducer, b: DocumentProducer) =>
this.documentProducerComparator(b, a)
);
// Creating the documentProducers
this.sem = semaphore(1);
// Creating callback for semaphore
// TODO: Code smell
const createDocumentProducersAndFillUpPriorityQueueFunc = async () => {
// ensure the lock is released after finishing up
try {
const targetPartitionRanges = await this._onTargetPartitionRanges();
this.waitingForInternalExecutionContexts = targetPartitionRanges.length;
// default to 1 if 0 or undefined is provided.
const maxDegreeOfParallelism =
options.maxDegreeOfParallelism === 0 || options.maxDegreeOfParallelism === undefined
? 1
: // use maximum parallelism if -1 (or less) is provided
options.maxDegreeOfParallelism > 0
? Math.min(options.maxDegreeOfParallelism + 1, targetPartitionRanges.length)
: targetPartitionRanges.length;
log.info(
"Query starting against " +
targetPartitionRanges.length +
" ranges with parallelism of " +
maxDegreeOfParallelism
);
const parallelismSem = semaphore(maxDegreeOfParallelism);
let filteredPartitionKeyRanges = [];
// The document producers generated from filteredPartitionKeyRanges
const targetPartitionQueryExecutionContextList: DocumentProducer[] = [];
if (this.requestContinuation) {
// Need to create the first documentProducer with the suppliedCompositeContinuationToken
try {
const suppliedCompositeContinuationToken = JSON.parse(this.requestContinuation);
filteredPartitionKeyRanges = this.getPartitionKeyRangesForContinuation(
suppliedCompositeContinuationToken,
targetPartitionRanges
);
if (filteredPartitionKeyRanges.length > 0) {
targetPartitionQueryExecutionContextList.push(
this._createTargetPartitionQueryExecutionContext(
filteredPartitionKeyRanges[0],
suppliedCompositeContinuationToken.token
)
);
// Slicing the first element off, since we already made a documentProducer for it
filteredPartitionKeyRanges = filteredPartitionKeyRanges.slice(1);
}
} catch (e) {
this.err = e;
this.sem.leave();
}
} else {
filteredPartitionKeyRanges = targetPartitionRanges;
}
// Create one documentProducer for each partitionTargetRange
filteredPartitionKeyRanges.forEach((partitionTargetRange: any) => {
// TODO: any partitionTargetRange
// no async callback
targetPartitionQueryExecutionContextList.push(
this._createTargetPartitionQueryExecutionContext(partitionTargetRange)
);
});
// Fill up our priority queue with documentProducers
targetPartitionQueryExecutionContextList.forEach(documentProducer => {
// has async callback
const throttledFunc = async () => {
try {
const { result: document, headers } = await documentProducer.current();
this._mergeWithActiveResponseHeaders(headers);
if (document === undefined) {
// no results on this one
return;
}
// if there are matching results in the target ex range add it to the priority queue
try {
this.orderByPQ.enq(documentProducer);
} catch (e) {
this.err = e;
}
} catch (err) {
this._mergeWithActiveResponseHeaders(err.headers);
this.err = err;
} finally {
parallelismSem.leave();
this._decrementInitiationLock();
}
};
parallelismSem.take(throttledFunc);
});
} catch (err) {
this.err = err;
// release the lock
this.sem.leave();
return;
}
};
this.sem.take(createDocumentProducersAndFillUpPriorityQueueFunc);
}
protected abstract documentProducerComparator(dp1: DocumentProducer, dp2: DocumentProducer): number;
// TODO: any TODO: any
public getPartitionKeyRangesForContinuation(suppliedCompositeContinuationToken: any, partitionKeyRanges: any) {
const startRange: any = {}; // TODO: any
startRange[PARITIONKEYRANGE.MinInclusive] = suppliedCompositeContinuationToken.range.min;
startRange[PARITIONKEYRANGE.MaxExclusive] = suppliedCompositeContinuationToken.range.max;
const vbCompareFunction = (x: any, y: any) => {
// TODO: any
if (x[PARITIONKEYRANGE.MinInclusive] > y[PARITIONKEYRANGE.MinInclusive]) {
return 1;
}
if (x[PARITIONKEYRANGE.MinInclusive] < y[PARITIONKEYRANGE.MinInclusive]) {
return -1;
}
return 0;
};
const minIndex = bs.le(partitionKeyRanges, startRange, vbCompareFunction);
// that's an error
if (minIndex > 0) {
throw new Error("BadRequestException: InvalidContinuationToken");
}
// return slice of the partition key ranges
return partitionKeyRanges.slice(minIndex, partitionKeyRanges.length - minIndex);
}
private _decrementInitiationLock() {
// decrements waitingForInternalExecutionContexts
// if waitingForInternalExecutionContexts reaches 0 releases the semaphore and changes the state
this.waitingForInternalExecutionContexts = this.waitingForInternalExecutionContexts - 1;
if (this.waitingForInternalExecutionContexts === 0) {
this.sem.leave();
if (this.orderByPQ.size() === 0) {
this.state = ParallelQueryExecutionContextBase.STATES.inProgress;
}
}
}
private _mergeWithActiveResponseHeaders(headers: CosmosHeaders) {
mergeHeaders(this.respHeaders, headers);
}
private _getAndResetActiveResponseHeaders() {
const ret = this.respHeaders;
this.respHeaders = getInitialHeader();
return ret;
}
private async _onTargetPartitionRanges() {
// invokes the callback when the target partition ranges are ready
const parsedRanges = this.partitionedQueryExecutionInfo.queryRanges;
const queryRanges = parsedRanges.map((item: any) => QueryRange.parseFromDict(item)); // TODO: any
return this.routingProvider.getOverlappingRanges(this.collectionLink, queryRanges);
}
/**
* Gets the replacement ranges for a partitionkeyrange that has been split
* @memberof ParallelQueryExecutionContextBase
* @instance
*/
private async _getReplacementPartitionKeyRanges(documentProducer: DocumentProducer) {
const partitionKeyRange = documentProducer.targetPartitionKeyRange;
// Download the new routing map
this.routingProvider = new SmartRoutingMapProvider(this.clientContext);
// Get the queryRange that relates to this partitionKeyRange
const queryRange = QueryRange.parsePartitionKeyRange(partitionKeyRange);
return this.routingProvider.getOverlappingRanges(this.collectionLink, [queryRange]);
}
// TODO: P0 Code smell - can barely tell what this is doing
/**
* Removes the current document producer from the priqueue,
* replaces that document producer with child document producers,
* then reexecutes the originFunction with the corrrected executionContext
* @memberof ParallelQueryExecutionContextBase
* @instance
*/
private async _repairExecutionContext(originFunction: any) {
// TODO: any
// Get the replacement ranges
// Removing the invalid documentProducer from the orderByPQ
const parentDocumentProducer = this.orderByPQ.deq();
try {
const replacementPartitionKeyRanges: any[] = await this._getReplacementPartitionKeyRanges(parentDocumentProducer);
const replacementDocumentProducers: DocumentProducer[] = [];
// Create the replacement documentProducers
replacementPartitionKeyRanges.forEach(partitionKeyRange => {
// Create replacment document producers with the parent's continuationToken
const replacementDocumentProducer = this._createTargetPartitionQueryExecutionContext(
partitionKeyRange,
parentDocumentProducer.continuationToken
);
replacementDocumentProducers.push(replacementDocumentProducer);
});
// We need to check if the documentProducers even has anything left to fetch from before enqueing them
const checkAndEnqueueDocumentProducer = async (
documentProducerToCheck: DocumentProducer,
checkNextDocumentProducerCallback: any
) => {
try {
const { result: afterItem } = await documentProducerToCheck.current();
if (afterItem === undefined) {
// no more results left in this document producer, so we don't enqueue it
} else {
// Safe to put document producer back in the queue
this.orderByPQ.enq(documentProducerToCheck);
}
await checkNextDocumentProducerCallback();
} catch (err) {
this.err = err;
return;
}
};
const checkAndEnqueueDocumentProducers = async (rdp: DocumentProducer[]) => {
if (rdp.length > 0) {
// We still have a replacementDocumentProducer to check
const replacementDocumentProducer = rdp.shift();
await checkAndEnqueueDocumentProducer(replacementDocumentProducer, async () => {
await checkAndEnqueueDocumentProducers(rdp);
});
} else {
// reexecutes the originFunction with the corrrected executionContext
return originFunction();
}
};
// Invoke the recursive function to get the ball rolling
await checkAndEnqueueDocumentProducers(replacementDocumentProducers);
} catch (err) {
this.err = err;
throw err;
}
}
private static _needPartitionKeyRangeCacheRefresh(error: any) {
// TODO: any error
return (
error.code === StatusCodes.Gone &&
"substatus" in error &&
error["substatus"] === SubStatusCodes.PartitionKeyRangeGone
);
}
/**
* Checks to see if the executionContext needs to be repaired.
* if so it repairs the execution context and executes the ifCallback,
* else it continues with the current execution context and executes the elseCallback
* @memberof ParallelQueryExecutionContextBase
* @instance
*/
private async _repairExecutionContextIfNeeded(ifCallback: any, elseCallback: any) {
const documentProducer = this.orderByPQ.peek();
// Check if split happened
try {
await documentProducer.current();
elseCallback();
} catch (err) {
if (ParallelQueryExecutionContextBase._needPartitionKeyRangeCacheRefresh(err)) {
// Split has happened so we need to repair execution context before continueing
return this._repairExecutionContext(ifCallback);
} else {
// Something actually bad happened ...
this.err = err;
throw err;
}
}
}
/**
* Execute a provided function on the next element in the ParallelQueryExecutionContextBase.
* @memberof ParallelQueryExecutionContextBase
* @instance
* @param {callback} callback - Function to execute for each element. the function takes two \
* parameters error, element.
*/
public async nextItem(): Promise<Response<any>> {
if (this.err) {
// if there is a prior error return error
throw this.err;
}
return new Promise<Response<any>>((resolve, reject) => {
this.sem.take(() => {
// NOTE: lock must be released before invoking quitting
if (this.err) {
// release the lock before invoking callback
this.sem.leave();
// if there is a prior error return error
this.err.headers = this._getAndResetActiveResponseHeaders();
reject(this.err);
return;
}
if (this.orderByPQ.size() === 0) {
// there is no more results
this.state = ParallelQueryExecutionContextBase.STATES.ended;
// release the lock before invoking callback
this.sem.leave();
return resolve({
result: undefined,
headers: this._getAndResetActiveResponseHeaders()
});
}
const ifCallback = () => {
// Release the semaphore to avoid deadlock
this.sem.leave();
// Reexcute the function
return resolve(this.nextItem());
};
const elseCallback = async () => {
let documentProducer: DocumentProducer;
try {
documentProducer = this.orderByPQ.deq();
} catch (e) {
// if comparing elements of the priority queue throws exception
// set that error and return error
this.err = e;
// release the lock before invoking callback
this.sem.leave();
this.err.headers = this._getAndResetActiveResponseHeaders();
reject(this.err);
return;
}
let item: any;
let headers: CosmosHeaders;
try {
const response = await documentProducer.nextItem();
item = response.result;
headers = response.headers;
this._mergeWithActiveResponseHeaders(headers);
if (item === undefined) {
// this should never happen
// because the documentProducer already has buffered an item
// assert item !== undefined
this.err = new Error(
`Extracted DocumentProducer from the priority queue \
doesn't have any buffered item!`
);
// release the lock before invoking callback
this.sem.leave();
return resolve({
result: undefined,
headers: this._getAndResetActiveResponseHeaders()
});
}
} catch (err) {
this.err = new Error(
`Extracted DocumentProducer from the priority queue fails to get the \
buffered item. Due to ${JSON.stringify(err)}`
);
this.err.headers = this._getAndResetActiveResponseHeaders();
// release the lock before invoking callback
this.sem.leave();
reject(this.err);
return;
}
// we need to put back the document producer to the queue if it has more elements.
// the lock will be released after we know document producer must be put back in the queue or not
try {
const { result: afterItem, headers: otherHeaders } = await documentProducer.current();
this._mergeWithActiveResponseHeaders(otherHeaders);
if (afterItem === undefined) {
// no more results is left in this document producer
} else {
try {
const headItem = documentProducer.fetchResults[0];
if (typeof headItem === "undefined") {
throw new Error("Extracted DocumentProducer from PQ is invalid state with no result!");
}
this.orderByPQ.enq(documentProducer);
} catch (e) {
// if comparing elements in priority queue throws exception
// set error
this.err = e;
}
}
} catch (err) {
if (ParallelQueryExecutionContextBase._needPartitionKeyRangeCacheRefresh(err)) {
// We want the document producer enqueued
// So that later parts of the code can repair the execution context
this.orderByPQ.enq(documentProducer);
} else {
// Something actually bad happened
this.err = err;
reject(this.err);
}
} finally {
// release the lock before returning
this.sem.leave();
}
// invoke the callback on the item
return resolve({
result: item,
headers: this._getAndResetActiveResponseHeaders()
});
};
this._repairExecutionContextIfNeeded(ifCallback, elseCallback).catch(reject);
});
});
}
/**
* Retrieve the current element on the ParallelQueryExecutionContextBase.
* @memberof ParallelQueryExecutionContextBase
* @instance
* @param {callback} callback - Function to execute for the current element. \
* the function takes two parameters error, element.
*/
public async current(): Promise<Response<any>> {
if (this.err) {
this.err.headerse = this._getAndResetActiveResponseHeaders();
throw this.err;
}
return new Promise<Response<any>>((resolve, reject) => {
this.sem.take(() => {
try {
if (this.err) {
this.err = this._getAndResetActiveResponseHeaders();
throw this.err;
}
if (this.orderByPQ.size() === 0) {
return resolve({
result: undefined,
headers: this._getAndResetActiveResponseHeaders()
});
}
const ifCallback = () => {
// Reexcute the function
return resolve(this.current());
};
const elseCallback = () => {
const documentProducer = this.orderByPQ.peek();
return resolve(documentProducer.current());
};
this._repairExecutionContextIfNeeded(ifCallback, elseCallback).catch(reject);
} finally {
this.sem.leave();
}
});
});
}
/**
* Determine if there are still remaining resources to processs based on the value of the continuation \
* token or the elements remaining on the current batch in the QueryIterator.
* @memberof ParallelQueryExecutionContextBase
* @instance
* @returns {Boolean} true if there is other elements to process in the ParallelQueryExecutionContextBase.
*/
public hasMoreResults() {
return !(this.state === ParallelQueryExecutionContextBase.STATES.ended || this.err !== undefined);
}
/**
* Creates document producers
*/
private _createTargetPartitionQueryExecutionContext(partitionKeyTargetRange: any, continuationToken?: any) {
// TODO: any
// creates target partition range Query Execution Context
let rewrittenQuery = this.partitionedQueryExecutionInfo.queryInfo.rewrittenQuery;
let query = this.query;
if (typeof query === "string") {
query = { query };
}
const formatPlaceHolder = "{documentdb-formattableorderbyquery-filter}";
if (rewrittenQuery) {
query = JSON.parse(JSON.stringify(query));
// We hardcode the formattable filter to true for now
rewrittenQuery = rewrittenQuery.replace(formatPlaceHolder, "true");
query["query"] = rewrittenQuery;
}
const options = JSON.parse(JSON.stringify(this.options));
options.continuationToken = continuationToken;
return new DocumentProducer(this.clientContext, this.collectionLink, query, partitionKeyTargetRange, options);
}
} | the_stack |
* Virtual Key Codes, the value does not hold any inherent meaning.
* Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
* But these are "more general", as they should work across browsers & OS`s.
*/
export const enum KeyCode {
DependsOnKbLayout = -1,
/**
* Placed first to cover the 0 value of the enum.
*/
Unknown = 0,
Backspace,
Tab,
Enter,
Shift,
Ctrl,
Alt,
PauseBreak,
CapsLock,
Escape,
Space,
PageUp,
PageDown,
End,
Home,
LeftArrow,
UpArrow,
RightArrow,
DownArrow,
Insert,
Delete,
Digit0,
Digit1,
Digit2,
Digit3,
Digit4,
Digit5,
Digit6,
Digit7,
Digit8,
Digit9,
KeyA,
KeyB,
KeyC,
KeyD,
KeyE,
KeyF,
KeyG,
KeyH,
KeyI,
KeyJ,
KeyK,
KeyL,
KeyM,
KeyN,
KeyO,
KeyP,
KeyQ,
KeyR,
KeyS,
KeyT,
KeyU,
KeyV,
KeyW,
KeyX,
KeyY,
KeyZ,
Meta,
ContextMenu,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
NumLock,
ScrollLock,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ';:' key
*/
Semicolon,
/**
* For any country/region, the '+' key
* For the US standard keyboard, the '=+' key
*/
Equal,
/**
* For any country/region, the ',' key
* For the US standard keyboard, the ',<' key
*/
Comma,
/**
* For any country/region, the '-' key
* For the US standard keyboard, the '-_' key
*/
Minus,
/**
* For any country/region, the '.' key
* For the US standard keyboard, the '.>' key
*/
Period,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '/?' key
*/
Slash,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '`~' key
*/
Backquote,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '[{' key
*/
BracketLeft,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '\|' key
*/
Backslash,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ']}' key
*/
BracketRight,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ''"' key
*/
Quote,
/**
* Used for miscellaneous characters; it can vary by keyboard.
*/
OEM_8,
/**
* Either the angle bracket key or the backslash key on the RT 102-key keyboard.
*/
IntlBackslash,
Numpad0, // VK_NUMPAD0, 0x60, Numeric keypad 0 key
Numpad1, // VK_NUMPAD1, 0x61, Numeric keypad 1 key
Numpad2, // VK_NUMPAD2, 0x62, Numeric keypad 2 key
Numpad3, // VK_NUMPAD3, 0x63, Numeric keypad 3 key
Numpad4, // VK_NUMPAD4, 0x64, Numeric keypad 4 key
Numpad5, // VK_NUMPAD5, 0x65, Numeric keypad 5 key
Numpad6, // VK_NUMPAD6, 0x66, Numeric keypad 6 key
Numpad7, // VK_NUMPAD7, 0x67, Numeric keypad 7 key
Numpad8, // VK_NUMPAD8, 0x68, Numeric keypad 8 key
Numpad9, // VK_NUMPAD9, 0x69, Numeric keypad 9 key
NumpadMultiply, // VK_MULTIPLY, 0x6A, Multiply key
NumpadAdd, // VK_ADD, 0x6B, Add key
NUMPAD_SEPARATOR, // VK_SEPARATOR, 0x6C, Separator key
NumpadSubtract, // VK_SUBTRACT, 0x6D, Subtract key
NumpadDecimal, // VK_DECIMAL, 0x6E, Decimal key
NumpadDivide, // VK_DIVIDE, 0x6F,
/**
* Cover all key codes when IME is processing input.
*/
KEY_IN_COMPOSITION,
ABNT_C1, // Brazilian (ABNT) Keyboard
ABNT_C2, // Brazilian (ABNT) Keyboard
AudioVolumeMute,
AudioVolumeUp,
AudioVolumeDown,
BrowserSearch,
BrowserHome,
BrowserBack,
BrowserForward,
MediaTrackNext,
MediaTrackPrevious,
MediaStop,
MediaPlayPause,
LaunchMediaPlayer,
LaunchMail,
LaunchApp2,
/**
* VK_CLEAR, 0x0C, CLEAR key
*/
Clear,
/**
* Placed last to cover the length of the enum.
* Please do not depend on this value!
*/
MAX_VALUE
}
/**
* keyboardEvent.code
*/
export const enum ScanCode {
DependsOnKbLayout = -1,
None,
Hyper,
Super,
Fn,
FnLock,
Suspend,
Resume,
Turbo,
Sleep,
WakeUp,
KeyA,
KeyB,
KeyC,
KeyD,
KeyE,
KeyF,
KeyG,
KeyH,
KeyI,
KeyJ,
KeyK,
KeyL,
KeyM,
KeyN,
KeyO,
KeyP,
KeyQ,
KeyR,
KeyS,
KeyT,
KeyU,
KeyV,
KeyW,
KeyX,
KeyY,
KeyZ,
Digit1,
Digit2,
Digit3,
Digit4,
Digit5,
Digit6,
Digit7,
Digit8,
Digit9,
Digit0,
Enter,
Escape,
Backspace,
Tab,
Space,
Minus,
Equal,
BracketLeft,
BracketRight,
Backslash,
IntlHash,
Semicolon,
Quote,
Backquote,
Comma,
Period,
Slash,
CapsLock,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
PrintScreen,
ScrollLock,
Pause,
Insert,
Home,
PageUp,
Delete,
End,
PageDown,
ArrowRight,
ArrowLeft,
ArrowDown,
ArrowUp,
NumLock,
NumpadDivide,
NumpadMultiply,
NumpadSubtract,
NumpadAdd,
NumpadEnter,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
Numpad0,
NumpadDecimal,
IntlBackslash,
ContextMenu,
Power,
NumpadEqual,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
Open,
Help,
Select,
Again,
Undo,
Cut,
Copy,
Paste,
Find,
AudioVolumeMute,
AudioVolumeUp,
AudioVolumeDown,
NumpadComma,
IntlRo,
KanaMode,
IntlYen,
Convert,
NonConvert,
Lang1,
Lang2,
Lang3,
Lang4,
Lang5,
Abort,
Props,
NumpadParenLeft,
NumpadParenRight,
NumpadBackspace,
NumpadMemoryStore,
NumpadMemoryRecall,
NumpadMemoryClear,
NumpadMemoryAdd,
NumpadMemorySubtract,
NumpadClear,
NumpadClearEntry,
ControlLeft,
ShiftLeft,
AltLeft,
MetaLeft,
ControlRight,
ShiftRight,
AltRight,
MetaRight,
BrightnessUp,
BrightnessDown,
MediaPlay,
MediaRecord,
MediaFastForward,
MediaRewind,
MediaTrackNext,
MediaTrackPrevious,
MediaStop,
Eject,
MediaPlayPause,
MediaSelect,
LaunchMail,
LaunchApp2,
LaunchApp1,
SelectTask,
LaunchScreenSaver,
BrowserSearch,
BrowserHome,
BrowserBack,
BrowserForward,
BrowserStop,
BrowserRefresh,
BrowserFavorites,
ZoomToggle,
MailReply,
MailForward,
MailSend,
MAX_VALUE
}
class KeyCodeStrMap {
public _keyCodeToStr: string[];
public _strToKeyCode: { [str: string]: KeyCode };
constructor() {
this._keyCodeToStr = [];
this._strToKeyCode = Object.create(null);
}
define(keyCode: KeyCode, str: string): void {
this._keyCodeToStr[keyCode] = str;
this._strToKeyCode[str.toLowerCase()] = keyCode;
}
keyCodeToStr(keyCode: KeyCode): string {
return this._keyCodeToStr[keyCode];
}
strToKeyCode(str: string): KeyCode {
return this._strToKeyCode[str.toLowerCase()] || KeyCode.Unknown;
}
}
const uiMap = new KeyCodeStrMap();
const userSettingsUSMap = new KeyCodeStrMap();
const userSettingsGeneralMap = new KeyCodeStrMap();
export const EVENT_KEY_CODE_MAP: { [keyCode: number]: KeyCode } = new Array(230);
export const NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE: { [nativeKeyCode: string]: KeyCode } = {};
const scanCodeIntToStr: string[] = [];
const scanCodeStrToInt: { [code: string]: number } = Object.create(null);
const scanCodeLowerCaseStrToInt: { [code: string]: number } = Object.create(null);
export const ScanCodeUtils = {
lowerCaseToEnum: (scanCode: string) => scanCodeLowerCaseStrToInt[scanCode] || ScanCode.None,
toEnum: (scanCode: string) => scanCodeStrToInt[scanCode] || ScanCode.None,
toString: (scanCode: ScanCode) => scanCodeIntToStr[scanCode] || 'None'
};
/**
* -1 if a ScanCode => KeyCode mapping depends on kb layout.
*/
export const IMMUTABLE_CODE_TO_KEY_CODE: KeyCode[] = [];
/**
* -1 if a KeyCode => ScanCode mapping depends on kb layout.
*/
export const IMMUTABLE_KEY_CODE_TO_CODE: ScanCode[] = [];
for (let i = 0; i <= ScanCode.MAX_VALUE; i++) {
IMMUTABLE_CODE_TO_KEY_CODE[i] = KeyCode.DependsOnKbLayout;
}
for (let i = 0; i <= KeyCode.MAX_VALUE; i++) {
IMMUTABLE_KEY_CODE_TO_CODE[i] = ScanCode.DependsOnKbLayout;
}
(function () {
// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
// See https://github.com/microsoft/node-native-keymap/blob/master/deps/chromium/keyboard_codes_win.h
const empty = '';
type IMappingEntry = [number, 0 | 1, ScanCode, string, KeyCode, string, number, string, string, string];
const mappings: IMappingEntry[] = [
// keyCodeOrd, immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel
[0, 1, ScanCode.None, 'None', KeyCode.Unknown, 'unknown', 0, 'VK_UNKNOWN', empty, empty],
[0, 1, ScanCode.Hyper, 'Hyper', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Super, 'Super', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Fn, 'Fn', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.FnLock, 'FnLock', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Suspend, 'Suspend', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Resume, 'Resume', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Turbo, 'Turbo', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Sleep, 'Sleep', KeyCode.Unknown, empty, 0, 'VK_SLEEP', empty, empty],
[0, 1, ScanCode.WakeUp, 'WakeUp', KeyCode.Unknown, empty, 0, empty, empty, empty],
[31, 0, ScanCode.KeyA, 'KeyA', KeyCode.KeyA, 'A', 65, 'VK_A', empty, empty],
[32, 0, ScanCode.KeyB, 'KeyB', KeyCode.KeyB, 'B', 66, 'VK_B', empty, empty],
[33, 0, ScanCode.KeyC, 'KeyC', KeyCode.KeyC, 'C', 67, 'VK_C', empty, empty],
[34, 0, ScanCode.KeyD, 'KeyD', KeyCode.KeyD, 'D', 68, 'VK_D', empty, empty],
[35, 0, ScanCode.KeyE, 'KeyE', KeyCode.KeyE, 'E', 69, 'VK_E', empty, empty],
[36, 0, ScanCode.KeyF, 'KeyF', KeyCode.KeyF, 'F', 70, 'VK_F', empty, empty],
[37, 0, ScanCode.KeyG, 'KeyG', KeyCode.KeyG, 'G', 71, 'VK_G', empty, empty],
[38, 0, ScanCode.KeyH, 'KeyH', KeyCode.KeyH, 'H', 72, 'VK_H', empty, empty],
[39, 0, ScanCode.KeyI, 'KeyI', KeyCode.KeyI, 'I', 73, 'VK_I', empty, empty],
[40, 0, ScanCode.KeyJ, 'KeyJ', KeyCode.KeyJ, 'J', 74, 'VK_J', empty, empty],
[41, 0, ScanCode.KeyK, 'KeyK', KeyCode.KeyK, 'K', 75, 'VK_K', empty, empty],
[42, 0, ScanCode.KeyL, 'KeyL', KeyCode.KeyL, 'L', 76, 'VK_L', empty, empty],
[43, 0, ScanCode.KeyM, 'KeyM', KeyCode.KeyM, 'M', 77, 'VK_M', empty, empty],
[44, 0, ScanCode.KeyN, 'KeyN', KeyCode.KeyN, 'N', 78, 'VK_N', empty, empty],
[45, 0, ScanCode.KeyO, 'KeyO', KeyCode.KeyO, 'O', 79, 'VK_O', empty, empty],
[46, 0, ScanCode.KeyP, 'KeyP', KeyCode.KeyP, 'P', 80, 'VK_P', empty, empty],
[47, 0, ScanCode.KeyQ, 'KeyQ', KeyCode.KeyQ, 'Q', 81, 'VK_Q', empty, empty],
[48, 0, ScanCode.KeyR, 'KeyR', KeyCode.KeyR, 'R', 82, 'VK_R', empty, empty],
[49, 0, ScanCode.KeyS, 'KeyS', KeyCode.KeyS, 'S', 83, 'VK_S', empty, empty],
[50, 0, ScanCode.KeyT, 'KeyT', KeyCode.KeyT, 'T', 84, 'VK_T', empty, empty],
[51, 0, ScanCode.KeyU, 'KeyU', KeyCode.KeyU, 'U', 85, 'VK_U', empty, empty],
[52, 0, ScanCode.KeyV, 'KeyV', KeyCode.KeyV, 'V', 86, 'VK_V', empty, empty],
[53, 0, ScanCode.KeyW, 'KeyW', KeyCode.KeyW, 'W', 87, 'VK_W', empty, empty],
[54, 0, ScanCode.KeyX, 'KeyX', KeyCode.KeyX, 'X', 88, 'VK_X', empty, empty],
[55, 0, ScanCode.KeyY, 'KeyY', KeyCode.KeyY, 'Y', 89, 'VK_Y', empty, empty],
[56, 0, ScanCode.KeyZ, 'KeyZ', KeyCode.KeyZ, 'Z', 90, 'VK_Z', empty, empty],
[22, 0, ScanCode.Digit1, 'Digit1', KeyCode.Digit1, '1', 49, 'VK_1', empty, empty],
[23, 0, ScanCode.Digit2, 'Digit2', KeyCode.Digit2, '2', 50, 'VK_2', empty, empty],
[24, 0, ScanCode.Digit3, 'Digit3', KeyCode.Digit3, '3', 51, 'VK_3', empty, empty],
[25, 0, ScanCode.Digit4, 'Digit4', KeyCode.Digit4, '4', 52, 'VK_4', empty, empty],
[26, 0, ScanCode.Digit5, 'Digit5', KeyCode.Digit5, '5', 53, 'VK_5', empty, empty],
[27, 0, ScanCode.Digit6, 'Digit6', KeyCode.Digit6, '6', 54, 'VK_6', empty, empty],
[28, 0, ScanCode.Digit7, 'Digit7', KeyCode.Digit7, '7', 55, 'VK_7', empty, empty],
[29, 0, ScanCode.Digit8, 'Digit8', KeyCode.Digit8, '8', 56, 'VK_8', empty, empty],
[30, 0, ScanCode.Digit9, 'Digit9', KeyCode.Digit9, '9', 57, 'VK_9', empty, empty],
[21, 0, ScanCode.Digit0, 'Digit0', KeyCode.Digit0, '0', 48, 'VK_0', empty, empty],
[3, 1, ScanCode.Enter, 'Enter', KeyCode.Enter, 'Enter', 13, 'VK_RETURN', empty, empty],
[9, 1, ScanCode.Escape, 'Escape', KeyCode.Escape, 'Escape', 27, 'VK_ESCAPE', empty, empty],
[1, 1, ScanCode.Backspace, 'Backspace', KeyCode.Backspace, 'Backspace', 8, 'VK_BACK', empty, empty],
[2, 1, ScanCode.Tab, 'Tab', KeyCode.Tab, 'Tab', 9, 'VK_TAB', empty, empty],
[10, 1, ScanCode.Space, 'Space', KeyCode.Space, 'Space', 32, 'VK_SPACE', empty, empty],
[83, 0, ScanCode.Minus, 'Minus', KeyCode.Minus, '-', 189, 'VK_OEM_MINUS', '-', 'OEM_MINUS'],
[81, 0, ScanCode.Equal, 'Equal', KeyCode.Equal, '=', 187, 'VK_OEM_PLUS', '=', 'OEM_PLUS'],
[87, 0, ScanCode.BracketLeft, 'BracketLeft', KeyCode.BracketLeft, '[', 219, 'VK_OEM_4', '[', 'OEM_4'],
[89, 0, ScanCode.BracketRight, 'BracketRight', KeyCode.BracketRight, ']', 221, 'VK_OEM_6', ']', 'OEM_6'],
[88, 0, ScanCode.Backslash, 'Backslash', KeyCode.Backslash, '\\', 220, 'VK_OEM_5', '\\', 'OEM_5'],
[0, 0, ScanCode.IntlHash, 'IntlHash', KeyCode.Unknown, empty, 0, empty, empty, empty], // has been dropped from the w3c spec
[80, 0, ScanCode.Semicolon, 'Semicolon', KeyCode.Semicolon, ';', 186, 'VK_OEM_1', ';', 'OEM_1'],
[90, 0, ScanCode.Quote, 'Quote', KeyCode.Quote, '\'', 222, 'VK_OEM_7', '\'', 'OEM_7'],
[86, 0, ScanCode.Backquote, 'Backquote', KeyCode.Backquote, '`', 192, 'VK_OEM_3', '`', 'OEM_3'],
[82, 0, ScanCode.Comma, 'Comma', KeyCode.Comma, ',', 188, 'VK_OEM_COMMA', ',', 'OEM_COMMA'],
[84, 0, ScanCode.Period, 'Period', KeyCode.Period, '.', 190, 'VK_OEM_PERIOD', '.', 'OEM_PERIOD'],
[85, 0, ScanCode.Slash, 'Slash', KeyCode.Slash, '/', 191, 'VK_OEM_2', '/', 'OEM_2'],
[8, 1, ScanCode.CapsLock, 'CapsLock', KeyCode.CapsLock, 'CapsLock', 20, 'VK_CAPITAL', empty, empty],
[59, 1, ScanCode.F1, 'F1', KeyCode.F1, 'F1', 112, 'VK_F1', empty, empty],
[60, 1, ScanCode.F2, 'F2', KeyCode.F2, 'F2', 113, 'VK_F2', empty, empty],
[61, 1, ScanCode.F3, 'F3', KeyCode.F3, 'F3', 114, 'VK_F3', empty, empty],
[62, 1, ScanCode.F4, 'F4', KeyCode.F4, 'F4', 115, 'VK_F4', empty, empty],
[63, 1, ScanCode.F5, 'F5', KeyCode.F5, 'F5', 116, 'VK_F5', empty, empty],
[64, 1, ScanCode.F6, 'F6', KeyCode.F6, 'F6', 117, 'VK_F6', empty, empty],
[65, 1, ScanCode.F7, 'F7', KeyCode.F7, 'F7', 118, 'VK_F7', empty, empty],
[66, 1, ScanCode.F8, 'F8', KeyCode.F8, 'F8', 119, 'VK_F8', empty, empty],
[67, 1, ScanCode.F9, 'F9', KeyCode.F9, 'F9', 120, 'VK_F9', empty, empty],
[68, 1, ScanCode.F10, 'F10', KeyCode.F10, 'F10', 121, 'VK_F10', empty, empty],
[69, 1, ScanCode.F11, 'F11', KeyCode.F11, 'F11', 122, 'VK_F11', empty, empty],
[70, 1, ScanCode.F12, 'F12', KeyCode.F12, 'F12', 123, 'VK_F12', empty, empty],
[0, 1, ScanCode.PrintScreen, 'PrintScreen', KeyCode.Unknown, empty, 0, empty, empty, empty],
[79, 1, ScanCode.ScrollLock, 'ScrollLock', KeyCode.ScrollLock, 'ScrollLock', 145, 'VK_SCROLL', empty, empty],
[7, 1, ScanCode.Pause, 'Pause', KeyCode.PauseBreak, 'PauseBreak', 19, 'VK_PAUSE', empty, empty],
[19, 1, ScanCode.Insert, 'Insert', KeyCode.Insert, 'Insert', 45, 'VK_INSERT', empty, empty],
[14, 1, ScanCode.Home, 'Home', KeyCode.Home, 'Home', 36, 'VK_HOME', empty, empty],
[11, 1, ScanCode.PageUp, 'PageUp', KeyCode.PageUp, 'PageUp', 33, 'VK_PRIOR', empty, empty],
[20, 1, ScanCode.Delete, 'Delete', KeyCode.Delete, 'Delete', 46, 'VK_DELETE', empty, empty],
[13, 1, ScanCode.End, 'End', KeyCode.End, 'End', 35, 'VK_END', empty, empty],
[12, 1, ScanCode.PageDown, 'PageDown', KeyCode.PageDown, 'PageDown', 34, 'VK_NEXT', empty, empty],
[17, 1, ScanCode.ArrowRight, 'ArrowRight', KeyCode.RightArrow, 'RightArrow', 39, 'VK_RIGHT', 'Right', empty],
[15, 1, ScanCode.ArrowLeft, 'ArrowLeft', KeyCode.LeftArrow, 'LeftArrow', 37, 'VK_LEFT', 'Left', empty],
[18, 1, ScanCode.ArrowDown, 'ArrowDown', KeyCode.DownArrow, 'DownArrow', 40, 'VK_DOWN', 'Down', empty],
[16, 1, ScanCode.ArrowUp, 'ArrowUp', KeyCode.UpArrow, 'UpArrow', 38, 'VK_UP', 'Up', empty],
[78, 1, ScanCode.NumLock, 'NumLock', KeyCode.NumLock, 'NumLock', 144, 'VK_NUMLOCK', empty, empty],
[108, 1, ScanCode.NumpadDivide, 'NumpadDivide', KeyCode.NumpadDivide, 'NumPad_Divide', 111, 'VK_DIVIDE', empty, empty],
[103, 1, ScanCode.NumpadMultiply, 'NumpadMultiply', KeyCode.NumpadMultiply, 'NumPad_Multiply', 106, 'VK_MULTIPLY', empty, empty],
[106, 1, ScanCode.NumpadSubtract, 'NumpadSubtract', KeyCode.NumpadSubtract, 'NumPad_Subtract', 109, 'VK_SUBTRACT', empty, empty],
[104, 1, ScanCode.NumpadAdd, 'NumpadAdd', KeyCode.NumpadAdd, 'NumPad_Add', 107, 'VK_ADD', empty, empty],
[3, 1, ScanCode.NumpadEnter, 'NumpadEnter', KeyCode.Enter, empty, 0, empty, empty, empty],
[94, 1, ScanCode.Numpad1, 'Numpad1', KeyCode.Numpad1, 'NumPad1', 97, 'VK_NUMPAD1', empty, empty],
[95, 1, ScanCode.Numpad2, 'Numpad2', KeyCode.Numpad2, 'NumPad2', 98, 'VK_NUMPAD2', empty, empty],
[96, 1, ScanCode.Numpad3, 'Numpad3', KeyCode.Numpad3, 'NumPad3', 99, 'VK_NUMPAD3', empty, empty],
[97, 1, ScanCode.Numpad4, 'Numpad4', KeyCode.Numpad4, 'NumPad4', 100, 'VK_NUMPAD4', empty, empty],
[98, 1, ScanCode.Numpad5, 'Numpad5', KeyCode.Numpad5, 'NumPad5', 101, 'VK_NUMPAD5', empty, empty],
[99, 1, ScanCode.Numpad6, 'Numpad6', KeyCode.Numpad6, 'NumPad6', 102, 'VK_NUMPAD6', empty, empty],
[100, 1, ScanCode.Numpad7, 'Numpad7', KeyCode.Numpad7, 'NumPad7', 103, 'VK_NUMPAD7', empty, empty],
[101, 1, ScanCode.Numpad8, 'Numpad8', KeyCode.Numpad8, 'NumPad8', 104, 'VK_NUMPAD8', empty, empty],
[102, 1, ScanCode.Numpad9, 'Numpad9', KeyCode.Numpad9, 'NumPad9', 105, 'VK_NUMPAD9', empty, empty],
[93, 1, ScanCode.Numpad0, 'Numpad0', KeyCode.Numpad0, 'NumPad0', 96, 'VK_NUMPAD0', empty, empty],
[107, 1, ScanCode.NumpadDecimal, 'NumpadDecimal', KeyCode.NumpadDecimal, 'NumPad_Decimal', 110, 'VK_DECIMAL', empty, empty],
[92, 0, ScanCode.IntlBackslash, 'IntlBackslash', KeyCode.IntlBackslash, 'OEM_102', 226, 'VK_OEM_102', empty, empty],
[58, 1, ScanCode.ContextMenu, 'ContextMenu', KeyCode.ContextMenu, 'ContextMenu', 93, empty, empty, empty],
[0, 1, ScanCode.Power, 'Power', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadEqual, 'NumpadEqual', KeyCode.Unknown, empty, 0, empty, empty, empty],
[71, 1, ScanCode.F13, 'F13', KeyCode.F13, 'F13', 124, 'VK_F13', empty, empty],
[72, 1, ScanCode.F14, 'F14', KeyCode.F14, 'F14', 125, 'VK_F14', empty, empty],
[73, 1, ScanCode.F15, 'F15', KeyCode.F15, 'F15', 126, 'VK_F15', empty, empty],
[74, 1, ScanCode.F16, 'F16', KeyCode.F16, 'F16', 127, 'VK_F16', empty, empty],
[75, 1, ScanCode.F17, 'F17', KeyCode.F17, 'F17', 128, 'VK_F17', empty, empty],
[76, 1, ScanCode.F18, 'F18', KeyCode.F18, 'F18', 129, 'VK_F18', empty, empty],
[77, 1, ScanCode.F19, 'F19', KeyCode.F19, 'F19', 130, 'VK_F19', empty, empty],
[0, 1, ScanCode.F20, 'F20', KeyCode.Unknown, empty, 0, 'VK_F20', empty, empty],
[0, 1, ScanCode.F21, 'F21', KeyCode.Unknown, empty, 0, 'VK_F21', empty, empty],
[0, 1, ScanCode.F22, 'F22', KeyCode.Unknown, empty, 0, 'VK_F22', empty, empty],
[0, 1, ScanCode.F23, 'F23', KeyCode.Unknown, empty, 0, 'VK_F23', empty, empty],
[0, 1, ScanCode.F24, 'F24', KeyCode.Unknown, empty, 0, 'VK_F24', empty, empty],
[0, 1, ScanCode.Open, 'Open', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Help, 'Help', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Select, 'Select', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Again, 'Again', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Undo, 'Undo', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Cut, 'Cut', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Copy, 'Copy', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Paste, 'Paste', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Find, 'Find', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.AudioVolumeMute, 'AudioVolumeMute', KeyCode.AudioVolumeMute, 'AudioVolumeMute', 173, 'VK_VOLUME_MUTE', empty, empty],
[0, 1, ScanCode.AudioVolumeUp, 'AudioVolumeUp', KeyCode.AudioVolumeUp, 'AudioVolumeUp', 175, 'VK_VOLUME_UP', empty, empty],
[0, 1, ScanCode.AudioVolumeDown, 'AudioVolumeDown', KeyCode.AudioVolumeDown, 'AudioVolumeDown', 174, 'VK_VOLUME_DOWN', empty, empty],
[105, 1, ScanCode.NumpadComma, 'NumpadComma', KeyCode.NUMPAD_SEPARATOR, 'NumPad_Separator', 108, 'VK_SEPARATOR', empty, empty],
[110, 0, ScanCode.IntlRo, 'IntlRo', KeyCode.ABNT_C1, 'ABNT_C1', 193, 'VK_ABNT_C1', empty, empty],
[0, 1, ScanCode.KanaMode, 'KanaMode', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 0, ScanCode.IntlYen, 'IntlYen', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Convert, 'Convert', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NonConvert, 'NonConvert', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Lang1, 'Lang1', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Lang2, 'Lang2', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Lang3, 'Lang3', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Lang4, 'Lang4', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Lang5, 'Lang5', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Abort, 'Abort', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.Props, 'Props', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadParenLeft, 'NumpadParenLeft', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadParenRight, 'NumpadParenRight', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadBackspace, 'NumpadBackspace', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadMemoryStore, 'NumpadMemoryStore', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadMemoryRecall, 'NumpadMemoryRecall', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadMemoryClear, 'NumpadMemoryClear', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadMemoryAdd, 'NumpadMemoryAdd', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadMemorySubtract, 'NumpadMemorySubtract', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.NumpadClear, 'NumpadClear', KeyCode.Clear, 'Clear', 12, 'VK_CLEAR', empty, empty],
[0, 1, ScanCode.NumpadClearEntry, 'NumpadClearEntry', KeyCode.Unknown, empty, 0, empty, empty, empty],
[5, 1, ScanCode.None, empty, KeyCode.Ctrl, 'Ctrl', 17, 'VK_CONTROL', empty, empty],
[4, 1, ScanCode.None, empty, KeyCode.Shift, 'Shift', 16, 'VK_SHIFT', empty, empty],
[6, 1, ScanCode.None, empty, KeyCode.Alt, 'Alt', 18, 'VK_MENU', empty, empty],
[57, 1, ScanCode.None, empty, KeyCode.Meta, 'Meta', 0, 'VK_COMMAND', empty, empty],
[5, 1, ScanCode.ControlLeft, 'ControlLeft', KeyCode.Ctrl, empty, 0, 'VK_LCONTROL', empty, empty],
[4, 1, ScanCode.ShiftLeft, 'ShiftLeft', KeyCode.Shift, empty, 0, 'VK_LSHIFT', empty, empty],
[6, 1, ScanCode.AltLeft, 'AltLeft', KeyCode.Alt, empty, 0, 'VK_LMENU', empty, empty],
[57, 1, ScanCode.MetaLeft, 'MetaLeft', KeyCode.Meta, empty, 0, 'VK_LWIN', empty, empty],
[5, 1, ScanCode.ControlRight, 'ControlRight', KeyCode.Ctrl, empty, 0, 'VK_RCONTROL', empty, empty],
[4, 1, ScanCode.ShiftRight, 'ShiftRight', KeyCode.Shift, empty, 0, 'VK_RSHIFT', empty, empty],
[6, 1, ScanCode.AltRight, 'AltRight', KeyCode.Alt, empty, 0, 'VK_RMENU', empty, empty],
[57, 1, ScanCode.MetaRight, 'MetaRight', KeyCode.Meta, empty, 0, 'VK_RWIN', empty, empty],
[0, 1, ScanCode.BrightnessUp, 'BrightnessUp', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.BrightnessDown, 'BrightnessDown', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.MediaPlay, 'MediaPlay', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.MediaRecord, 'MediaRecord', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.MediaFastForward, 'MediaFastForward', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.MediaRewind, 'MediaRewind', KeyCode.Unknown, empty, 0, empty, empty, empty],
[114, 1, ScanCode.MediaTrackNext, 'MediaTrackNext', KeyCode.MediaTrackNext, 'MediaTrackNext', 176, 'VK_MEDIA_NEXT_TRACK', empty, empty],
[115, 1, ScanCode.MediaTrackPrevious, 'MediaTrackPrevious', KeyCode.MediaTrackPrevious, 'MediaTrackPrevious', 177, 'VK_MEDIA_PREV_TRACK', empty, empty],
[116, 1, ScanCode.MediaStop, 'MediaStop', KeyCode.MediaStop, 'MediaStop', 178, 'VK_MEDIA_STOP', empty, empty],
[0, 1, ScanCode.Eject, 'Eject', KeyCode.Unknown, empty, 0, empty, empty, empty],
[117, 1, ScanCode.MediaPlayPause, 'MediaPlayPause', KeyCode.MediaPlayPause, 'MediaPlayPause', 179, 'VK_MEDIA_PLAY_PAUSE', empty, empty],
[0, 1, ScanCode.MediaSelect, 'MediaSelect', KeyCode.LaunchMediaPlayer, 'LaunchMediaPlayer', 181, 'VK_MEDIA_LAUNCH_MEDIA_SELECT', empty, empty],
[0, 1, ScanCode.LaunchMail, 'LaunchMail', KeyCode.LaunchMail, 'LaunchMail', 180, 'VK_MEDIA_LAUNCH_MAIL', empty, empty],
[0, 1, ScanCode.LaunchApp2, 'LaunchApp2', KeyCode.LaunchApp2, 'LaunchApp2', 183, 'VK_MEDIA_LAUNCH_APP2', empty, empty],
[0, 1, ScanCode.LaunchApp1, 'LaunchApp1', KeyCode.Unknown, empty, 0, 'VK_MEDIA_LAUNCH_APP1', empty, empty],
[0, 1, ScanCode.SelectTask, 'SelectTask', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.LaunchScreenSaver, 'LaunchScreenSaver', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.BrowserSearch, 'BrowserSearch', KeyCode.BrowserSearch, 'BrowserSearch', 170, 'VK_BROWSER_SEARCH', empty, empty],
[0, 1, ScanCode.BrowserHome, 'BrowserHome', KeyCode.BrowserHome, 'BrowserHome', 172, 'VK_BROWSER_HOME', empty, empty],
[112, 1, ScanCode.BrowserBack, 'BrowserBack', KeyCode.BrowserBack, 'BrowserBack', 166, 'VK_BROWSER_BACK', empty, empty],
[113, 1, ScanCode.BrowserForward, 'BrowserForward', KeyCode.BrowserForward, 'BrowserForward', 167, 'VK_BROWSER_FORWARD', empty, empty],
[0, 1, ScanCode.BrowserStop, 'BrowserStop', KeyCode.Unknown, empty, 0, 'VK_BROWSER_STOP', empty, empty],
[0, 1, ScanCode.BrowserRefresh, 'BrowserRefresh', KeyCode.Unknown, empty, 0, 'VK_BROWSER_REFRESH', empty, empty],
[0, 1, ScanCode.BrowserFavorites, 'BrowserFavorites', KeyCode.Unknown, empty, 0, 'VK_BROWSER_FAVORITES', empty, empty],
[0, 1, ScanCode.ZoomToggle, 'ZoomToggle', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.MailReply, 'MailReply', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.MailForward, 'MailForward', KeyCode.Unknown, empty, 0, empty, empty, empty],
[0, 1, ScanCode.MailSend, 'MailSend', KeyCode.Unknown, empty, 0, empty, empty, empty],
// See https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
// If an Input Method Editor is processing key input and the event is keydown, return 229.
[109, 1, ScanCode.None, empty, KeyCode.KEY_IN_COMPOSITION, 'KeyInComposition', 229, empty, empty, empty],
[111, 1, ScanCode.None, empty, KeyCode.ABNT_C2, 'ABNT_C2', 194, 'VK_ABNT_C2', empty, empty],
[91, 1, ScanCode.None, empty, KeyCode.OEM_8, 'OEM_8', 223, 'VK_OEM_8', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_KANA', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_HANGUL', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_JUNJA', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_FINAL', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_HANJA', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_KANJI', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_CONVERT', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_NONCONVERT', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_ACCEPT', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_MODECHANGE', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_SELECT', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_PRINT', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_EXECUTE', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_SNAPSHOT', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_HELP', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_APPS', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_PROCESSKEY', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_PACKET', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_DBE_SBCSCHAR', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_DBE_DBCSCHAR', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_ATTN', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_CRSEL', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_EXSEL', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_EREOF', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_PLAY', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_ZOOM', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_NONAME', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_PA1', empty, empty],
[0, 1, ScanCode.None, empty, KeyCode.Unknown, empty, 0, 'VK_OEM_CLEAR', empty, empty],
];
let seenKeyCode: boolean[] = [];
let seenScanCode: boolean[] = [];
for (const mapping of mappings) {
const [_keyCodeOrd, immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel] = mapping;
if (!seenScanCode[scanCode]) {
seenScanCode[scanCode] = true;
scanCodeIntToStr[scanCode] = scanCodeStr;
scanCodeStrToInt[scanCodeStr] = scanCode;
scanCodeLowerCaseStrToInt[scanCodeStr.toLowerCase()] = scanCode;
if (immutable) {
IMMUTABLE_CODE_TO_KEY_CODE[scanCode] = keyCode;
if (
(keyCode !== KeyCode.Unknown)
&& (keyCode !== KeyCode.Enter)
&& (keyCode !== KeyCode.Ctrl)
&& (keyCode !== KeyCode.Shift)
&& (keyCode !== KeyCode.Alt)
&& (keyCode !== KeyCode.Meta)
) {
IMMUTABLE_KEY_CODE_TO_CODE[keyCode] = scanCode;
}
}
}
if (!seenKeyCode[keyCode]) {
seenKeyCode[keyCode] = true;
if (!keyCodeStr) {
throw new Error(`String representation missing for key code ${keyCode} around scan code ${scanCodeStr}`);
}
uiMap.define(keyCode, keyCodeStr);
userSettingsUSMap.define(keyCode, usUserSettingsLabel || keyCodeStr);
userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel || usUserSettingsLabel || keyCodeStr);
}
if (eventKeyCode) {
EVENT_KEY_CODE_MAP[eventKeyCode] = keyCode;
}
if (vkey) {
NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE[vkey] = keyCode;
}
}
// Manually added due to the exclusion above (due to duplication with NumpadEnter)
IMMUTABLE_KEY_CODE_TO_CODE[KeyCode.Enter] = ScanCode.Enter;
})();
export namespace KeyCodeUtils {
export function toString(keyCode: KeyCode): string {
return uiMap.keyCodeToStr(keyCode);
}
export function fromString(key: string): KeyCode {
return uiMap.strToKeyCode(key);
}
export function toUserSettingsUS(keyCode: KeyCode): string {
return userSettingsUSMap.keyCodeToStr(keyCode);
}
export function toUserSettingsGeneral(keyCode: KeyCode): string {
return userSettingsGeneralMap.keyCodeToStr(keyCode);
}
export function fromUserSettings(key: string): KeyCode {
return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key);
}
export function toElectronAccelerator(keyCode: KeyCode): string | null {
if (keyCode >= KeyCode.Numpad0 && keyCode <= KeyCode.NumpadDivide) {
// [Electron Accelerators] Electron is able to parse numpad keys, but unfortunately it
// renders them just as regular keys in menus. For example, num0 is rendered as "0",
// numdiv is rendered as "/", numsub is rendered as "-".
//
// This can lead to incredible confusion, as it makes numpad based keybindings indistinguishable
// from keybindings based on regular keys.
//
// We therefore need to fall back to custom rendering for numpad keys.
return null;
}
switch (keyCode) {
case KeyCode.UpArrow:
return 'Up';
case KeyCode.DownArrow:
return 'Down';
case KeyCode.LeftArrow:
return 'Left';
case KeyCode.RightArrow:
return 'Right';
}
return uiMap.keyCodeToStr(keyCode);
}
}
export const enum KeyMod {
CtrlCmd = (1 << 11) >>> 0,
Shift = (1 << 10) >>> 0,
Alt = (1 << 9) >>> 0,
WinCtrl = (1 << 8) >>> 0,
}
export function KeyChord(firstPart: number, secondPart: number): number {
const chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0;
return (firstPart | chordPart) >>> 0;
} | the_stack |
import {
concat,
of,
EMPTY,
interval,
Observable,
TimeoutError,
throwError,
} from "rxjs";
import {
scan,
debounce,
debounceTime,
catchError,
switchMap,
tap,
distinctUntilChanged,
timeout,
} from "rxjs/operators";
import { useEffect, useCallback, useState } from "react";
import { log } from "@ledgerhq/logs";
import type { DeviceInfo } from "../../types/manager";
import type { ListAppsResult } from "../../apps/types";
import { useReplaySubject } from "../../observable";
import manager from "../../manager";
import type {
ConnectManagerEvent,
Input as ConnectManagerInput,
} from "../connectManager";
import type { Action, Device } from "./types";
import isEqual from "lodash/isEqual";
import { ConnectManagerTimeout } from "../../errors";
import { currentMode } from "./app";
import {
DisconnectedDevice,
DisconnectedDeviceDuringOperation,
} from "@ledgerhq/errors";
import { getDeviceModel } from "@ledgerhq/devices";
type State = {
isLoading: boolean;
requestQuitApp: boolean;
unresponsive: boolean;
allowManagerRequestedWording: string | null | undefined;
allowManagerGranted: boolean;
device: Device | null | undefined;
deviceInfo: DeviceInfo | null | undefined;
result: ListAppsResult | null | undefined;
error: Error | null | undefined;
};
type ManagerState = State & {
repairModalOpened:
| {
auto: boolean;
}
| null
| undefined;
onRetry: () => void;
onAutoRepair: () => void;
onRepairModal: (arg0: boolean) => void;
closeRepairModal: () => void;
};
export type ManagerRequest =
| {
autoQuitAppDisabled?: boolean;
}
| null
| undefined;
type Result = {
device: Device;
deviceInfo: DeviceInfo;
result: ListAppsResult | null | undefined;
};
type ManagerAction = Action<ManagerRequest, ManagerState, Result>;
type Event =
| ConnectManagerEvent
| {
type: "error";
error: Error;
}
| {
type: "deviceChange";
device: Device | null | undefined;
};
const mapResult = ({ deviceInfo, device, result }): Result | null | undefined =>
deviceInfo && device
? {
device,
deviceInfo,
result,
}
: null;
const getInitialState = (device?: Device | null | undefined): State => ({
isLoading: !!device,
requestQuitApp: false,
unresponsive: false,
allowManagerRequestedWording: null,
allowManagerGranted: false,
device,
deviceInfo: null,
result: null,
error: null,
});
const reducer = (state: State, e: Event): State => {
switch (e.type) {
case "unresponsiveDevice":
return { ...state, unresponsive: true };
case "deviceChange":
return getInitialState(e.device);
case "error":
return {
...getInitialState(state.device),
error: e.error,
isLoading: false,
};
case "appDetected":
return { ...state, unresponsive: false, requestQuitApp: true };
case "osu":
case "bootloader":
return {
...state,
isLoading: false,
unresponsive: false,
requestQuitApp: false,
deviceInfo: e.deviceInfo,
};
case "listingApps":
return {
...state,
requestQuitApp: false,
unresponsive: false,
deviceInfo: e.deviceInfo,
};
case "device-permission-requested":
return {
...state,
unresponsive: false,
allowManagerRequestedWording: e.wording,
};
case "device-permission-granted":
return {
...state,
unresponsive: false,
allowManagerRequestedWording: null,
allowManagerGranted: true,
};
case "result":
return {
...state,
isLoading: false,
unresponsive: false,
result: e.result,
};
}
return state;
};
const implementations = {
// in this paradigm, we know that deviceSubject is reflecting the device events
// so we just trust deviceSubject to reflect the device context (switch between apps, dashboard,...)
event: ({ deviceSubject, connectManager, managerRequest }) =>
deviceSubject.pipe(
debounceTime(1000),
switchMap((d) => connectManager(d, managerRequest))
),
// in this paradigm, we can't observe directly the device, so we have to poll it
polling: ({ deviceSubject, connectManager, managerRequest }) =>
Observable.create((o) => {
const POLLING = 2000;
const INIT_DEBOUNCE = 5000;
const DISCONNECT_DEBOUNCE = 5000;
const DEVICE_POLLING_TIMEOUT = 20000;
// this pattern allows to actually support events based (like if deviceSubject emits new device changes) but inside polling paradigm
let pollingOnDevice;
const sub = deviceSubject.subscribe((d) => {
if (d) {
pollingOnDevice = d;
}
});
let initT: NodeJS.Timeout | null = setTimeout(() => {
// initial timeout to unset the device if it's still not connected
o.next({
type: "deviceChange",
device: null,
});
device = null;
log("app/polling", "device init timeout");
}, INIT_DEBOUNCE);
let connectSub;
let loopT;
let disconnectT;
let device = null; // used as internal state for polling
let stopDevicePollingError = null;
function loop() {
stopDevicePollingError = null;
if (!pollingOnDevice) {
loopT = setTimeout(loop, POLLING);
return;
}
log("manager/polling", "polling loop");
connectSub = connectManager(pollingOnDevice, managerRequest)
.pipe(
timeout(DEVICE_POLLING_TIMEOUT),
catchError((err) => {
const productName = getDeviceModel(
pollingOnDevice.modelId
).productName;
return err instanceof TimeoutError
? of({
type: "error",
error: new ConnectManagerTimeout(undefined, {
productName,
}) as Error,
})
: throwError(err);
})
)
.subscribe({
next: (event) => {
if (initT && device) {
clearTimeout(initT);
initT = null;
}
if (disconnectT) {
// any connect app event unschedule the disconnect debounced event
clearTimeout(disconnectT);
disconnectT = null;
}
if (event.type === "error" && event.error) {
if (
event.error instanceof DisconnectedDevice ||
event.error instanceof DisconnectedDeviceDuringOperation
) {
// disconnect on manager actions seems to trigger a type "error" instead of "disconnect"
// the disconnect event is delayed to debounce the reconnection that happens when switching apps
disconnectT = setTimeout(() => {
disconnectT = null;
// a disconnect will locally be remembered via locally setting device to null...
device = null;
o.next(event);
log("app/polling", "device disconnect timeout");
}, DISCONNECT_DEBOUNCE);
} else {
// These error events should stop polling
stopDevicePollingError = event.error;
// clear all potential polling loops
if (loopT) {
clearTimeout(loopT);
loopT = null;
}
// send in the event for the UI immediately
o.next(event);
}
} else if (event.type === "unresponsiveDevice") {
return; // ignore unresponsive case which happens for polling
} else {
if (device !== pollingOnDevice) {
// ...but any time an event comes back, it means our device was responding and need to be set back on in polling context
device = pollingOnDevice;
o.next({
type: "deviceChange",
device,
});
}
o.next(event);
}
},
complete: () => {
// start a new polling if available
if (!stopDevicePollingError) loopT = setTimeout(loop, POLLING);
},
error: (e) => {
o.error(e);
},
});
}
// delay a bit the first loop run in order to be async and wait pollingOnDevice
loopT = setTimeout(loop, 0);
return () => {
if (initT) clearTimeout(initT);
if (disconnectT) clearTimeout(disconnectT);
if (connectSub) connectSub.unsubscribe();
sub.unsubscribe();
clearTimeout(loopT);
};
}).pipe(distinctUntilChanged(isEqual)),
};
export const createAction = (
connectManagerExec: (
arg0: ConnectManagerInput
) => Observable<ConnectManagerEvent>
): ManagerAction => {
const connectManager = (device, managerRequest) =>
concat(
of({
type: "deviceChange",
device,
}),
!device
? EMPTY
: connectManagerExec({
devicePath: device.deviceId,
managerRequest,
}).pipe(
catchError((error: Error) =>
of({
type: "error",
error,
})
)
)
);
const useHook = (
device: Device | null | undefined,
managerRequest: ManagerRequest = {}
): ManagerState => {
// repair modal will interrupt everything and be rendered instead of the background content
const [repairModalOpened, setRepairModalOpened] = useState<{
auto: boolean;
} | null>(null);
const [state, setState] = useState(() => getInitialState(device));
const [resetIndex, setResetIndex] = useState(0);
const deviceSubject = useReplaySubject(device);
useEffect(() => {
const impl = implementations[currentMode]({
deviceSubject,
connectManager,
managerRequest,
});
if (repairModalOpened) return;
const sub = impl
.pipe(
// debounce a bit the connect/disconnect event that we don't need
tap((e: Event) => log("actions-manager-event", e.type, e)), // tap(e => console.log("connectManager event", e)),
// we gather all events with a reducer into the UI state
scan(reducer, getInitialState()), // tap(s => console.log("connectManager state", s)),
// we debounce the UI state to not blink on the UI
debounce((s: State) => {
if (s.allowManagerRequestedWording || s.allowManagerGranted) {
// no debounce for allow manager
return EMPTY;
}
// default debounce (to be tweak)
return interval(1500);
})
) // the state simply goes into a React state
.subscribe(setState);
return () => {
sub.unsubscribe();
};
}, [deviceSubject, resetIndex, repairModalOpened, managerRequest]);
const { deviceInfo } = state;
useEffect(() => {
if (!deviceInfo) return;
// Preload latest firmware in parallel
manager.getLatestFirmwareForDevice(deviceInfo).catch((e: Error) => {
log("warn", e.message);
});
}, [deviceInfo]);
const onRepairModal = useCallback((open) => {
setRepairModalOpened(
open
? {
auto: false,
}
: null
);
}, []);
const closeRepairModal = useCallback(() => {
setRepairModalOpened(null);
}, []);
const onRetry = useCallback(() => {
setResetIndex((currIndex) => currIndex + 1);
setState((s) => getInitialState(s.device));
}, []);
const onAutoRepair = useCallback(() => {
setRepairModalOpened({
auto: true,
});
}, []);
return {
...state,
repairModalOpened,
onRetry,
onAutoRepair,
closeRepairModal,
onRepairModal,
};
};
return {
useHook,
mapResult,
};
}; | the_stack |
import { randomBytes, RandomSource } from "@stablelib/random";
import { hash, SHA512 } from "@stablelib/sha512";
import { wipe } from "@stablelib/wipe";
export const SIGNATURE_LENGTH = 64;
export const PUBLIC_KEY_LENGTH = 32;
export const SECRET_KEY_LENGTH = 64;
export const SEED_LENGTH = 32;
// TODO(dchest): some functions are copies of ../kex/x25519.
// Find a way to combine them without opening up to public.
// Ported from TweetNaCl.js, which was ported from TweetNaCl
// by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
// https://tweetnacl.js.org
// TweetNaCl contributors:
// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,
// Tanja Lange, Peter Schwabe, Sjaak Smetsers.
// Public domain.
// https://tweetnacl.cr.yp.to/
type GF = Float64Array;
// Returns new zero-filled 16-element GF (Float64Array).
// If passed an array of numbers, prefills the returned
// array with them.
//
// We use Float64Array, because we need 48-bit numbers
// for this implementation.
function gf(init?: number[]): GF {
const r = new Float64Array(16);
if (init) {
for (let i = 0; i < init.length; i++) {
r[i] = init[i];
}
}
return r;
}
// Base point.
const _9 = new Uint8Array(32); _9[0] = 9;
const gf0 = gf();
const gf1 = gf([1]);
const D = gf([
0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,
0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203
]);
const D2 = gf([
0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,
0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406
]);
const X = gf([
0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,
0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169
]);
const Y = gf([
0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666
]);
const I = gf([
0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,
0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83
]);
function set25519(r: GF, a: GF) {
for (let i = 0; i < 16; i++) {
r[i] = a[i] | 0;
}
}
function car25519(o: GF) {
let c = 1;
for (let i = 0; i < 16; i++) {
let v = o[i] + c + 65535;
c = Math.floor(v / 65536);
o[i] = v - c * 65536;
}
o[0] += c - 1 + 37 * (c - 1);
}
function sel25519(p: GF, q: GF, b: number) {
const c = ~(b - 1);
for (let i = 0; i < 16; i++) {
const t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function pack25519(o: Uint8Array, n: GF) {
const m = gf();
const t = gf();
for (let i = 0; i < 16; i++) {
t[i] = n[i];
}
car25519(t);
car25519(t);
car25519(t);
for (let j = 0; j < 2; j++) {
m[0] = t[0] - 0xffed;
for (let i = 1; i < 15; i++) {
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
const b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
sel25519(t, m, 1 - b);
}
for (let i = 0; i < 16; i++) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
function verify32(x: Uint8Array, y: Uint8Array) {
let d = 0;
for (let i = 0; i < 32; i++) {
d |= x[i] ^ y[i];
}
return (1 & ((d - 1) >>> 8)) - 1;
}
function neq25519(a: GF, b: GF) {
const c = new Uint8Array(32);
const d = new Uint8Array(32);
pack25519(c, a);
pack25519(d, b);
return verify32(c, d);
}
function par25519(a: GF) {
const d = new Uint8Array(32);
pack25519(d, a);
return d[0] & 1;
}
function unpack25519(o: GF, n: Uint8Array) {
for (let i = 0; i < 16; i++) {
o[i] = n[2 * i] + (n[2 * i + 1] << 8);
}
o[15] &= 0x7fff;
}
function add(o: GF, a: GF, b: GF) {
for (let i = 0; i < 16; i++) {
o[i] = a[i] + b[i];
}
}
function sub(o: GF, a: GF, b: GF) {
for (let i = 0; i < 16; i++) {
o[i] = a[i] - b[i];
}
}
function mul(o: GF, a: GF, b: GF) {
let v: number, c: number,
t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3],
b4 = b[4],
b5 = b[5],
b6 = b[6],
b7 = b[7],
b8 = b[8],
b9 = b[9],
b10 = b[10],
b11 = b[11],
b12 = b[12],
b13 = b[13],
b14 = b[14],
b15 = b[15];
v = a[0];
t0 += v * b0;
t1 += v * b1;
t2 += v * b2;
t3 += v * b3;
t4 += v * b4;
t5 += v * b5;
t6 += v * b6;
t7 += v * b7;
t8 += v * b8;
t9 += v * b9;
t10 += v * b10;
t11 += v * b11;
t12 += v * b12;
t13 += v * b13;
t14 += v * b14;
t15 += v * b15;
v = a[1];
t1 += v * b0;
t2 += v * b1;
t3 += v * b2;
t4 += v * b3;
t5 += v * b4;
t6 += v * b5;
t7 += v * b6;
t8 += v * b7;
t9 += v * b8;
t10 += v * b9;
t11 += v * b10;
t12 += v * b11;
t13 += v * b12;
t14 += v * b13;
t15 += v * b14;
t16 += v * b15;
v = a[2];
t2 += v * b0;
t3 += v * b1;
t4 += v * b2;
t5 += v * b3;
t6 += v * b4;
t7 += v * b5;
t8 += v * b6;
t9 += v * b7;
t10 += v * b8;
t11 += v * b9;
t12 += v * b10;
t13 += v * b11;
t14 += v * b12;
t15 += v * b13;
t16 += v * b14;
t17 += v * b15;
v = a[3];
t3 += v * b0;
t4 += v * b1;
t5 += v * b2;
t6 += v * b3;
t7 += v * b4;
t8 += v * b5;
t9 += v * b6;
t10 += v * b7;
t11 += v * b8;
t12 += v * b9;
t13 += v * b10;
t14 += v * b11;
t15 += v * b12;
t16 += v * b13;
t17 += v * b14;
t18 += v * b15;
v = a[4];
t4 += v * b0;
t5 += v * b1;
t6 += v * b2;
t7 += v * b3;
t8 += v * b4;
t9 += v * b5;
t10 += v * b6;
t11 += v * b7;
t12 += v * b8;
t13 += v * b9;
t14 += v * b10;
t15 += v * b11;
t16 += v * b12;
t17 += v * b13;
t18 += v * b14;
t19 += v * b15;
v = a[5];
t5 += v * b0;
t6 += v * b1;
t7 += v * b2;
t8 += v * b3;
t9 += v * b4;
t10 += v * b5;
t11 += v * b6;
t12 += v * b7;
t13 += v * b8;
t14 += v * b9;
t15 += v * b10;
t16 += v * b11;
t17 += v * b12;
t18 += v * b13;
t19 += v * b14;
t20 += v * b15;
v = a[6];
t6 += v * b0;
t7 += v * b1;
t8 += v * b2;
t9 += v * b3;
t10 += v * b4;
t11 += v * b5;
t12 += v * b6;
t13 += v * b7;
t14 += v * b8;
t15 += v * b9;
t16 += v * b10;
t17 += v * b11;
t18 += v * b12;
t19 += v * b13;
t20 += v * b14;
t21 += v * b15;
v = a[7];
t7 += v * b0;
t8 += v * b1;
t9 += v * b2;
t10 += v * b3;
t11 += v * b4;
t12 += v * b5;
t13 += v * b6;
t14 += v * b7;
t15 += v * b8;
t16 += v * b9;
t17 += v * b10;
t18 += v * b11;
t19 += v * b12;
t20 += v * b13;
t21 += v * b14;
t22 += v * b15;
v = a[8];
t8 += v * b0;
t9 += v * b1;
t10 += v * b2;
t11 += v * b3;
t12 += v * b4;
t13 += v * b5;
t14 += v * b6;
t15 += v * b7;
t16 += v * b8;
t17 += v * b9;
t18 += v * b10;
t19 += v * b11;
t20 += v * b12;
t21 += v * b13;
t22 += v * b14;
t23 += v * b15;
v = a[9];
t9 += v * b0;
t10 += v * b1;
t11 += v * b2;
t12 += v * b3;
t13 += v * b4;
t14 += v * b5;
t15 += v * b6;
t16 += v * b7;
t17 += v * b8;
t18 += v * b9;
t19 += v * b10;
t20 += v * b11;
t21 += v * b12;
t22 += v * b13;
t23 += v * b14;
t24 += v * b15;
v = a[10];
t10 += v * b0;
t11 += v * b1;
t12 += v * b2;
t13 += v * b3;
t14 += v * b4;
t15 += v * b5;
t16 += v * b6;
t17 += v * b7;
t18 += v * b8;
t19 += v * b9;
t20 += v * b10;
t21 += v * b11;
t22 += v * b12;
t23 += v * b13;
t24 += v * b14;
t25 += v * b15;
v = a[11];
t11 += v * b0;
t12 += v * b1;
t13 += v * b2;
t14 += v * b3;
t15 += v * b4;
t16 += v * b5;
t17 += v * b6;
t18 += v * b7;
t19 += v * b8;
t20 += v * b9;
t21 += v * b10;
t22 += v * b11;
t23 += v * b12;
t24 += v * b13;
t25 += v * b14;
t26 += v * b15;
v = a[12];
t12 += v * b0;
t13 += v * b1;
t14 += v * b2;
t15 += v * b3;
t16 += v * b4;
t17 += v * b5;
t18 += v * b6;
t19 += v * b7;
t20 += v * b8;
t21 += v * b9;
t22 += v * b10;
t23 += v * b11;
t24 += v * b12;
t25 += v * b13;
t26 += v * b14;
t27 += v * b15;
v = a[13];
t13 += v * b0;
t14 += v * b1;
t15 += v * b2;
t16 += v * b3;
t17 += v * b4;
t18 += v * b5;
t19 += v * b6;
t20 += v * b7;
t21 += v * b8;
t22 += v * b9;
t23 += v * b10;
t24 += v * b11;
t25 += v * b12;
t26 += v * b13;
t27 += v * b14;
t28 += v * b15;
v = a[14];
t14 += v * b0;
t15 += v * b1;
t16 += v * b2;
t17 += v * b3;
t18 += v * b4;
t19 += v * b5;
t20 += v * b6;
t21 += v * b7;
t22 += v * b8;
t23 += v * b9;
t24 += v * b10;
t25 += v * b11;
t26 += v * b12;
t27 += v * b13;
t28 += v * b14;
t29 += v * b15;
v = a[15];
t15 += v * b0;
t16 += v * b1;
t17 += v * b2;
t18 += v * b3;
t19 += v * b4;
t20 += v * b5;
t21 += v * b6;
t22 += v * b7;
t23 += v * b8;
t24 += v * b9;
t25 += v * b10;
t26 += v * b11;
t27 += v * b12;
t28 += v * b13;
t29 += v * b14;
t30 += v * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t2 += 38 * t18;
t3 += 38 * t19;
t4 += 38 * t20;
t5 += 38 * t21;
t6 += 38 * t22;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
// t15 left as is
// first car
c = 1;
v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
// second car
c = 1;
v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
o[0] = t0;
o[1] = t1;
o[2] = t2;
o[3] = t3;
o[4] = t4;
o[5] = t5;
o[6] = t6;
o[7] = t7;
o[8] = t8;
o[9] = t9;
o[10] = t10;
o[11] = t11;
o[12] = t12;
o[13] = t13;
o[14] = t14;
o[15] = t15;
}
function square(o: GF, a: GF) {
mul(o, a, a);
}
function inv25519(o: GF, i: GF) {
const c = gf();
let a: number;
for (a = 0; a < 16; a++) {
c[a] = i[a];
}
for (a = 253; a >= 0; a--) {
square(c, c);
if (a !== 2 && a !== 4) {
mul(c, c, i);
}
}
for (a = 0; a < 16; a++) {
o[a] = c[a];
}
}
function pow2523(o: GF, i: GF) {
const c = gf();
let a: number;
for (a = 0; a < 16; a++) {
c[a] = i[a];
}
for (a = 250; a >= 0; a--) {
square(c, c);
if (a !== 1) {
mul(c, c, i);
}
}
for (a = 0; a < 16; a++) {
o[a] = c[a];
}
}
function edadd(p: GF[], q: GF[]) {
const a = gf(), b = gf(), c = gf(),
d = gf(), e = gf(), f = gf(),
g = gf(), h = gf(), t = gf();
sub(a, p[1], p[0]);
sub(t, q[1], q[0]);
mul(a, a, t);
add(b, p[0], p[1]);
add(t, q[0], q[1]);
mul(b, b, t);
mul(c, p[3], q[3]);
mul(c, c, D2);
mul(d, p[2], q[2]);
add(d, d, d);
sub(e, b, a);
sub(f, d, c);
add(g, d, c);
add(h, b, a);
mul(p[0], e, f);
mul(p[1], h, g);
mul(p[2], g, f);
mul(p[3], e, h);
}
function cswap(p: GF[], q: GF[], b: number) {
for (let i = 0; i < 4; i++) {
sel25519(p[i], q[i], b);
}
}
function pack(r: Uint8Array, p: GF[]) {
const tx = gf(), ty = gf(), zi = gf();
inv25519(zi, p[2]);
mul(tx, p[0], zi);
mul(ty, p[1], zi);
pack25519(r, ty);
r[31] ^= par25519(tx) << 7;
}
function scalarmult(p: GF[], q: GF[], s: Uint8Array) {
set25519(p[0], gf0);
set25519(p[1], gf1);
set25519(p[2], gf1);
set25519(p[3], gf0);
for (let i = 255; i >= 0; --i) {
const b = (s[(i / 8) | 0] >> (i & 7)) & 1;
cswap(p, q, b);
edadd(q, p);
edadd(p, p);
cswap(p, q, b);
}
}
function scalarbase(p: GF[], s: Uint8Array) {
const q = [gf(), gf(), gf(), gf()];
set25519(q[0], X);
set25519(q[1], Y);
set25519(q[2], gf1);
mul(q[3], X, Y);
scalarmult(p, q, s);
}
export interface KeyPair {
publicKey: Uint8Array;
secretKey: Uint8Array;
}
// Generates key pair from secret 32-byte seed.
export function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {
if (seed.length !== SEED_LENGTH) {
throw new Error(`ed25519: seed must be ${SEED_LENGTH} bytes`);
}
const d = hash(seed);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
const publicKey = new Uint8Array(32);
const p = [gf(), gf(), gf(), gf()];
scalarbase(p, d);
pack(publicKey, p);
const secretKey = new Uint8Array(64);
secretKey.set(seed);
secretKey.set(publicKey, 32);
return {
publicKey,
secretKey
};
}
export function generateKeyPair(prng?: RandomSource): KeyPair {
const seed = randomBytes(32, prng);
const result = generateKeyPairFromSeed(seed);
wipe(seed);
return result;
}
export function extractPublicKeyFromSecretKey(secretKey: Uint8Array): Uint8Array {
if (secretKey.length !== SECRET_KEY_LENGTH) {
throw new Error(`ed25519: secret key must be ${SECRET_KEY_LENGTH} bytes`);
}
return new Uint8Array(secretKey.subarray(32));
}
const L = new Float64Array([
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2,
0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10
]);
function modL(r: Uint8Array, x: Float64Array) {
let carry: number;
let i: number;
let j: number;
let k: number;
for (i = 63; i >= 32; --i) {
carry = 0;
for (j = i - 32, k = i - 12; j < k; ++j) {
x[j] += carry - 16 * x[i] * L[j - (i - 32)];
carry = Math.floor((x[j] + 128) / 256);
x[j] -= carry * 256;
}
x[j] += carry;
x[i] = 0;
}
carry = 0;
for (j = 0; j < 32; j++) {
x[j] += carry - (x[31] >> 4) * L[j];
carry = x[j] >> 8;
x[j] &= 255;
}
for (j = 0; j < 32; j++) {
x[j] -= carry * L[j];
}
for (i = 0; i < 32; i++) {
x[i + 1] += x[i] >> 8;
r[i] = x[i] & 255;
}
}
function reduce(r: Uint8Array) {
const x = new Float64Array(64);
for (let i = 0; i < 64; i++) {
x[i] = r[i];
}
for (let i = 0; i < 64; i++) {
r[i] = 0;
}
modL(r, x);
}
// Returns 64-byte signature of the message under the 64-byte secret key.
export function sign(secretKey: Uint8Array, message: Uint8Array): Uint8Array {
const x = new Float64Array(64);
const p = [gf(), gf(), gf(), gf()];
const d = hash(secretKey.subarray(0, 32));
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
const signature = new Uint8Array(64);
signature.set(d.subarray(32), 32);
const hs = new SHA512();
hs.update(signature.subarray(32));
hs.update(message);
const r = hs.digest();
hs.clean();
reduce(r);
scalarbase(p, r);
pack(signature, p);
hs.reset();
hs.update(signature.subarray(0, 32));
hs.update(secretKey.subarray(32));
hs.update(message);
const h = hs.digest();
reduce(h);
for (let i = 0; i < 32; i++) {
x[i] = r[i];
}
for (let i = 0; i < 32; i++) {
for (let j = 0; j < 32; j++) {
x[i + j] += h[i] * d[j];
}
}
modL(signature.subarray(32), x);
return signature;
}
function unpackneg(r: GF[], p: Uint8Array) {
const t = gf(), chk = gf(), num = gf(),
den = gf(), den2 = gf(), den4 = gf(),
den6 = gf();
set25519(r[2], gf1);
unpack25519(r[1], p);
square(num, r[1]);
mul(den, num, D);
sub(num, num, r[2]);
add(den, r[2], den);
square(den2, den);
square(den4, den2);
mul(den6, den4, den2);
mul(t, den6, num);
mul(t, t, den);
pow2523(t, t);
mul(t, t, num);
mul(t, t, den);
mul(t, t, den);
mul(r[0], t, den);
square(chk, r[0]);
mul(chk, chk, den);
if (neq25519(chk, num)) {
mul(r[0], r[0], I);
}
square(chk, r[0]);
mul(chk, chk, den);
if (neq25519(chk, num)) {
return -1;
}
if (par25519(r[0]) === (p[31] >> 7)) {
sub(r[0], gf0, r[0]);
}
mul(r[3], r[0], r[1]);
return 0;
}
export function verify(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): boolean {
const t = new Uint8Array(32);
const p = [gf(), gf(), gf(), gf()];
const q = [gf(), gf(), gf(), gf()];
if (signature.length !== SIGNATURE_LENGTH) {
throw new Error(`ed25519: signature must be ${SIGNATURE_LENGTH} bytes`);
}
if (unpackneg(q, publicKey)) {
return false;
}
const hs = new SHA512();
hs.update(signature.subarray(0, 32));
hs.update(publicKey);
hs.update(message);
const h = hs.digest();
reduce(h);
scalarmult(p, q, h);
scalarbase(q, signature.subarray(32));
edadd(p, q);
pack(t, p);
if (verify32(signature, t)) {
return false;
}
return true;
}
/**
* Convert Ed25519 public key to X25519 public key.
*
* Throws if given an invalid public key.
*/
export function convertPublicKeyToX25519(publicKey: Uint8Array): Uint8Array {
let q = [gf(), gf(), gf(), gf()];
if (unpackneg(q, publicKey)) {
throw new Error("Ed25519: invalid public key");
}
// Formula: montgomeryX = (edwardsY + 1)*inverse(1 - edwardsY) mod p
let a = gf();
let b = gf();
let y = q[1];
add(a, gf1, y);
sub(b, gf1, y);
inv25519(b, b);
mul(a, a, b);
let z = new Uint8Array(32);
pack25519(z, a);
return z;
}
/**
* Convert Ed25519 secret (private) key to X25519 secret key.
*/
export function convertSecretKeyToX25519(secretKey: Uint8Array): Uint8Array {
const d = hash(secretKey.subarray(0, 32));
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
const o = new Uint8Array(d.subarray(0, 32));
wipe(d);
return o;
} | the_stack |
import * as d3Force from 'd3-force';
// -------------------------------------------------------------------------------------
// Preparatory Steps
// -------------------------------------------------------------------------------------
interface SimNode extends d3Force.SimulationNodeDatum {
id: string;
group: number;
r: number;
}
interface SimLink extends d3Force.SimulationLinkDatum<SimNode> {
value: number;
d: number;
s: number;
}
interface Graph {
nodes: SimNode[];
links: SimLink[];
}
const graph: Graph = {
nodes: [
{ id: 'Myriel', group: 1, r: 5 },
{ id: 'Napoleon', group: 1, r: 10 },
{ id: 'Mlle.Baptistine', group: 1, r: 5 },
{ id: 'Mme.Magloire', group: 1, r: 10 },
{ id: 'CountessdeLo', group: 1, r: 5 }
],
links: [
{ source: 'Napoleon', target: 'Myriel', value: 1, d: 60, s: 0.95 },
{ source: 'Mlle.Baptistine', target: 'Myriel', value: 8, d: 100, s: 0.85 },
{ source: 'Mme.Magloire', target: 'Myriel', value: 10, d: 80, s: 0.85 },
{ source: 'Mme.Magloire', target: 'Mlle.Baptistine', value: 6, d: 60, s: 0.95 }
]
};
let simNode: SimNode | undefined;
let simLink: SimLink;
let simNodes: SimNode[];
let simLinks: SimLink[];
let num: number;
const canvas = document.querySelector('canvas')!;
const context = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
// -------------------------------------------------------------------------------------
// Test Pre-Defined Forces
// -------------------------------------------------------------------------------------
// Centering ===========================================================================
// create Centering force --------------------------------------------------------------
let forceCenter: d3Force.ForceCenter<SimNode>;
// without specified center point (i.e. defaults to [0, 0])
forceCenter = d3Force.forceCenter<SimNode>();
// with x-coordinate of center point
forceCenter = d3Force.forceCenter<SimNode>(100);
// with x- and y-coordinate of center point
forceCenter = d3Force.forceCenter<SimNode>(100, 100);
// Configure Centering force -----------------------------------------------------------
forceCenter = forceCenter.x(150);
num = forceCenter.x();
forceCenter = forceCenter.y(150);
num = forceCenter.y();
// Use Centering force -----------------------------------------------------------------
forceCenter.initialize(graph.nodes);
forceCenter(0.1); // alpha
// Collision ===========================================================================
// create Collision force --------------------------------------------------------------
let forceCollide: d3Force.ForceCollide<SimNode>;
// without radius
forceCollide = d3Force.forceCollide<SimNode>();
// with fixed radius
forceCollide = d3Force.forceCollide<SimNode>(15);
// with radius accessor function
forceCollide = d3Force.forceCollide<SimNode>((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return n.r;
});
// Configure Collision force -----------------------------------------------------------
let radiusAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number;
// radius
forceCollide = forceCollide.radius(20);
forceCollide = forceCollide.radius((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 2 * n.r;
});
radiusAccessor = forceCollide.radius();
// strength
forceCollide = forceCollide.strength(0.5);
num = forceCollide.strength();
// iterations
forceCollide = forceCollide.iterations(10);
num = forceCollide.iterations();
// Use Collision force -----------------------------------------------------------------
forceCollide.initialize(graph.nodes);
forceCollide(0.1); // alpha
// Link ================================================================================
// create Link force --------------------------------------------------------------
let forceLink: d3Force.ForceLink<SimNode, SimLink>;
// without link data
forceLink = d3Force.forceLink<SimNode, SimLink>();
// with link data
forceLink = d3Force.forceLink<SimNode, SimLink>(graph.links);
// Configure Link force -----------------------------------------------------------
let linkNumberAccessor: (link: SimLink, i: number, links: SimLink[]) => number;
// let nodeIdAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number | string;
// links
forceLink = forceLink.links(graph.links);
simLinks = forceLink.links();
simLink = simLinks[0];
simNode = (typeof simLink.source !== 'number' && typeof simLink.source !== 'string') ? simLink.source : undefined;
simNode = (typeof simLink.target !== 'number' && typeof simLink.target !== 'string') ? simLink.target : undefined;
const maybeNum: number | undefined = simLink.index; // Ex-ante type before initialization of links
num = simLink.index!; // Ex-post after link initialization, use ! non-null assertion operator to narrow to number
num = simLink.value;
num = simLink.d;
num = simLink.s;
// id (node id accessor)
forceLink = forceLink.id((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return n.id;
});
// distance
forceLink = forceLink.distance(50);
forceLink = forceLink.distance((link, index, links) => {
const l: SimLink = link;
const i: number = index;
const ls: SimLink[] = links;
return l.d;
});
linkNumberAccessor = forceLink.distance();
// strength
forceLink = forceLink.strength(0.95);
forceLink = forceLink.strength((link, index, links) => {
const l: SimLink = link;
const i: number = index;
const ls: SimLink[] = links;
return l.s;
});
linkNumberAccessor = forceLink.strength();
// iterations
forceLink = forceLink.iterations(10);
num = forceLink.iterations();
// Use Link force -----------------------------------------------------------------
forceLink.initialize(graph.nodes);
forceLink(0.1); // alpha
// ManyBody ============================================================================
// create ManyBody force --------------------------------------------------------------
let forceCharge: d3Force.ForceManyBody<SimNode>;
forceCharge = d3Force.forceManyBody<SimNode>();
// Configure ManyBody force -----------------------------------------------------------
let simNodeNumberAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number;
// strength
forceCharge = forceCharge.strength(-3000);
forceCharge = forceCharge.strength((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return -1000 * n.group;
});
simNodeNumberAccessor = forceCharge.strength();
// theta
forceCharge = forceCharge.theta(0.8);
num = forceCharge.theta();
// distanceMin
forceCharge = forceCharge.distanceMin(1);
num = forceCharge.distanceMin();
// distanceMax
forceCharge = forceCharge.distanceMax(1000);
num = forceCharge.distanceMax();
// Use ManyBody force -----------------------------------------------------------------
forceCharge.initialize(graph.nodes);
forceCharge(0.1); // alpha
// ForceX ==============================================================================
// create ForceX force --------------------------------------------------------------
let forcePosX: d3Force.ForceX<SimNode>;
forcePosX = d3Force.forceX<SimNode>();
// Configure ForceX force -----------------------------------------------------------
// strength
forcePosX = forcePosX.strength(0.2);
forcePosX = forcePosX.strength((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 0.1 * n.group;
});
simNodeNumberAccessor = forcePosX.strength();
// x
forcePosX = forcePosX.x(100);
forcePosX = forcePosX.x((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
let target: number;
switch (n.group) {
case 1:
target = 100;
break;
case 2:
target = 200;
break;
case 3:
target = 300;
break;
default:
target = 0;
break;
}
return target;
});
simNodeNumberAccessor = forcePosX.x();
// Use ForceX force -----------------------------------------------------------------
forcePosX.initialize(graph.nodes);
forcePosX(0.1); // alpha
// ForceY ==============================================================================
// create ForceY force --------------------------------------------------------------
let forcePosY: d3Force.ForceY<SimNode>;
forcePosY = d3Force.forceY<SimNode>();
// Configure ForceY force -----------------------------------------------------------
// strength
forcePosY = forcePosY.strength(0.2);
forcePosY = forcePosY.strength((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 0.1 * n.group;
});
simNodeNumberAccessor = forcePosY.strength();
// y
forcePosY = forcePosY.y(100);
forcePosY = forcePosY.y((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
let target: number;
switch (n.group) {
case 1:
target = 100;
break;
case 2:
target = 200;
break;
case 3:
target = 300;
break;
default:
target = 0;
break;
}
return target;
});
simNodeNumberAccessor = forcePosY.y();
// Use ForceY force -----------------------------------------------------------------
forcePosY.initialize(graph.nodes);
forcePosY(0.1); // alpha
// ForceRadial ==============================================================================
// create ForceRadial force --------------------------------------------------------------
let forceRadial: d3Force.ForceRadial<SimNode>;
// Radius set only
forceRadial = d3Force.forceRadial<SimNode>(50);
forceRadial = d3Force.forceRadial<SimNode>((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 50 * n.group;
});
// Radius and x-coordinate of center set only
forceRadial = d3Force.forceRadial<SimNode>(50, 10);
forceRadial = d3Force.forceRadial<SimNode>(
50, // radius
(node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 10 * n.group;
} // center-x
);
// Radius and center set
forceRadial = d3Force.forceRadial<SimNode>(50, 10, 10);
forceRadial = d3Force.forceRadial<SimNode>(
50, // radius
10, // center-x
(node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 10 * n.group;
} // center-y
);
forceRadial = d3Force.forceRadial<SimNode>(
(node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 50 * n.group;
}, // radius
(node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 10 * n.group;
}, // center-x
(node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 10 * n.group;
} // center-y
);
// Configure ForceRadial force -----------------------------------------------------------
// strength
forceRadial = forceRadial.strength(0.2);
forceRadial = forceRadial.strength((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
return 0.1 * n.group;
});
simNodeNumberAccessor = forceRadial.strength();
// radius
forceRadial = forceRadial.radius(100);
forceRadial = forceRadial.radius((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
let target: number;
switch (n.group) {
case 1:
target = 100;
break;
case 2:
target = 200;
break;
case 3:
target = 300;
break;
default:
target = 0;
break;
}
return target;
});
simNodeNumberAccessor = forceRadial.radius();
// x
forceRadial = forceRadial.x(100);
forceRadial = forceRadial.x((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
let target: number;
switch (n.group) {
case 1:
target = 100;
break;
case 2:
target = 200;
break;
case 3:
target = 300;
break;
default:
target = 0;
break;
}
return target;
});
simNodeNumberAccessor = forceRadial.x();
// y
forceRadial = forceRadial.y(100);
forceRadial = forceRadial.y((node, index, nodes) => {
const n: SimNode = node;
const i: number = index;
const ns: SimNode[] = nodes;
let target: number;
switch (n.group) {
case 1:
target = 100;
break;
case 2:
target = 200;
break;
case 3:
target = 300;
break;
default:
target = 0;
break;
}
return target;
});
simNodeNumberAccessor = forceRadial.y();
// Use ForceRadial force -----------------------------------------------------------------
forceRadial.initialize(graph.nodes);
forceRadial(0.1); // alpha
// -------------------------------------------------------------------------------------
// Test Force Simulation
// -------------------------------------------------------------------------------------
// Create Force Simulation =============================================================
let nodeSimulation: d3Force.Simulation<SimNode, undefined>;
let nodeLinkSimulation: d3Force.Simulation<SimNode, SimLink>;
// Force Simulation without Links / No node data
nodeSimulation = d3Force.forceSimulation<SimNode>();
// Force Simulation without Links / With node data
nodeSimulation = d3Force.forceSimulation<SimNode>(graph.nodes);
// Force Simulation with Links / No node data
nodeLinkSimulation = d3Force.forceSimulation<SimNode, SimLink>();
// Force Simulation with Links / With node data
nodeLinkSimulation = d3Force.forceSimulation<SimNode, SimLink>(graph.nodes);
// nodes() -----------------------------------------------------------------------------
nodeSimulation = nodeSimulation.nodes(graph.nodes);
simNodes = nodeSimulation.nodes();
// alpha() -----------------------------------------------------------------------------
nodeLinkSimulation = nodeLinkSimulation.alpha(0.3);
num = nodeLinkSimulation.alpha();
// alphaMin() -----------------------------------------------------------------------------
nodeLinkSimulation = nodeLinkSimulation.alphaMin(0.0001);
num = nodeLinkSimulation.alphaMin();
// alphaDecay() -----------------------------------------------------------------------------
nodeLinkSimulation = nodeLinkSimulation.alphaDecay(0.02);
num = nodeLinkSimulation.alphaDecay();
// alphaTarget() -----------------------------------------------------------------------------
nodeLinkSimulation = nodeLinkSimulation.alphaTarget(0);
num = nodeLinkSimulation.alphaTarget();
// velocityDecay() -----------------------------------------------------------------------------
nodeLinkSimulation = nodeLinkSimulation.velocityDecay(0.4);
num = nodeLinkSimulation.velocityDecay();
// force() -----------------------------------------------------------------------------
nodeSimulation = nodeSimulation.force('posx', forcePosX);
nodeSimulation.force('posy', forcePosY);
// Remove force
nodeSimulation = nodeSimulation.force('posx', null);
nodeLinkSimulation = nodeLinkSimulation.force('link', forceLink);
nodeLinkSimulation
.force('charge', forceCharge)
.force('center', forceCenter);
let maybeF: d3Force.Force<SimNode, SimLink> | undefined;
let f: d3Force.Force<SimNode, SimLink>;
// getter with generic force returned
maybeF = nodeLinkSimulation.force('charge');
maybeF = nodeLinkSimulation.force('link');
// assuming certainty that force has been previously assigned
f = nodeLinkSimulation.force<d3Force.Force<SimNode, SimLink>>('charge')!;
// if force may not have been assigned for the name
maybeF = nodeLinkSimulation.force<d3Force.Force<SimNode, SimLink>>('charge');
// f = nodeLinkSimulation.force<d3Force.Force<SimNode, SimLink>>('charge'); // fails, with strictNullChecks
// getter with force type cast to improve return type specificity
let fLink: d3Force.ForceLink<SimNode, SimLink>;
// Need explicit, careful type casting to a specific force type
fLink = nodeLinkSimulation.force<d3Force.ForceLink<SimNode, SimLink>>('link')!;
// This is mainly an issue for ForceLinks, if once wants to get the links from an initialized force
// or re-set new links for an initialized force, e.g.:
simLinks = nodeLinkSimulation.force<d3Force.ForceLink<SimNode, SimLink>>('link')!.links();
// fLink = nodeLinkSimulation.force('link')!; // fails, as ForceLink specific properties are missing from 'generic' force
// on() --------------------------------------------------------------------------------
function drawLink(d: SimLink) {
let source: SimNode | undefined;
let target: SimNode | undefined;
source = (typeof d.source !== 'string' && typeof d.source !== 'number') ? d.source : undefined;
target = (typeof d.target !== 'string' && typeof d.target !== 'number') ? d.target : undefined;
if (context && source && source.x && source.y && target && target.x && target.y) {
context.moveTo(source.x, source.y);
context.lineTo(target.x, target.y);
}
}
function drawNode(d: SimNode) {
if (context && d.x && d.y) {
context.moveTo(d.x + 3, d.y);
context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
}
}
nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() {
const that: d3Force.Simulation<SimNode, SimLink> = this;
if (context) {
context.clearRect(0, 0, width, height);
context.beginPath();
graph.links.forEach(drawLink);
context.strokeStyle = '#aaa';
context.stroke();
context.beginPath();
graph.nodes.forEach(drawNode);
context.fill();
context.strokeStyle = '#fff';
context.stroke();
}
});
// remove listener
nodeSimulation = nodeSimulation.on('tick', null);
// get listener
const listener: ((this: d3Force.Simulation<SimNode, undefined>) => void) | undefined = nodeSimulation.on('tick');
// Configure and Use Force Simulation ===================================================
// restart() --------------------------------------------------------------------------
nodeLinkSimulation = nodeLinkSimulation.restart();
// stop() -----------------------------------------------------------------------------
nodeLinkSimulation = nodeLinkSimulation.stop();
// tick() -----------------------------------------------------------------------------
nodeLinkSimulation.tick();
nodeLinkSimulation.tick(10);
// find() -----------------------------------------------------------------------------
simNode = nodeLinkSimulation.find(100, 100);
simNode = nodeLinkSimulation.find(100, 100, 20); | the_stack |
import { Renderer, Shader, DEG_TO_RAD } from "pixi.js"
import { LightType } from "../../lighting/light-type"
import { StandardMaterialFeatureSet } from "./standard-material-feature-set"
import { StandardShader } from "./standard-shader"
import { Material } from "../material"
import { Camera } from "../../camera/camera"
import { LightingEnvironment } from "../../lighting/lighting-environment"
import { Mesh3D } from "../../mesh/mesh"
import { StandardMaterialAlphaMode } from "./standard-material-alpha-mode"
import { StandardMaterialDebugMode } from "./standard-material-debug-mode"
import { ShadowCastingLight } from "../../shadow/shadow-casting-light"
import { StandardMaterialSkinUniforms } from "./standard-material-skin-uniforms"
import { Color } from "../../color"
import { InstancedStandardMaterial } from "./instanced-standard-material"
import { StandardMaterialOcclusionTexture } from "./standard-material-occlusion-texture"
import { StandardMaterialNormalTexture } from "./standard-material-normal-texture"
import { StandardMaterialTexture } from "./standard-material-texture"
import { StandardMaterialFactory } from "./standard-material-factory"
import { ImageBasedLighting } from "../../lighting/image-based-lighting"
const shaders: { [features: string]: StandardShader } = {}
const getLightingEnvironmentConfigId = (env?: LightingEnvironment) => {
return env ? (env.lights.length + (env.imageBasedLighting ? 0.5 : 0)) : 0
}
/**
* The standard material is using Physically-Based Rendering (PBR) which makes
* it suitable to represent a wide range of different surfaces. It's the default
* material when loading models from file.
*/
export class StandardMaterial extends Material {
private _lightingEnvironment?: LightingEnvironment
private _lightingEnvironmentConfigId = 0
private _unlit = false
private _alphaMode = StandardMaterialAlphaMode.opaque
private _debugMode?: StandardMaterialDebugMode
private _baseColorTexture?: StandardMaterialTexture
private _baseColor = new Float32Array(4)
private _normalTexture?: StandardMaterialNormalTexture
private _occlusionTexture?: StandardMaterialOcclusionTexture
private _emissiveTexture?: StandardMaterialTexture
private _metallicRoughnessTexture?: StandardMaterialTexture
private _shadowCastingLight?: ShadowCastingLight
private _instancingEnabled = false
private _skinUniforms = new StandardMaterialSkinUniforms()
/** The roughness of the material. */
roughness = 1
/** The metalness of the material. */
metallic = 1
/** The base color of the material. */
baseColor = new Color(1, 1, 1, 1)
/** The cutoff threshold when alpha mode is set to "mask". */
alphaCutoff = 0.5
/** The emissive color of the material. */
emissive = new Color(0, 0, 0)
/** The exposure (brightness) of the material. */
exposure = 1
/** The base color texture. */
get baseColorTexture() {
return this._baseColorTexture
}
set baseColorTexture(value: StandardMaterialTexture | undefined) {
if (value !== this._baseColorTexture) {
this.invalidateShader()
this._baseColorTexture = value
}
}
/** The metallic-roughness texture. */
get metallicRoughnessTexture() {
return this._metallicRoughnessTexture
}
set metallicRoughnessTexture(value: StandardMaterialTexture | undefined) {
if (value !== this._metallicRoughnessTexture) {
this.invalidateShader()
this._metallicRoughnessTexture = value
}
}
/** The normal map texture. */
get normalTexture() {
return this._normalTexture
}
set normalTexture(value: StandardMaterialNormalTexture | undefined) {
if (value !== this._normalTexture) {
this.invalidateShader()
this._normalTexture = value
}
}
/** The occlusion map texture. */
get occlusionTexture() {
return this._occlusionTexture
}
set occlusionTexture(value: StandardMaterialOcclusionTexture | undefined) {
if (value !== this._occlusionTexture) {
this.invalidateShader()
this._occlusionTexture = value
}
}
/** The emissive map texture. */
get emissiveTexture() {
return this._emissiveTexture
}
set emissiveTexture(value: StandardMaterialTexture | undefined) {
if (value !== this._emissiveTexture) {
this.invalidateShader()
this._emissiveTexture = value
}
}
/** The alpha rendering mode of the material. */
get alphaMode() {
return this._alphaMode
}
set alphaMode(value: StandardMaterialAlphaMode) {
if (this._alphaMode !== value) {
this._alphaMode = value
this.invalidateShader()
}
}
/** The shadow casting light of the material. */
get shadowCastingLight() {
return this._shadowCastingLight
}
set shadowCastingLight(value: ShadowCastingLight | undefined) {
if (value !== this._shadowCastingLight) {
this.invalidateShader()
this._shadowCastingLight = value
}
}
/** The debug rendering mode of the material. */
get debugMode() {
return this._debugMode
}
set debugMode(value: StandardMaterialDebugMode | undefined) {
if (this._debugMode !== value) {
this.invalidateShader()
this._debugMode = value
}
}
/**
* The camera used when rendering a mesh. If this value is not set, the main
* camera will be used by default.
*/
camera?: Camera
/**
* Lighting environment used when rendering a mesh. If this value is not set,
* the main lighting environment will be used by default.
*/
get lightingEnvironment() {
return this._lightingEnvironment
}
set lightingEnvironment(value: LightingEnvironment | undefined) {
if (value !== this._lightingEnvironment) {
this.invalidateShader()
this._lightingEnvironmentConfigId = getLightingEnvironmentConfigId(value)
this._lightingEnvironment = value
}
}
/**
* Value indicating if the material is unlit. If this value if set to true,
* all lighting is disabled and only the base color will be used.
*/
get unlit() {
return this._unlit
}
set unlit(value: boolean) {
if (this._unlit !== value) {
this._unlit = value
this.invalidateShader()
}
}
destroy() {
this._baseColorTexture?.destroy()
this._normalTexture?.destroy()
this._emissiveTexture?.destroy()
this._occlusionTexture?.destroy()
this._metallicRoughnessTexture?.destroy()
this._skinUniforms.destroy()
}
/**
* Invalidates the shader so it can be rebuilt with the current features.
*/
invalidateShader() {
this._shader = undefined
}
/**
* Creates a new standard material from the specified source.
* @param source Source from which the material is created.
*/
static create(source: unknown) {
return new StandardMaterialFactory().create(source)
}
render(mesh: Mesh3D, renderer: Renderer) {
if (!this._instancingEnabled && mesh.instances.length > 0) {
// Invalidate shader when instancing was enabled.
this.invalidateShader()
this._instancingEnabled = mesh.instances.length > 0
}
let lighting = this.lightingEnvironment || LightingEnvironment.main
let configId = getLightingEnvironmentConfigId(lighting)
if (configId !== this._lightingEnvironmentConfigId) {
// Invalidate shader when the lighting config has changed.
this.invalidateShader()
this._lightingEnvironmentConfigId = configId
}
super.render(mesh, renderer)
}
get isInstancingSupported() {
return true
}
createInstance() {
return new InstancedStandardMaterial(this)
}
createShader(mesh: Mesh3D, renderer: Renderer) {
if (renderer.context.webGLVersion === 1) {
let extensions = ["EXT_shader_texture_lod", "OES_standard_derivatives"]
for (let ext of extensions) {
if (!renderer.gl.getExtension(ext)) {
// Log warning?
}
}
}
let lightingEnvironment = this.lightingEnvironment || LightingEnvironment.main
let features = StandardMaterialFeatureSet.build(renderer, mesh, mesh.geometry, this, lightingEnvironment)
if (!features) {
// The shader features couldn't be built, some resources may still be
// loading. Don't worry, we will retry creating shader at next render.
return undefined
}
if (mesh.skin && StandardMaterialFeatureSet.hasSkinningTextureFeature(features)) {
this._skinUniforms.enableJointMatrixTextures(mesh.skin.joints.length)
}
let checksum = features.join(",")
if (!shaders[checksum]) {
shaders[checksum] = StandardShader.build(renderer, features)
}
return shaders[checksum]
}
updateUniforms(mesh: Mesh3D, shader: Shader) {
this._baseColor.set(this.baseColor.rgb)
this._baseColor[3] = this.baseColor.a * mesh.worldAlpha
let camera = this.camera || Camera.main
if (mesh.skin) {
this._skinUniforms.update(mesh, shader)
}
shader.uniforms.u_Camera = camera.worldTransform.position
shader.uniforms.u_ViewProjectionMatrix = camera.viewProjection
shader.uniforms.u_Exposure = this.exposure
shader.uniforms.u_MetallicFactor = this.metallic
shader.uniforms.u_RoughnessFactor = this.roughness
shader.uniforms.u_BaseColorFactor = this._baseColor
shader.uniforms.u_ModelMatrix = mesh.worldTransform.array
shader.uniforms.u_NormalMatrix = mesh.transform.normalTransform.array
if (this._alphaMode === StandardMaterialAlphaMode.mask) {
shader.uniforms.u_AlphaCutoff = this.alphaCutoff
}
if (mesh.targetWeights) {
shader.uniforms.u_morphWeights = mesh.targetWeights
}
if (this.baseColorTexture?.valid) {
shader.uniforms.u_BaseColorSampler = this.baseColorTexture
shader.uniforms.u_BaseColorUVSet = this.baseColorTexture.uvSet || 0
if (this.baseColorTexture.transform) {
shader.uniforms.u_BaseColorUVTransform = this.baseColorTexture.transform.array
}
}
let lightingEnvironment = this.lightingEnvironment || LightingEnvironment.main
for (let i = 0; i < lightingEnvironment.lights.length; i++) {
let light = lightingEnvironment.lights[i]
let type = 0
switch (light.type) {
case LightType.point: type = 1; break
case LightType.directional: type = 0; break
case LightType.spot: type = 2; break
}
shader.uniforms[`u_Lights[${i}].type`] = type
shader.uniforms[`u_Lights[${i}].position`] = light.worldTransform.position
shader.uniforms[`u_Lights[${i}].direction`] = light.worldTransform.forward
shader.uniforms[`u_Lights[${i}].range`] = light.range
shader.uniforms[`u_Lights[${i}].color`] = light.color.rgb
shader.uniforms[`u_Lights[${i}].intensity`] = light.intensity
shader.uniforms[`u_Lights[${i}].innerConeCos`] = Math.cos(light.innerConeAngle * DEG_TO_RAD)
shader.uniforms[`u_Lights[${i}].outerConeCos`] = Math.cos(light.outerConeAngle * DEG_TO_RAD)
}
if (this._shadowCastingLight) {
shader.uniforms.u_ShadowSampler = this._shadowCastingLight.shadowTexture
shader.uniforms.u_LightViewProjectionMatrix = this._shadowCastingLight.lightViewProjection
shader.uniforms.u_ShadowLightIndex = lightingEnvironment.lights.indexOf(this._shadowCastingLight.light)
}
let imageBasedLighting = lightingEnvironment.imageBasedLighting
if (imageBasedLighting?.valid) {
shader.uniforms.u_DiffuseEnvSampler = imageBasedLighting.diffuse
shader.uniforms.u_SpecularEnvSampler = imageBasedLighting.specular
shader.uniforms.u_brdfLUT = imageBasedLighting.lookupBrdf || ImageBasedLighting.defaultLookupBrdf
shader.uniforms.u_MipCount = imageBasedLighting.specular.levels - 1
}
if (this.emissiveTexture?.valid) {
shader.uniforms.u_EmissiveSampler = this.emissiveTexture
shader.uniforms.u_EmissiveUVSet = this.emissiveTexture.uvSet || 0
shader.uniforms.u_EmissiveFactor = this.emissive.rgb
if (this.emissiveTexture.transform) {
shader.uniforms.u_EmissiveUVTransform = this.emissiveTexture.transform.array
}
}
if (this.normalTexture?.valid) {
shader.uniforms.u_NormalSampler = this.normalTexture
shader.uniforms.u_NormalScale = this.normalTexture.scale || 1
shader.uniforms.u_NormalUVSet = this.normalTexture.uvSet || 0
if (this.normalTexture.transform) {
shader.uniforms.u_NormalUVTransform = this.normalTexture.transform.array
}
}
if (this.metallicRoughnessTexture?.valid) {
shader.uniforms.u_MetallicRoughnessSampler = this.metallicRoughnessTexture
shader.uniforms.u_MetallicRoughnessUVSet = this.metallicRoughnessTexture.uvSet || 0
if (this.metallicRoughnessTexture.transform) {
shader.uniforms.u_MetallicRoughnessUVTransform = this.metallicRoughnessTexture.transform.array
}
}
if (this.occlusionTexture?.valid) {
shader.uniforms.u_OcclusionSampler = this.occlusionTexture
shader.uniforms.u_OcclusionStrength = this.occlusionTexture.strength || 1
shader.uniforms.u_OcclusionUVSet = this.occlusionTexture.uvSet || 0
if (this.occlusionTexture.transform) {
shader.uniforms.u_OcclusionUVTransform = this.occlusionTexture.transform.array
}
}
}
} | the_stack |
import { EventEmitter } from 'events'
import { Status, PickleFilter } from '@cucumber/cucumber'
import {
Pickle, TestCase, Envelope, TestStepResult, TestCaseStarted, GherkinDocument,
TestStepStarted, TestStepFinished, PickleStep
} from '@cucumber/messages'
import logger from '@wdio/logger'
import type { Capabilities } from '@wdio/types'
import { HookParams } from './types'
import { addKeywordToStep, filterPickles, getRule } from './utils'
import { ReporterScenario } from './constants'
const log = logger('CucumberEventListener')
export default class CucumberEventListener extends EventEmitter {
private _gherkinDocEvents: GherkinDocument[] = []
private _scenarios: Pickle[] = []
private _testCases: TestCase[] = []
private _currentTestCase?: TestCaseStarted
private _currentPickle?: HookParams = {}
private _suiteMap: Map<string, string> = new Map()
private _pickleMap: Map<string, string> = new Map()
private _currentDoc: GherkinDocument = { comments: [] }
private _startedFeatures: string[] = []
constructor (eventBroadcaster: EventEmitter, private _pickleFilter: PickleFilter) {
super()
let results: TestStepResult[] = []
eventBroadcaster.on('envelope', (envelope: Envelope) => {
if (envelope.gherkinDocument) {
this.onGherkinDocument(envelope.gherkinDocument)
} else if (envelope.testRunStarted) {
this.onTestRunStarted()
} else if (envelope.pickle) {
this.onPickleAccepted(envelope.pickle)
} else if (envelope.testCase) {
this.onTestCasePrepared(envelope.testCase)
} else if (envelope.testCaseStarted) {
results = []
this.onTestCaseStarted(envelope.testCaseStarted)
} else if (envelope.testStepStarted) {
this.onTestStepStarted(envelope.testStepStarted)
} else if (envelope.testStepFinished) {
results.push(envelope.testStepFinished.testStepResult!)
this.onTestStepFinished(envelope.testStepFinished)
} else if (envelope.testCaseFinished) {
/**
* only store result if step isn't retried
*/
if (envelope.testCaseFinished.willBeRetried) {
return log.debug(`test case with id ${envelope.testCaseFinished.testCaseStartedId} will be retried, ignoring result`)
}
this.onTestCaseFinished(results)
} else if (envelope.testRunFinished) {
this.onTestRunFinished()
} else if (envelope.source) {
// do nothing for step definition patterns
} else {
/* istanbul ignore next */
log.debug(`Unknown envelope received: ${JSON.stringify(envelope, null, 4)}`)
}
})
}
usesSpecGrouping() {
return this._gherkinDocEvents.length > 1
}
featureIsStarted(feature: string) {
return this._startedFeatures.includes(feature)
}
// {
// "gherkinDocument": {
// "uri": "/Users/christianbromann/Sites/WebdriverIO/webdriverio/examples/wdio/cucumber/features/my-feature.feature",
// "feature": {
// "location": {
// "line": 1,
// "column": 1
// },
// "language": "en",
// "keyword": "Feature",
// "name": "Example feature",
// "description": " As a user of WebdriverIO\n I should be able to use different commands\n to get informations about elements on the page",
// "children": [
// {
// "scenario": {
// "location": {
// "line": 6,
// "column": 3
// },
// "keyword": "Scenario",
// "name": "Get size of an element",
// "steps": [
// {
// "location": {
// "line": 7,
// "column": 5
// },
// "keyword": "Given ",
// "text": "I go on the website \"https://github.com/\"",
// "id": "0"
// },
// {
// "location": {
// "line": 8,
// "column": 5
// },
// "keyword": "Then ",
// "text": "should the element \".header-logged-out a\" be 32px wide and 35px high",
// "id": "1"
// }
// ],
// "id": "2"
// }
// }
// ]
// }
// }
// }
onGherkinDocument (gherkinDocEvent: GherkinDocument) {
this._currentPickle = { uri: gherkinDocEvent.uri, feature: gherkinDocEvent.feature }
this._gherkinDocEvents.push(gherkinDocEvent)
}
// {
// "pickle": {
// "id": "5",
// "uri": "/Users/christianbromann/Sites/WebdriverIO/webdriverio/examples/wdio/cucumber/features/my-feature.feature",
// "name": "Get size of an element",
// "language": "en",
// "steps": [
// {
// "text": "I go on the website \"https://github.com/\"",
// "id": "3",
// "astNodeIds": [
// "0"
// ]
// },
// {
// "text": "should the element \".header-logged-out a\" be 32px wide and 35px high",
// "id": "4",
// "astNodeIds": [
// "1"
// ]
// }
// ],
// "astNodeIds": [
// "2"
// ]
// }
// }
onPickleAccepted (pickleEvent: Pickle) {
const id = this._suiteMap.size.toString()
this._suiteMap.set(pickleEvent.id as string, id)
this._pickleMap.set(id, pickleEvent.astNodeIds[0] as string)
const scenario = { ...pickleEvent, id }
this._scenarios.push(scenario)
}
// {
// "testRunStarted": {
// "timestamp": {
// "seconds": "1609002214",
// "nanos": 447000000
// }
// }
// }
onTestRunStarted () {
if (this.usesSpecGrouping()) {
return
}
const doc = this._gherkinDocEvents[this._gherkinDocEvents.length - 1]
this.emit('before-feature', doc.uri, doc.feature)
}
// {
// "testCase": {
// "id": "15",
// "pickleId": "5",
// "testSteps": [
// {
// "id": "16",
// "hookId": "13"
// },
// {
// "id": "17",
// "pickleStepId": "3",
// "stepDefinitionIds": [
// "6"
// ],
// "stepMatchArgumentsLists": [
// {
// "stepMatchArguments": [
// {
// "group": {
// "start": 21,
// "value": "https://github.com/"
// }
// }
// ]
// }
// ]
// },
// {
// "id": "18",
// "pickleStepId": "4",
// "stepDefinitionIds": [
// "8"
// ],
// "stepMatchArgumentsLists": [
// {
// "stepMatchArguments": [
// {
// "group": {
// "start": 20,
// "value": ".header-logged-out a"
// }
// },
// {
// "parameterTypeName": "int",
// "group": {
// "start": 45,
// "value": "32"
// }
// },
// {
// "parameterTypeName": "int",
// "group": {
// "start": 59,
// "value": "35"
// }
// }
// ]
// }
// ]
// },
// {
// "id": "19",
// "hookId": "11"
// }
// ]
// }
// }
onTestCasePrepared (testCase: TestCase) {
this._testCases.push(testCase)
}
// {
// "testCaseStarted": {
// "timestamp": {
// "seconds": "1609002214",
// "nanos": 453000000
// },
// "attempt": 0,
// "testCaseId": "15",
// "id": "20"
// }
// }
onTestCaseStarted (testcase: TestCaseStarted) {
this._currentTestCase = testcase
const tc = this._testCases.find(tc => tc.id === testcase.testCaseId)
const scenario = this._scenarios.find(sc => sc.id === this._suiteMap.get(tc?.pickleId as string))
/* istanbul ignore if */
if (!scenario) {
return
}
const doc = this._gherkinDocEvents.find(gde => gde.uri === scenario?.uri)
const uri = doc?.uri
const feature = doc?.feature
if (this._currentDoc.uri && this._currentDoc.feature && this.usesSpecGrouping() && doc != this._currentDoc && this.featureIsStarted(this._currentDoc.uri)) {
this.emit('after-feature', this._currentDoc.uri, this._currentDoc.feature)
}
if (this.usesSpecGrouping() && doc && doc.uri && !this.featureIsStarted(doc.uri)) {
this.emit('before-feature', doc.uri, doc.feature)
this._currentDoc = doc
this._startedFeatures.push(doc.uri)
}
/**
* The reporters need to have the keywords, like `Given|When|Then`. They are NOT available
* on the scenario, they ARE on the feature.
* This will aad them
*/
if (scenario.steps && feature) {
scenario.steps = addKeywordToStep(scenario.steps as PickleStep[], feature)
}
this._currentPickle = { uri, feature, scenario }
let reporterScenario: ReporterScenario = scenario
reporterScenario.rule = getRule(doc?.feature!, this._pickleMap.get(scenario.id)!)
this.emit('before-scenario', scenario.uri, doc?.feature, reporterScenario)
}
// {
// "testStepStarted": {
// "timestamp": {
// "seconds": "1609002214",
// "nanos": 454000000
// },
// "testStepId": "16",
// "testCaseStartedId": "20"
// }
// }
onTestStepStarted (testStepStartedEvent: TestStepStarted) {
const testcase = this._testCases.find((testcase) => this._currentTestCase && testcase.id === this._currentTestCase.testCaseId)
const scenario = this._scenarios.find(sc => sc.id === this._suiteMap.get(testcase?.pickleId as string))
const teststep = testcase?.testSteps?.find((step) => step.id === testStepStartedEvent.testStepId)
const step = scenario?.steps?.find((s) => s.id === teststep?.pickleStepId) || teststep
const doc = this._gherkinDocEvents.find(gde => gde.uri === scenario?.uri)
const uri = doc?.uri
const feature = doc?.feature
/* istanbul ignore if */
if (!step) {
return
}
this._currentPickle = { uri, feature, scenario, step }
this.emit('before-step', uri, feature, scenario, step)
}
// {
// "testStepFinished": {
// "testStepResult": {
// "status": "PASSED",
// "duration": {
// "seconds": "0",
// "nanos": 1000000
// }
// },
// "timestamp": {
// "seconds": "1609002214",
// "nanos": 455000000
// },
// "testStepId": "16",
// "testCaseStartedId": "20"
// }
// }
onTestStepFinished (testStepFinishedEvent: TestStepFinished) {
const testcase = this._testCases.find((testcase) => testcase.id === this._currentTestCase?.testCaseId)
const scenario = this._scenarios.find(sc => sc.id === this._suiteMap.get(testcase?.pickleId as string))
const teststep = testcase?.testSteps?.find((step) => step.id === testStepFinishedEvent.testStepId)
const step = scenario?.steps?.find((s) => s.id === teststep?.pickleStepId) || teststep
const result = testStepFinishedEvent.testStepResult
const doc = this._gherkinDocEvents.find(gde => gde.uri === scenario?.uri)
const uri = doc?.uri
const feature = doc?.feature
/* istanbul ignore if */
if (!step) {
return
}
this.emit('after-step', uri, feature, scenario, step, result)
delete this._currentPickle
}
// {
// "testCaseFinished": {
// "timestamp": {
// "seconds": "1609002223",
// "nanos": 913000000
// },
// "testCaseStartedId": "20"
// }
// }
onTestCaseFinished (
results: TestStepResult[]
) {
const tc = this._testCases.find(tc => tc.id === this._currentTestCase?.testCaseId)
const scenario = this._scenarios.find(sc => sc.id === this._suiteMap.get(tc?.pickleId as string))
/* istanbul ignore if */
if (!scenario) {
return
}
/**
* propagate the first non passing result or the last one
*/
const finalResult = results.find((r) => r.status !== Status.PASSED) || results.pop()
const doc = this._gherkinDocEvents.find(gde => gde.uri === scenario?.uri)
const uri = doc?.uri
const feature = doc?.feature
this._currentPickle = { uri, feature, scenario }
this.emit('after-scenario', doc?.uri, doc?.feature, scenario, finalResult)
}
// testRunFinishedEvent = {
// "timestamp": {
// "seconds": "1609000747",
// "nanos": 793000000
// }
// }
onTestRunFinished () {
delete this._currentTestCase
if (this.usesSpecGrouping()) {
this.emit('after-feature', this._currentDoc.uri, this._currentDoc.feature)
return
}
const gherkinDocEvent = this._gherkinDocEvents.pop() // see .push() in `handleBeforeFeature()`
/* istanbul ignore if */
if (!gherkinDocEvent) {
return
}
this.emit('after-feature', gherkinDocEvent.uri, gherkinDocEvent.feature)
}
getHookParams () {
return this._currentPickle
}
/**
* returns a list of pickles to run based on capability tags
* @param caps session capabilities
*/
getPickleIds (caps: Capabilities.RemoteCapability) {
const gherkinDocument = this._gherkinDocEvents[this._gherkinDocEvents.length - 1]
return [...this._suiteMap.entries()]
/**
* match based on capability tags
*/
.filter(([, fakeId]) => filterPickles(caps, this._scenarios.find(s => s.id === fakeId)))
/**
* match based on Cucumber pickle filter
*/
.filter(([, fakeId]) => this._pickleFilter.matches({
gherkinDocument,
pickle: this._scenarios.find(s => s.id === fakeId) as Pickle
}))
.map(([id]) => id)
}
} | the_stack |
import { Rectangle } from '../../Utilities';
import { getBoundsFromTargetWindow, RectangleEdge } from './index';
import { __positioningTestPackage } from './positioning';
import { DirectionalHint } from '../../common/DirectionalHint';
import type { Point } from '../../Utilities';
import type { IElementPosition } from './index';
interface ITestValidation {
callout: Rectangle;
beak: Rectangle | null;
}
interface ITestValues {
callout: Rectangle;
target: Rectangle;
bounds: Rectangle;
beakWidth: number;
}
function positionCalloutTest(testValues: ITestValues, alignment: DirectionalHint, validate: ITestValidation): void {
const { callout, target, bounds, beakWidth } = testValues;
const gap: number = __positioningTestPackage._calculateActualBeakWidthInPixels(beakWidth) / 2;
const result: IElementPosition = __positioningTestPackage._positionElementWithinBounds(
callout,
target,
bounds,
__positioningTestPackage._getPositionData(alignment),
gap,
);
const beak = __positioningTestPackage._positionBeak(beakWidth, { ...result, targetRectangle: target });
expect(result.elementRectangle).toEqual(validate.callout);
for (const key in beak) {
if ((beak as any)[key]) {
const beakValue = (beak as any)[key];
const validateBeakValue = (validate.beak as any)[key];
const beakGood = beakValue && validateBeakValue && (beak as any)[key] === beakValue;
expect(beakGood).toBe(true);
}
}
}
function validateNoBeakTest(testValues: ITestValues, alignment: DirectionalHint, validate: ITestValidation): void {
const { callout, target, bounds, beakWidth } = testValues;
const result: IElementPosition = __positioningTestPackage._positionElementWithinBounds(
callout,
target,
bounds,
__positioningTestPackage._getPositionData(alignment),
beakWidth,
);
expect(result.elementRectangle).toEqual(validate.callout);
}
describe('Callout Positioning', () => {
it('Correctly positions the callout without beak', () => {
const noBeakTestCase: ITestValues = {
callout: new Rectangle(0, 300, 0, 300),
target: new Rectangle(400, 800, 400, 800),
bounds: new Rectangle(0, 1600, 0, 1600),
beakWidth: 0,
};
const validateNoBeakBottomLeft: ITestValidation = {
callout: new Rectangle(400, 700, 800, 1100),
beak: null,
};
const validateNoBeakLeft: ITestValidation = {
callout: new Rectangle(100, 400, 400, 700),
beak: null,
};
const validateNoBeakTop: ITestValidation = {
callout: new Rectangle(400, 700, 100, 400),
beak: null,
};
validateNoBeakTest(noBeakTestCase, DirectionalHint.bottomLeftEdge, validateNoBeakBottomLeft);
validateNoBeakTest(noBeakTestCase, DirectionalHint.leftTopEdge, validateNoBeakLeft);
validateNoBeakTest(noBeakTestCase, DirectionalHint.topLeftEdge, validateNoBeakTop);
});
it('Correctly positions the callout with the beak', () => {
const basicTestCase: ITestValues = {
callout: new Rectangle(0, 300, 0, 300),
target: new Rectangle(400, 800, 400, 800),
bounds: new Rectangle(0, 1600, 0, 1600),
beakWidth: 16,
};
const validateBottomLeft: ITestValidation = {
callout: new Rectangle(
400,
700,
800 + __positioningTestPackage._calculateActualBeakWidthInPixels(8),
1100 + __positioningTestPackage._calculateActualBeakWidthInPixels(8),
),
beak: new Rectangle(192, 208, -8, 8),
};
const validateBottomCenter: ITestValidation = {
callout: new Rectangle(
450,
750,
800 + __positioningTestPackage._calculateActualBeakWidthInPixels(8),
1100 + __positioningTestPackage._calculateActualBeakWidthInPixels(8),
),
beak: new Rectangle(142, 158, -8, 8),
};
const validateBottomRight: ITestValidation = {
callout: new Rectangle(
500,
800,
800 + __positioningTestPackage._calculateActualBeakWidthInPixels(8),
1100 + __positioningTestPackage._calculateActualBeakWidthInPixels(8),
),
beak: new Rectangle(92, 108, -8, 8),
};
positionCalloutTest(basicTestCase, DirectionalHint.bottomLeftEdge, validateBottomLeft);
positionCalloutTest(basicTestCase, DirectionalHint.bottomCenter, validateBottomCenter);
positionCalloutTest(basicTestCase, DirectionalHint.bottomRightEdge, validateBottomRight);
});
it('Correctly positions the callout when none of the alignment options fit within bounds', () => {
const basicTestCase: ITestValues = {
callout: new Rectangle(0, 200, 0, 200),
target: new Rectangle(150, 160, 150, 160),
bounds: new Rectangle(8, 300, 8, 300),
beakWidth: 0,
};
// when no alignment options fit within bounds, bottom left should flip to top left
// since there is more room at the top
const validateBottomLeft: ITestValidation = {
callout: new Rectangle(100, 300, 8, 208),
beak: null,
};
// when no alignment options fit within bounds, top right stays top right
// since that side has the most room
const validateTopRight: ITestValidation = {
callout: new Rectangle(8, 208, 8, 208),
beak: null,
};
validateNoBeakTest(basicTestCase, DirectionalHint.bottomLeftEdge, validateBottomLeft);
validateNoBeakTest(basicTestCase, DirectionalHint.topRightEdge, validateTopRight);
});
it('Correctly positions the callout when out of bounds and directionalHintFixed is true', () => {
const basicTestCase: ITestValues = {
callout: new Rectangle(0, 200, 0, 200),
target: new Rectangle(150, 160, 150, 160),
bounds: new Rectangle(8, 300, 8, 300),
beakWidth: 0,
};
// should align at the bottom, even if it doesn't fit
// the alignment edge (left) can adjust, but not the bottom position
const validateBottomLeft: ITestValidation = {
callout: new Rectangle(100, 300, 160, 300),
beak: null,
};
// manually call _positionElementWithinBounds to pass in directionalHintFixed value
const result: IElementPosition = __positioningTestPackage._positionElementWithinBounds(
basicTestCase.callout,
basicTestCase.target,
basicTestCase.bounds,
__positioningTestPackage._getPositionData(DirectionalHint.bottomLeftEdge),
basicTestCase.beakWidth,
true, // directionalHintFixed value
);
expect(result.elementRectangle).toEqual(validateBottomLeft.callout);
});
it('Correctly determines max height', () => {
const getMaxHeight = __positioningTestPackage._getMaxHeightFromTargetRectangle;
let targetTop;
let targetBot;
const targetRight = (targetBot = 20);
const targetLeft = (targetTop = 10);
const targetRectangle = new Rectangle(targetLeft, targetRight, targetTop, targetBot);
const bounds = new Rectangle(0, 1000, 0, 1000);
let testMax = getMaxHeight(targetRectangle, DirectionalHint.bottomCenter, 0, bounds);
// Test for maxHeight from bottom of target to bottom of bounds
expect(testMax).toBe(1000 - targetBot);
testMax = getMaxHeight(targetRectangle, DirectionalHint.topCenter, 0, bounds);
// Test for maxHeight from top of target to top of bounds
expect(testMax).toBe(targetTop);
testMax = getMaxHeight(targetRectangle, DirectionalHint.rightCenter, 0, bounds);
// Test for maxHeight from top of target to bottom of bounds
expect(testMax).toBe(1000 - targetTop);
});
it('Correctly determines max height with a gapSpace included', () => {
const getMaxHeight = __positioningTestPackage._getMaxHeightFromTargetRectangle;
let targetTop;
let targetBot;
const targetRight = (targetBot = 200);
const targetLeft = (targetTop = 100);
const targetRectangle = new Rectangle(targetLeft, targetRight, targetTop, targetBot);
const bounds = new Rectangle(0, 1000, 0, 1000);
const gapSpace = 10;
let testMax = getMaxHeight(targetRectangle, DirectionalHint.bottomCenter, gapSpace, bounds);
// Test for maxHeight from bottom of target to bottom of bounds
expect(testMax).toBe(1000 - targetBot - gapSpace);
testMax = getMaxHeight(targetRectangle, DirectionalHint.topCenter, gapSpace, bounds);
// Test for maxHeight from top of target to top of bounds
expect(testMax).toBe(targetTop - gapSpace);
testMax = getMaxHeight(targetRectangle, DirectionalHint.rightCenter, gapSpace, bounds);
// Test for maxHeight from top of target to bottom of bounds
expect(testMax).toBe(1000 - targetTop - gapSpace);
});
it('Correctly determines the correct edges to return', () => {
// Create a dummy host, this isn't the part that we care about for this test
const host = {
getBoundingClientRect: () => {
return {
bottom: 0,
top: 0,
left: 0,
right: 0,
width: 0,
height: 0,
};
},
};
// create a dummy beak
const beakPos = new Rectangle(8, -8, 8, -8);
const pos: IElementPosition = {
elementRectangle: new Rectangle(400, 500, 400, 500),
targetEdge: RectangleEdge.top,
alignmentEdge: RectangleEdge.left,
};
const bounds = new Rectangle(0, 501, 0, 501);
const flushBounds = new Rectangle(0, 500, 0, 500);
const target = new Rectangle(0, 100, 0, 100);
// Normal positioning should target the alignment edge and the opposite of the target edge.
// In this case, that's left (alignment) and bottom (opposite of target)
let finalizedPosition = __positioningTestPackage._finalizePositionData(pos, host as any);
expect(finalizedPosition.elementPosition.left).toBeDefined();
expect(finalizedPosition.elementPosition.bottom).toBeDefined();
expect(finalizedPosition.elementPosition.top).toBeUndefined();
// Cover positioning should target the alignment edge and the target edge.
// In this case, that's left (alignment) and top (target)
finalizedPosition = __positioningTestPackage._finalizePositionData(pos, host as any, undefined, true);
expect(finalizedPosition.elementPosition.left).toBeDefined();
expect(finalizedPosition.elementPosition.top).toBeDefined();
expect(finalizedPosition.elementPosition.bottom).toBeUndefined();
// With bounds introduced, if the elementRectangle is closer to one edge of bounds than another,
// should align to edge closest to bounds
// In this case, that's bottom (opposite of target) and right (closer to edge of bounds)
finalizedPosition = __positioningTestPackage._finalizePositionData(pos, host as any, bounds);
expect(finalizedPosition.elementPosition.right).toBeDefined();
expect(finalizedPosition.elementPosition.bottom).toBeDefined();
expect(finalizedPosition.elementPosition.left).toBeUndefined();
// With bounds introduced, if the elementRectangle is closer to one edge of bounds than another,
// but it has already been positioned previously, then don't change the edge
// In this case, that's bottom (opposite of target) and left
finalizedPosition = __positioningTestPackage._finalizePositionData(pos, host as any, bounds, false, true);
expect(finalizedPosition.elementPosition.left).toBeDefined();
expect(finalizedPosition.elementPosition.bottom).toBeDefined();
expect(finalizedPosition.elementPosition.right).toBeUndefined();
// With bounds flush against the edge of the elementRectangle, change the edge such that the elementRectangle
// will grow correctly but will not visually change
// In this case, that's bottom (opposite of target) and right (flush against the bounds)
finalizedPosition = __positioningTestPackage._finalizePositionData(pos, host as any, flushBounds, false, true);
expect(finalizedPosition.elementPosition.left).toBeUndefined();
expect(finalizedPosition.elementPosition.bottom).toBeDefined();
expect(finalizedPosition.elementPosition.right).toBeDefined();
// With bounds introduced, the alignment should apply to the beak as well, aligning it to
// the edge closest to bounds
// In this case, that's the bottom (opposite of target) and right (closer to edge of bounds)
const finalizedBeakPosition = __positioningTestPackage._finalizeBeakPosition(
{ ...pos, targetRectangle: target },
beakPos,
bounds,
);
expect(finalizedBeakPosition.elementPosition.right).toBeDefined();
expect(finalizedBeakPosition.elementPosition.bottom).toBeDefined();
expect(finalizedBeakPosition.elementPosition.left).toBeUndefined();
});
it('Correctly determines the correct edges to return when against bounds', () => {
// Create a dummy host, this isn't the part that we care about for this test
const host = {
getBoundingClientRect: () => {
return {
bottom: 0,
top: 0,
left: 0,
right: 0,
width: 0,
height: 0,
};
},
};
// create a dummy beak
const pos: IElementPosition = {
elementRectangle: new Rectangle(400, 500, 400, 500),
targetEdge: RectangleEdge.top,
alignmentEdge: RectangleEdge.left,
};
const bounds = new Rectangle(0, 500, 0, 500);
// When we allow finalizing the return edge, we should specify the bottom such that the host grows away from
// the edge of the bounds
// In this case, that's the bottom (opposite of target) and right (closer to edge of bounds)
let finalizedPosition = __positioningTestPackage._finalizePositionData(pos, host as any, bounds, false, false);
expect(finalizedPosition.elementPosition.right).toBeDefined();
expect(finalizedPosition.elementPosition.bottom).toBeDefined();
expect(finalizedPosition.elementPosition.top).toBeUndefined();
// When we don't allow finalizing the return edge, but the host is flush against the edge of the bounds,
// we should have the same result as before
// In this case, that's the bottom (opposite of target) and right (closer to edge of bounds)
finalizedPosition = __positioningTestPackage._finalizePositionData(pos, host as any, bounds, false, true);
expect(finalizedPosition.elementPosition.right).toBeDefined();
expect(finalizedPosition.elementPosition.bottom).toBeDefined();
expect(finalizedPosition.elementPosition.top).toBeUndefined();
});
});
describe('getBoundingRectangle', () => {
/**
* Window with typings for experimental features regarding Dual Screen devices.
*/
interface IWindowWithSegments extends Window {
getWindowSegments?: () => DOMRect[];
}
const __INNER_HEIGHT = 1080;
const __INNER_WIDTH = 1920;
it('Gets correct bounds in single screen scenarios where getWindowSegments call is not present', () => {
const target: Point = { left: 0, top: 0 };
const targetWindow: Partial<IWindowWithSegments> = {
innerHeight: __INNER_HEIGHT,
innerWidth: __INNER_WIDTH,
};
const validateBounds = {
top: 0,
left: 0,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT,
width: __INNER_WIDTH,
height: __INNER_HEIGHT,
};
expect(getBoundsFromTargetWindow(target, targetWindow as IWindowWithSegments)).toStrictEqual(validateBounds);
});
it('Gets correct bounds in single screen scenarios where getWindowSegments call is present', () => {
const target: Point = { left: 0, top: 0 };
const targetWindow: Partial<IWindowWithSegments> = {
innerHeight: __INNER_HEIGHT,
innerWidth: __INNER_WIDTH,
getWindowSegments: () => {
return [
{
x: 0,
y: 0,
top: 0,
left: 0,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT,
width: __INNER_WIDTH,
height: __INNER_HEIGHT,
},
] as DOMRect[];
},
};
const validateBounds = {
top: 0,
left: 0,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT,
width: __INNER_WIDTH,
height: __INNER_HEIGHT,
};
expect(getBoundsFromTargetWindow(target, targetWindow as IWindowWithSegments)).toStrictEqual(validateBounds);
});
describe('Horizontal fold dual screen scenarios', () => {
const leftRightDualScreenTargetWindow: IWindowWithSegments = {
innerHeight: __INNER_HEIGHT,
innerWidth: __INNER_WIDTH,
getWindowSegments: () => {
return [
{
x: 0,
y: 0,
left: 0,
top: 0,
right: __INNER_WIDTH / 3,
bottom: __INNER_HEIGHT,
width: __INNER_WIDTH / 3,
height: __INNER_HEIGHT,
},
{
x: __INNER_WIDTH / 3,
y: 0,
left: __INNER_WIDTH / 3,
top: 0,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT,
width: (__INNER_WIDTH * 2) / 3,
height: __INNER_HEIGHT,
},
] as DOMRect[];
},
} as IWindowWithSegments;
const validateBoundsLeftScreen = {
top: 0,
left: 0,
right: __INNER_WIDTH / 3,
bottom: __INNER_HEIGHT,
width: __INNER_WIDTH / 3,
height: __INNER_HEIGHT,
};
const validateBoundsRightScreen = {
top: 0,
left: __INNER_WIDTH / 3,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT,
width: (__INNER_WIDTH * 2) / 3,
height: __INNER_HEIGHT,
};
it('Gets the 0 values as bounds in horizontal fold dual screen scenarios when null is passed as the target', () => {
const target = null;
const validateBounds = {
top: 0,
left: 0,
right: 0,
bottom: 0,
width: 0,
height: 0,
};
expect(getBoundsFromTargetWindow(target, leftRightDualScreenTargetWindow)).toStrictEqual(validateBounds);
});
it('Gets correct bounds in horizontal fold dual screen scenarios when Elements are passed as targets', () => {
const targetWithinLeftScreen = {
getBoundingClientRect: () =>
({
x: 100,
y: 100,
left: 100,
top: 100,
right: 300,
bottom: 300,
width: 200,
height: 200,
} as DOMRect),
} as Element;
expect(getBoundsFromTargetWindow(targetWithinLeftScreen, leftRightDualScreenTargetWindow)).toStrictEqual(
validateBoundsLeftScreen,
);
const targetWithinRightScreen = {
getBoundingClientRect: () =>
({
x: 1000,
y: 100,
left: 1000,
top: 100,
right: 1300,
bottom: 300,
width: 300,
height: 200,
} as DOMRect),
} as Element;
expect(getBoundsFromTargetWindow(targetWithinRightScreen, leftRightDualScreenTargetWindow)).toStrictEqual(
validateBoundsRightScreen,
);
const targetCrossingScreensWithCenterOnLeftScreen = {
getBoundingClientRect: () =>
({
x: 500,
y: 100,
left: 500,
top: 100,
right: 700,
bottom: 300,
width: 200,
height: 200,
} as DOMRect),
} as Element;
expect(
getBoundsFromTargetWindow(targetCrossingScreensWithCenterOnLeftScreen, leftRightDualScreenTargetWindow),
).toStrictEqual(validateBoundsLeftScreen);
const targetCrossingScreensWithCenterOnRightScreen = {
getBoundingClientRect: () =>
({
x: 600,
y: 100,
left: 600,
top: 100,
right: 800,
bottom: 300,
width: 200,
height: 200,
} as DOMRect),
} as Element;
expect(
getBoundsFromTargetWindow(targetCrossingScreensWithCenterOnRightScreen, leftRightDualScreenTargetWindow),
).toStrictEqual(validateBoundsRightScreen);
});
it('Gets correct bounds in horizontal fold dual screen scenarios when MouseEvents are passed as targets', () => {
const targetWithinLeftScreen = {
x: 150,
y: 150,
} as MouseEvent;
expect(getBoundsFromTargetWindow(targetWithinLeftScreen, leftRightDualScreenTargetWindow)).toStrictEqual(
validateBoundsLeftScreen,
);
const targetWithinRightScreen = {
x: 1000,
y: 1000,
} as MouseEvent;
expect(getBoundsFromTargetWindow(targetWithinRightScreen, leftRightDualScreenTargetWindow)).toStrictEqual(
validateBoundsRightScreen,
);
});
it('Gets correct bounds in horizontal fold dual screen scenarios when Points are passed as targets', () => {
const targetWithinLeftScreen: Point = {
left: 150,
top: 150,
};
expect(getBoundsFromTargetWindow(targetWithinLeftScreen, leftRightDualScreenTargetWindow)).toStrictEqual(
validateBoundsLeftScreen,
);
const targetWithinRightScreen: Point = {
left: 1000,
top: 1000,
};
expect(getBoundsFromTargetWindow(targetWithinRightScreen, leftRightDualScreenTargetWindow)).toStrictEqual(
validateBoundsRightScreen,
);
});
});
describe('Vertical fold dual screen scenarios', () => {
const topBottomDualScreenTargetWindow: IWindowWithSegments = {
innerHeight: __INNER_HEIGHT,
innerWidth: __INNER_WIDTH,
getWindowSegments: () => {
return [
{
x: 0,
y: 0,
left: 0,
top: 0,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT / 3,
width: __INNER_WIDTH,
height: __INNER_HEIGHT / 3,
},
{
x: 0,
y: __INNER_HEIGHT / 3,
left: 0,
top: __INNER_HEIGHT / 3,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT,
width: __INNER_WIDTH,
height: (__INNER_HEIGHT * 2) / 3,
},
] as DOMRect[];
},
} as IWindowWithSegments;
const validateBoundsTopScreen = {
left: 0,
top: 0,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT / 3,
width: __INNER_WIDTH,
height: __INNER_HEIGHT / 3,
};
const validateBoundsBottomScreen = {
left: 0,
top: __INNER_HEIGHT / 3,
right: __INNER_WIDTH,
bottom: __INNER_HEIGHT,
width: __INNER_WIDTH,
height: (__INNER_HEIGHT * 2) / 3,
};
it('Gets the 0 values as bounds in vertical fold dual screen scenarios when null is passed as the target', () => {
const target = null;
const validateBounds = {
top: 0,
left: 0,
right: 0,
bottom: 0,
width: 0,
height: 0,
};
expect(getBoundsFromTargetWindow(target, topBottomDualScreenTargetWindow)).toStrictEqual(validateBounds);
});
it('Gets correct bounds in vertical fold dual screen scenarios when Elements are passed as targets', () => {
const targetWithinTopScreen = {
getBoundingClientRect: () =>
({
x: 100,
y: 100,
left: 100,
top: 100,
right: 300,
bottom: 300,
width: 200,
height: 200,
} as DOMRect),
} as Element;
expect(getBoundsFromTargetWindow(targetWithinTopScreen, topBottomDualScreenTargetWindow)).toStrictEqual(
validateBoundsTopScreen,
);
const targetWithinBottomScreen = {
getBoundingClientRect: () =>
({
x: 100,
y: 800,
left: 100,
top: 800,
right: 300,
bottom: 1000,
width: 200,
height: 200,
} as DOMRect),
} as Element;
expect(getBoundsFromTargetWindow(targetWithinBottomScreen, topBottomDualScreenTargetWindow)).toStrictEqual(
validateBoundsBottomScreen,
);
const targetCrossingScreensWithCenterOnTopScreen = {
getBoundingClientRect: () =>
({
x: 500,
y: 200,
left: 500,
top: 200,
right: 700,
bottom: 400,
width: 200,
height: 200,
} as DOMRect),
} as Element;
expect(
getBoundsFromTargetWindow(targetCrossingScreensWithCenterOnTopScreen, topBottomDualScreenTargetWindow),
).toStrictEqual(validateBoundsTopScreen);
const targetCrossingScreensWithCenterOnBottomScreen = {
getBoundingClientRect: () =>
({
x: 600,
y: 300,
left: 600,
top: 300,
right: 800,
bottom: 500,
width: 200,
height: 200,
} as DOMRect),
} as Element;
expect(
getBoundsFromTargetWindow(targetCrossingScreensWithCenterOnBottomScreen, topBottomDualScreenTargetWindow),
).toStrictEqual(validateBoundsBottomScreen);
});
it('Gets correct bounds in vertical fold dual screen scenarios when MouseEvents are passed as targets', () => {
const targetWithinTopScreen = {
x: 150,
y: 150,
} as MouseEvent;
expect(getBoundsFromTargetWindow(targetWithinTopScreen, topBottomDualScreenTargetWindow)).toStrictEqual(
validateBoundsTopScreen,
);
const targetWithinBottomScreen = {
x: 1000,
y: 1000,
} as MouseEvent;
expect(getBoundsFromTargetWindow(targetWithinBottomScreen, topBottomDualScreenTargetWindow)).toStrictEqual(
validateBoundsBottomScreen,
);
});
it('Gets correct bounds in vertical fold dual screen scenarios when Points are passed as targets', () => {
const targetWithinTopScreen: Point = {
left: 150,
top: 150,
};
expect(getBoundsFromTargetWindow(targetWithinTopScreen, topBottomDualScreenTargetWindow)).toStrictEqual(
validateBoundsTopScreen,
);
const targetWithinBottomScreen: Point = {
left: 1000,
top: 1000,
};
expect(getBoundsFromTargetWindow(targetWithinBottomScreen, topBottomDualScreenTargetWindow)).toStrictEqual(
validateBoundsBottomScreen,
);
});
});
}); | the_stack |
// Custom Typings for Taiko - https://docs.taiko.dev/api/reference
// eslint-disable-next-line no-unused-vars
import Protocol from 'devtools-protocol';
export type Cookie = Protocol.Network.Cookie;
export type BrowserEvent =
| 'DOMContentLoaded'
| 'loadEventFired'
| 'networkAlmostIdle'
| 'networkIdle'
| 'firstPaint'
| 'firstContentfulPaint'
| 'firstMeaningfulPaint'
| 'targetNavigated';
/**
* Options
*/
export interface BrowserOptions {
headless?: boolean;
args?: string[];
host?: string;
port?: number;
ignoreCertificateErrors?: boolean;
observe?: boolean;
observeTime?: number;
dumpio?: boolean;
}
export interface EventOptions {
waitForEvents?: BrowserEvent[];
}
export interface VeryBasicNavigationOptions extends ForceOption {
waitForNavigation?: boolean;
}
export interface BasicNavigationOptions extends VeryBasicNavigationOptions {
navigationTimeout?: number;
}
export interface NavigationOptions extends BasicNavigationOptions, EventOptions {
headers?: object;
waitForStart?: number;
}
export interface ReloadOptions extends NavigationOptions {
ignoreCache?: boolean;
}
export interface ClickOptions extends NavigationOptions, ForceOption {
button?: 'left' | 'right' | 'middle';
clickCount?: number;
position?: string;
elementsToMatch?: number;
}
export interface GlobalConfigurationOptions {
navigationTimeout?: number;
observeTime?: number;
retryInterval?: number;
retryTimeout?: number;
noOfElementToMatch?: number;
observe?: boolean;
waitForNavigation?: boolean;
waitForEvents?: BrowserEvent[];
ignoreSSLErrors?: boolean;
headful?: boolean;
criConnectionRetries?: number;
firefox?: boolean;
highlightOnAction?: 'true' | 'false';
local?: boolean;
}
export interface TapOptions extends BasicNavigationOptions, EventOptions, ForceOption {}
export interface KeyOptions extends NavigationOptions {
text?: string;
delay?: number;
}
export interface WriteOptions extends NavigationOptions, ForceOption {
delay?: number;
hideText?: boolean;
}
export interface ScreenshotOptions {
path?: string;
fullPage?: boolean;
encoding?: string;
}
// TODO: remove this type declaration and replace with devtools-protocol Emulation.SetDeviceMetricsOverrideRequest
export interface ViewPortOptions {
width: number;
height: number;
deviceScaleFactor?: number;
mobile?: boolean;
scale?: number;
screenWidth?: number;
screenHeight?: number;
positionX?: number;
positionY?: number;
dontSetVisibleSize?: boolean;
screenOrientation?: ViewPortScreenOrientation;
viewport?: ViewPort;
}
export interface CookieOptions {
url?: string;
domain?: string;
path?: string;
}
export interface ResizeWindowOptions {
height?: number;
width?: number;
}
export interface CookieDetailOptions extends CookieOptions {
secure?: boolean;
httpOnly?: boolean;
sameSite?: string;
expires?: number;
}
export interface LocationOptions {
latitude: number;
longitude: number;
accuracy?: number;
}
export interface ProximitySelectorNearOptions {
offset: number;
}
export interface EvaluateHandlerArgs {
[key: string]: any;
}
export interface EvaluateOptions extends Omit<NavigationOptions, 'headers'> {
args?: EvaluateHandlerArgs;
}
export interface DollarOptions {
args?: any;
}
export interface TableCellOptions {
row: number;
col: number;
}
export interface MatchingOptions {
exactMatch?: boolean;
}
export interface OpenWindowOrTabOptions extends NavigationOptions {
name: string;
}
export interface BasicResponse {
url: string;
status: { code: number; text: string };
}
export interface Response extends BasicResponse {
redirectedResponse?: BasicResponse[];
}
export interface ForceOption {
force?: boolean;
}
export interface ForcedNavigationOptions extends NavigationOptions, ForceOption {}
/**
* Elements, Selectors and Searches
*/
export interface Element {
objectId: string;
description?: string;
runtimeHandler?: any;
get(): string;
text(): Promise<string>;
value(): Promise<string>;
select(value?: string | number): Promise<void>;
check(): Promise<void>;
uncheck(): Promise<void>;
isChecked(): Promise<boolean>;
deselect(): Promise<void>;
isSelected(): Promise<boolean>;
isVisible(): Promise<boolean>;
create(objectIds: string[], runtimeHandler?: any): Element[];
isDisabled(): Promise<boolean>;
isDraggable(): Promise<boolean>;
}
export interface ElementWrapper {
get(retryInterval?: number, retryTimeout?: number): Promise<ElementWrapper>;
readonly description: string;
exists(retryInterval?: number, retryTimeout?: number): Promise<boolean>;
text(): Promise<string>;
isVisible(retryInterval?: number, retryTimeout?: number): Promise<boolean>;
isDisabled(retryInterval?: number, retryTimeout?: number): Promise<boolean>;
isDraggable(retryInterval?: number, retryTimeout?: number): Promise<boolean>;
attribute(name: string): Promise<string>;
elements(retryInterval?: number, retryTimeout?: number): Promise<Element[]>;
element(index: number, retryInterval?: number, retryTimeout?: number): Promise<Element>;
}
export interface ValueWrapper extends ElementWrapper {
value(): Promise<string>;
}
export interface ButtonWrapper extends ElementWrapper {}
export interface DollarWrapper extends ElementWrapper {}
export interface ImageWrapper extends ElementWrapper {}
export interface LinkWrapper extends ElementWrapper {}
export interface ListItemWrapper extends ElementWrapper {}
export interface TableCellWrapper extends ElementWrapper {}
export interface TextWrapper extends ElementWrapper {}
export interface ColorWrapper extends ValueWrapper {
select(value?: string | number): Promise<void>;
}
export interface FileFieldWrapper extends ValueWrapper {}
export interface TextBoxWrapper extends ValueWrapper {}
export interface DropDownWrapper extends ValueWrapper {
select(value?: string | number | string[] | number[] | { index: number[] }): Promise<void>;
}
export interface TimeFieldWrapper extends ValueWrapper {
select(value?: Date): Promise<void>;
}
export interface RangeWrapper extends ValueWrapper {
select(value?: string | number): Promise<void>;
}
export interface CheckBoxWrapper extends ElementWrapper {
check(): Promise<void>;
uncheck(): Promise<void>;
isChecked(): Promise<boolean>;
}
export interface RadioButtonWrapper extends ElementWrapper {
select(value?: string | number): Promise<void>;
deselect(): Promise<void>;
isSelected(): Promise<boolean>;
}
// BasicSelector mimics isSelector
export interface BasicSelector {
elements: Element[] | MatchingNode[] | string[];
exists(retryInterval?: number, retryTimeout?: number): Promise<boolean>;
[key: string]: any;
}
export interface MatchingNode {
elem: Element;
dist: number;
}
/**
* a relative search element is returned by proximity methods such as near,
*/
export interface RelativeSearchElement {
desc: string;
condition(element: Element, value: number): boolean;
findProximityElementRects(): { elem: Element; result: any }; // result is wrapped in a callback
validNodes(objectId: Element): MatchingNode;
}
// isSelector also allows ElementWrapper instances
export type Selector = BasicSelector | ElementWrapper;
// SearchElement mimics isSelector, isString, isElement and also allows relative search elements
export type SearchElement = string | Selector | Element | RelativeSearchElement | object;
export interface AttrValuePairs {
[key: string]: string;
}
/**
* Intercept
*/
export type InterceptRedirectUrl = string;
export interface InterceptMockData {
[key: string]: any;
}
export interface InterceptRequest {
continue(overrides?: {
url?: string;
method?: string;
postData?: string;
headers?: Record<string, unknown>;
}): Promise<void>;
respond(response: InterceptMockData): Promise<void>;
requestId: string;
request: {
url: string;
method: string;
headers: { [key: string]: string };
postData?: string;
hasPostData: boolean;
postDataEntries: Array<{ bytes: string }>;
initialPriority: string;
referrerPolicy: string;
};
frameId: string;
resourceType: string;
networkId: string;
}
export type interceptRequestHandler = (request: InterceptRequest) => Promise<void>;
/**
* Viewport
*/
export interface ViewPortScreenOrientation {
type: 'portraitPrimary' | 'portraitSecondary' | 'landscapePrimary' | 'landscapeSecondary';
angle: number;
}
export interface ViewPort {
x: number;
y: number;
width: number;
height: number;
scale: number;
}
/**
* Distances
*/
export interface DragAndDropDistance {
up: number;
down: number;
left: number;
right: number;
}
/**
* Coordinates
*/
export interface MouseCoordinates {
x: number;
y: number;
}
/**
* Browser Actions
*/
// https://docs.taiko.dev/api/openbrowser
export function openBrowser(options?: BrowserOptions): Promise<void>;
// https://docs.taiko.dev/api/closebrowser
export function closeBrowser(): Promise<void>;
// https://docs.taiko.dev/api/client
export function client(): any; // TODO: no TS Bindings available: https://github.com/cyrus-and/chrome-remote-interface/issues/112
// https://docs.taiko.dev/api/switchto
// TODO: fix corresponding JSDoc in lib/taiko.js
export function switchTo(target: RegExp | OpenWindowOrTabOptions): Promise<void>;
// https://docs.taiko.dev/api/intercept
// https://github.com/getgauge/taiko/issues/98#issuecomment-42024186
export function intercept(
requestUrl: string,
options?: InterceptMockData | interceptRequestHandler | InterceptRedirectUrl,
): Promise<void>;
// https://docs.taiko.dev/api/emulatenetwork
export function emulateNetwork(
networkType:
| 'GPRS'
| 'Regular2G'
| 'Good2G'
| 'Good3G'
| 'Regular3G'
| 'Regular4G'
| 'DSL'
| 'WiFi'
| 'Offline'
| {
offline?: boolean;
downloadThroughput?: number;
uploadThroughput?: number;
latency?: number;
},
): Promise<void>;
// https://docs.taiko.dev/api/emulatedevice
export function emulateDevice(deviceModel: string): Promise<void>;
// https://docs.taiko.dev/api/setviewport
export function setViewPort(options: ViewPortOptions): Promise<void>;
export function resizeWindow(options: ResizeWindowOptions): Promise<void>;
// https://docs.taiko.dev/api/emulateTimezone
export function emulateTimezone(timezoneId: string): Promise<void>;
// https://docs.taiko.dev/api/opentab
export function openTab(
targetUrl?: string | OpenWindowOrTabOptions,
options?: OpenWindowOrTabOptions,
): Promise<void>;
// https://docs.taiko.dev/api/closetab
export function closeTab(targetUrl?: string | RegExp): Promise<void>;
// https://docs.taiko.dev/api/openincognitowindow
export function openIncognitoWindow(
url?: string | OpenWindowOrTabOptions,
options?: OpenWindowOrTabOptions,
): Promise<void>;
// https://docs.taiko.dev/api/closeincognitowindow
export function closeIncognitoWindow(name: string): Promise<void>;
// https://docs.taiko.dev/api/overridepermissions
// TODO: use the proper type for the second param from devtools-protocol
export function overridePermissions(origin: string, permissions: string[]): Promise<void>;
// https://docs.taiko.dev/api/clearpermissionoverrides
export function clearPermissionOverrides(): Promise<void>;
// https://docs.taiko.dev/api/setcookie
export function setCookie(
name: string,
value: string,
options?: CookieDetailOptions,
): Promise<void>;
// https://docs.taiko.dev/api/deletecookies
export function deleteCookies(cookieName?: string, options?: CookieOptions): Promise<void>;
// https://docs.taiko.dev/api/getcookies
export function getCookies(options?: { urls: string[] }): Promise<Cookie[]>;
// https://docs.taiko.dev/api/setlocation
export function setLocation(options: LocationOptions): Promise<void>;
/**
* Page Actions
*/
// https://docs.taiko.dev/api/goto
export function goto(url: string, options?: NavigationOptions): Promise<Response>;
// https://docs.taiko.dev/api/reload
export function reload(url?: string, options?: ReloadOptions): Promise<void>;
// https://docs.taiko.dev/api/goback
export function goBack(options?: NavigationOptions): Promise<void>;
// https://docs.taiko.dev/api/goforward
export function goForward(options?: NavigationOptions): Promise<void>;
// https://docs.taiko.dev/api/title
export function title(): Promise<string>;
// https://docs.taiko.dev/api/click
export function click(
selector: SearchElement | MouseCoordinates,
options?: ClickOptions | RelativeSearchElement,
...args: RelativeSearchElement[]
): Promise<void>;
// https://docs.taiko.dev/api/doubleclick
export function doubleClick(
selector: SearchElement | MouseCoordinates,
options?: VeryBasicNavigationOptions | RelativeSearchElement,
...args: RelativeSearchElement[]
): Promise<void>;
// https://docs.taiko.dev/api/rightclick
export function rightClick(
selector: SearchElement | MouseCoordinates,
options?: VeryBasicNavigationOptions | RelativeSearchElement,
...args: RelativeSearchElement[]
): Promise<void>;
// https://docs.taiko.dev/api/draganddrop
export function dragAndDrop(
source: SearchElement,
destinationOrDistance: SearchElement | DragAndDropDistance,
options?: ForceOption,
): Promise<void>;
// https://docs.taiko.dev/api/hover
export function hover(selector: SearchElement, options?: ForcedNavigationOptions): Promise<void>;
// https://docs.taiko.dev/api/focus
export function focus(selector: SearchElement, options?: ForcedNavigationOptions): Promise<void>;
// https://docs.taiko.dev/api/write
export function write(text: string, into?: SearchElement, options?: WriteOptions): Promise<void>;
// https://docs.taiko.dev/api/clear
export function clear(selector?: SearchElement, options?: ForcedNavigationOptions): Promise<void>;
// https://docs.taiko.dev/api/attach
export function attach(filepath: string, to: SearchElement, options?: ForceOption): Promise<void>;
// https://docs.taiko.dev/api/press
export function press(keys: string | string[], options?: KeyOptions): Promise<void>;
// https://docs.taiko.dev/api/highlight
export function highlight(selector: SearchElement, ...args: RelativeSearchElement[]): Promise<void>;
// https://docs.taiko.dev/api/clearHighlights
export function clearHighlights(): Promise<void>;
// https://docs.taiko.dev/api/mouseaction
export function mouseAction(
selector: SearchElement | 'press' | 'move' | 'release',
action?: 'press' | 'move' | 'release' | MouseCoordinates,
coordinates?: MouseCoordinates | NavigationOptions,
options?: ForcedNavigationOptions,
): Promise<void>;
// https://docs.taiko.dev/api/scrollto
export function scrollTo(selector: SearchElement, options?: NavigationOptions): Promise<void>;
// https://docs.taiko.dev/api/scrollright
export function scrollRight(selector?: SearchElement | number, px?: number): Promise<void>;
// https://docs.taiko.dev/api/scrollleft
export function scrollLeft(selector?: SearchElement | number, px?: number): Promise<void>;
// https://docs.taiko.dev/api/scrollup
export function scrollUp(selector?: SearchElement | number, px?: number): Promise<void>;
// https://docs.taiko.dev/api/scrolldown
export function scrollDown(selector?: SearchElement | number, px?: number): Promise<void>;
// https://docs.taiko.dev/api/screenshot
export function screenshot(
selector?: SearchElement,
options?: ScreenshotOptions,
): Promise<Buffer | undefined>;
// https://docs.taiko.dev/api/tap
export function tap(
selector: SearchElement,
options?: TapOptions | RelativeSearchElement,
...args: SearchElement[]
): Promise<void>;
/**
* Selectors
*/
// https://docs.taiko.dev/api/$
export function $(
selector: string | ((args?: any) => any),
_options?: DollarOptions | RelativeSearchElement,
...args: RelativeSearchElement[]
): DollarWrapper;
// https://docs.taiko.dev/api/image
export function image(
selector: SearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): ImageWrapper;
// https://docs.taiko.dev/api/link
export function link(
selector: SearchElement,
options?: RelativeSearchElement,
...args: SearchElement[]
): LinkWrapper;
// https://docs.taiko.dev/api/listitem
export function listItem(
selector: SearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): ListItemWrapper;
// https://docs.taiko.dev/api/button
export function button(
selector: SearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): ButtonWrapper;
// https://docs.taiko.dev/api/filefield
export function fileField(
selector: SearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): FileFieldWrapper;
// https://docs.taiko.dev/api/timefield
export function timeField(
selector: SearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): TimeFieldWrapper;
// https://docs.taiko.dev/api/range
export function range(
selector: SearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): RangeWrapper;
// https://docs.taiko.dev/api/color
export function color(
selector: SearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): ColorWrapper;
// https://docs.taiko.dev/api/tableCell
export function tableCell(
options?: TableCellOptions | SearchElement,
selector?: SearchElement,
...args: RelativeSearchElement[]
): TableCellWrapper;
// https://docs.taiko.dev/api/textbox
export function textBox(
labelOrAttrValuePairs?: string | AttrValuePairs | RelativeSearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): TextBoxWrapper;
// https://docs.taiko.dev/api/dropdown
export function dropDown(
labelOrAttrValuePairs?: string | AttrValuePairs | RelativeSearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): DropDownWrapper;
// https://docs.taiko.dev/api/checkbox
export function checkBox(
labelOrAttrValuePairs?: string | AttrValuePairs | RelativeSearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): CheckBoxWrapper;
// https://docs.taiko.dev/api/radiobutton
export function radioButton(
selector: SearchElement,
options?: RelativeSearchElement,
...args: RelativeSearchElement[]
): RadioButtonWrapper;
// https://docs.taiko.dev/api/text
export function text(
selector: string | RegExp,
options?: MatchingOptions | RelativeSearchElement,
...args: RelativeSearchElement[]
): TextWrapper;
/**
* Proximity Selectors
*/
// https://docs.taiko.dev/api/toleftof
export function toLeftOf(selector: SearchElement | ElementWrapper): RelativeSearchElement;
// https://docs.taiko.dev/api/torightof
export function toRightOf(selector: SearchElement | ElementWrapper): RelativeSearchElement;
// https://docs.taiko.dev/api/above
export function above(selector: SearchElement | ElementWrapper): RelativeSearchElement;
// https://docs.taiko.dev/api/below
export function below(selector: SearchElement | ElementWrapper): RelativeSearchElement;
// https://docs.taiko.dev/api/within
export function within(selector: SearchElement | ElementWrapper): RelativeSearchElement;
// https://docs.taiko.dev/api/near
export function near(
selector: SearchElement | ElementWrapper,
opts?: ProximitySelectorNearOptions,
): RelativeSearchElement;
/**
* Events
*/
export interface DialogValue {
message: string;
type: string;
url: string;
defaultPrompt: string;
}
export type DialogHandler = (value: DialogValue) => void;
// https://docs.taiko.dev/api/alert
export function alert(
messageOrCallback: string | RegExp | DialogHandler,
callback?: DialogHandler,
): void;
// https://docs.taiko.dev/api/prompt
export function prompt(
messageOrCallback: string | RegExp | DialogHandler,
callback?: DialogHandler,
): void;
// https://docs.taiko.dev/api/confirm
export function confirm(
messageOrCallback: string | RegExp | DialogHandler,
callback?: DialogHandler,
): void;
// https://docs.taiko.dev/api/beforeunload
export function beforeunload(callback: () => Promise<void>): void;
export type EvaluateHandler<T> = (element: HTMLElement, args?: EvaluateHandlerArgs) => T;
/**
* Helpers
*/
// https://docs.taiko.dev/api/evaluate
export function evaluate<T>(
selector?: Selector | string | EvaluateHandler<T>,
handlerCallback?: EvaluateHandler<T>,
options?: EvaluateOptions,
): Promise<T>;
// https://docs.taiko.dev/api/to
export function to<T extends string | Selector>(value: T): T;
// https://docs.taiko.dev/api/into
export function into<T extends SearchElement>(value: T): T;
// https://docs.taiko.dev/api/accept
export function accept(text?: string): Promise<void>;
// https://docs.taiko.dev/api/dismiss
export function dismiss(): Promise<void>;
// https://docs.taiko.dev/api/setconfig
export function setConfig(options: GlobalConfigurationOptions): void;
// https://docs.taiko.dev/api/getconfig
export function getConfig(): GlobalConfigurationOptions;
export function getConfig<T extends keyof GlobalConfigurationOptions>(
option: T,
): Required<GlobalConfigurationOptions>[T];
// https://docs.taiko.dev/api/currenturl
export function currentURL(): Promise<string>;
// https://docs.taiko.dev/api/waitfor
export function waitFor(time: number): Promise<void>;
export function waitFor(
elementOrCondition: SearchElement | (() => Promise<boolean>),
time?: number,
): Promise<void>;
export function clearIntercept(requestUrl?: string): void;
// TODO
// trying to support recorder.repl, not sure this is the right approach
// export namespace recorder {
// export function repl(): Promise<void>;
// } | the_stack |
import * as coreClient from "@azure/core-client";
/** The response to an attestation policy operation */
export interface PolicyResponse {
/** An RFC7519 JSON Web Token structure whose body is an PolicyResult object. */
token: string;
}
/** An error response from Attestation. */
export interface CloudError {
/** An error response from Attestation. */
error?: CloudErrorBody;
}
/** An error response from Attestation. */
export interface CloudErrorBody {
/** An identifier for the error. Codes are invariant and are intended to be consumed programmatically. */
code?: string;
/** A message describing the error, intended to be suitable for displaying in a user interface. */
message?: string;
}
/** The response to an attestation policy management API */
export interface PolicyCertificatesResponse {
/** An RFC7519 JSON Web Token structure containing a PolicyCertificatesResults object which contains the certificates used to validate policy changes */
token: string;
}
/** The response to an attestation policy management API */
export interface PolicyCertificatesModifyResponse {
/** An RFC7519 JSON Web Token structure whose body is a PolicyCertificatesModificationResult object. */
token: string;
}
/** Attestation request for Intel SGX enclaves */
export interface AttestOpenEnclaveRequest {
/** OpenEnclave report from the enclave to be attested */
report?: Uint8Array;
/** Runtime data provided by the enclave at the time of report generation. The MAA will verify that the first 32 bytes of the report_data field of the quote contains the SHA256 hash of the decoded "data" field of the runtime data. */
runtimeData?: RuntimeData;
/** Base64Url encoded "InitTime data". The MAA will verify that the init data was known to the enclave. Note that InitTimeData is invalid for CoffeeLake processors. */
initTimeData?: InitTimeData;
/** Attest against the provided draft policy. Note that the resulting token cannot be validated. */
draftPolicyForAttestation?: string;
}
/** Defines the "run time data" provided by the attestation target for use by the MAA */
export interface RuntimeData {
/** UTF-8 encoded Runtime Data generated by the trusted environment */
data?: Uint8Array;
/** The type of data contained within the "data" field */
dataType?: DataType;
}
/** Defines the "initialization time data" used to provision the attestation target for use by the MAA */
export interface InitTimeData {
/** UTF-8 encoded Initialization Data passed into the trusted environment when it is created. */
data?: Uint8Array;
/** The type of data contained within the "data" field */
dataType?: DataType;
}
/** The result of an attestation operation */
export interface AttestationResponse {
/** An RFC 7519 JSON Web Token, the body of which is an AttestationResult object. */
token: string;
}
/** Attestation request for Intel SGX enclaves */
export interface AttestSgxEnclaveRequest {
/** Quote of the enclave to be attested */
quote?: Uint8Array;
/** Runtime data provided by the enclave at the time of quote generation. The MAA will verify that the first 32 bytes of the report_data field of the quote contains the SHA256 hash of the decoded "data" field of the runtime data. */
runtimeData?: RuntimeData;
/** Initialization data provided when the enclave is created. MAA will verify that the init data was known to the enclave. Note that InitTimeData is invalid for CoffeeLake processors. */
initTimeData?: InitTimeData;
/** Attest against the provided draft policy. Note that the resulting token cannot be validated. */
draftPolicyForAttestation?: string;
}
/** Attestation request for Trusted Platform Module (TPM) attestation. */
export interface TpmAttestationRequest {
/** Protocol data containing artifacts for attestation. */
data?: Uint8Array;
}
/** Attestation response for Trusted Platform Module (TPM) attestation. */
export interface TpmAttestationResponse {
/** Protocol data containing attestation service response. */
data?: Uint8Array;
}
export interface JsonWebKeySet {
/**
* The value of the "keys" parameter is an array of JWK values. By
* default, the order of the JWK values within the array does not imply
* an order of preference among them, although applications of JWK Sets
* can choose to assign a meaning to the order for their purposes, if
* desired.
*/
keys: JsonWebKey[];
}
export interface JsonWebKey {
/**
* The "alg" (algorithm) parameter identifies the algorithm intended for
* use with the key. The values used should either be registered in the
* IANA "JSON Web Signature and Encryption Algorithms" registry
* established by [JWA] or be a value that contains a Collision-
* Resistant Name.
*/
alg?: string;
/** The "crv" (curve) parameter identifies the curve type */
crv?: string;
/** RSA private exponent or ECC private key */
d?: string;
/** RSA Private Key Parameter */
dp?: string;
/** RSA Private Key Parameter */
dq?: string;
/** RSA public exponent, in Base64 */
e?: string;
/** Symmetric key */
k?: string;
/**
* The "kid" (key ID) parameter is used to match a specific key. This
* is used, for instance, to choose among a set of keys within a JWK Set
* during key rollover. The structure of the "kid" value is
* unspecified. When "kid" values are used within a JWK Set, different
* keys within the JWK Set SHOULD use distinct "kid" values. (One
* example in which different keys might use the same "kid" value is if
* they have different "kty" (key type) values but are considered to be
* equivalent alternatives by the application using them.) The "kid"
* value is a case-sensitive string.
*/
kid?: string;
/**
* The "kty" (key type) parameter identifies the cryptographic algorithm
* family used with the key, such as "RSA" or "EC". "kty" values should
* either be registered in the IANA "JSON Web Key Types" registry
* established by [JWA] or be a value that contains a Collision-
* Resistant Name. The "kty" value is a case-sensitive string.
*/
kty: string;
/** RSA modulus, in Base64 */
n?: string;
/** RSA secret prime */
p?: string;
/** RSA secret prime, with p < q */
q?: string;
/** RSA Private Key Parameter */
qi?: string;
/**
* Use ("public key use") identifies the intended use of
* the public key. The "use" parameter is employed to indicate whether
* a public key is used for encrypting data or verifying the signature
* on data. Values are commonly "sig" (signature) or "enc" (encryption).
*/
use?: string;
/** X coordinate for the Elliptic Curve point */
x?: string;
/**
* The "x5c" (X.509 certificate chain) parameter contains a chain of one
* or more PKIX certificates [RFC5280]. The certificate chain is
* represented as a JSON array of certificate value strings. Each
* string in the array is a base64-encoded (Section 4 of [RFC4648] --
* not base64url-encoded) DER [ITU.X690.1994] PKIX certificate value.
* The PKIX certificate containing the key value MUST be the first
* certificate.
*/
x5C?: string[];
/** Y coordinate for the Elliptic Curve point */
y?: string;
}
/** The body of the JWT used for the PolicyCertificates APIs */
export interface AttestationCertificateManagementBody {
/** RFC 7517 Json Web Key describing the certificate. */
policyCertificate?: JsonWebKey;
}
/** The result of a call to retrieve policy certificates. */
export interface PolicyCertificatesResult {
/** SHA256 Hash of the binary representation certificate which was added or removed */
policyCertificates: JsonWebKeySet;
}
/** The result of a policy certificate modification */
export interface PolicyCertificatesModificationResult {
/** Hex encoded SHA1 Hash of the binary representation certificate which was added or removed */
certificateThumbprint: string;
/** The result of the operation */
certificateResolution: CertificateModification;
}
export interface StoredAttestationPolicy {
/** Policy text to set as a sequence of UTF-8 encoded octets. */
attestationPolicy?: Uint8Array;
}
/** The result of a policy certificate modification */
export interface PolicyResult {
/** The result of the operation */
policyResolution: PolicyModification;
/** The SHA256 hash of the policy object modified */
policyTokenHash: Uint8Array;
/** The certificate used to sign the policy object, if specified */
policySigner?: JsonWebKey;
/** A JSON Web Token containing a StoredAttestationPolicy object with the attestation policy */
policy?: string;
}
/** A Microsoft Azure Attestation response token body - the body of a response token issued by MAA */
export interface GeneratedAttestationResult {
/** Unique Identifier for the token */
jti: string;
/** The Principal who issued the token */
iss: string;
/** The time at which the token was issued, in the number of seconds since 1970-01-0T00:00:00Z UTC */
iat?: number;
/** The expiration time after which the token is no longer valid, in the number of seconds since 1970-01-0T00:00:00Z UTC */
exp?: number;
/** The not before time before which the token cannot be considered valid, in the number of seconds since 1970-01-0T00:00:00Z UTC */
nbf?: number;
/** An RFC 7800 Proof of Possession Key */
cnf?: Record<string, unknown>;
/** The Nonce input to the attestation request, if provided. */
nonce?: string;
/** The Schema version of this structure. Current Value: 1.0 */
version: string;
/** Runtime Claims */
runtimeClaims?: Record<string, unknown>;
/** Inittime Claims */
inittimeClaims?: Record<string, unknown>;
/** Policy Generated Claims */
policyClaims?: Record<string, unknown>;
/** The Attestation type being attested. */
verifierType: string;
/** The certificate used to sign the policy object, if specified. */
policySigner?: JsonWebKey;
/** The SHA256 hash of the BASE64URL encoded policy text used for attestation */
policyHash: Uint8Array;
/** True if the enclave is debuggable, false otherwise */
isDebuggable: boolean;
/** The SGX Product ID for the enclave. */
productId: number;
/** The HEX encoded SGX MRENCLAVE value for the enclave. */
mrEnclave: string;
/** The HEX encoded SGX MRSIGNER value for the enclave. */
mrSigner: string;
/** The SGX SVN value for the enclave. */
svn: number;
/** A copy of the RuntimeData specified as an input to the attest call. */
enclaveHeldData?: Uint8Array;
/** The SGX SVN value for the enclave. */
sgxCollateral?: Record<string, unknown>;
/** DEPRECATED: Private Preview version of x-ms-ver claim. */
deprecatedVersion?: string;
/** DEPRECATED: Private Preview version of x-ms-sgx-is-debuggable claim. */
deprecatedIsDebuggable?: boolean;
/** DEPRECATED: Private Preview version of x-ms-sgx-collateral claim. */
deprecatedSgxCollateral?: Record<string, unknown>;
/** DEPRECATED: Private Preview version of x-ms-sgx-ehd claim. */
deprecatedEnclaveHeldData?: Uint8Array;
/** DEPRECATED: Private Preview version of x-ms-sgx-ehd claim. */
deprecatedEnclaveHeldData2?: Uint8Array;
/** DEPRECATED: Private Preview version of x-ms-sgx-product-id */
deprecatedProductId?: number;
/** DEPRECATED: Private Preview version of x-ms-sgx-mrenclave. */
deprecatedMrEnclave?: string;
/** DEPRECATED: Private Preview version of x-ms-sgx-mrsigner. */
deprecatedMrSigner?: string;
/** DEPRECATED: Private Preview version of x-ms-sgx-svn. */
deprecatedSvn?: number;
/** DEPRECATED: Private Preview version of x-ms-tee. */
deprecatedTee?: string;
/** DEPRECATED: Private Preview version of x-ms-policy-signer */
deprecatedPolicySigner?: JsonWebKey;
/** DEPRECATED: Private Preview version of x-ms-policy-hash */
deprecatedPolicyHash?: Uint8Array;
/** DEPRECATED: Private Preview version of nonce */
deprecatedRpData?: string;
}
/** Known values of {@link AttestationType} that the service accepts. */
export enum KnownAttestationType {
/** Intel Software Guard eXtensions */
SgxEnclave = "SgxEnclave",
/** OpenEnclave extensions to SGX */
OpenEnclave = "OpenEnclave",
/** Edge TPM Virtualization Based Security */
Tpm = "Tpm"
}
/**
* Defines values for AttestationType. \
* {@link KnownAttestationType} can be used interchangeably with AttestationType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **SgxEnclave**: Intel Software Guard eXtensions \
* **OpenEnclave**: OpenEnclave extensions to SGX \
* **Tpm**: Edge TPM Virtualization Based Security
*/
export type AttestationType = string;
/** Known values of {@link DataType} that the service accepts. */
export enum KnownDataType {
/** The contents of the field should be treated as binary and not interpreted by MAA. */
Binary = "Binary",
/** The contents of the field should be treated as a JSON object and may be further interpreted by MAA. */
Json = "JSON"
}
/**
* Defines values for DataType. \
* {@link KnownDataType} can be used interchangeably with DataType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Binary**: The contents of the field should be treated as binary and not interpreted by MAA. \
* **JSON**: The contents of the field should be treated as a JSON object and may be further interpreted by MAA.
*/
export type DataType = string;
/** Known values of {@link CertificateModification} that the service accepts. */
export enum KnownCertificateModification {
/** After the operation was performed, the certificate is in the set of certificates. */
IsPresent = "IsPresent",
/** After the operation was performed, the certificate is no longer present in the set of certificates. */
IsAbsent = "IsAbsent"
}
/**
* Defines values for CertificateModification. \
* {@link KnownCertificateModification} can be used interchangeably with CertificateModification,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **IsPresent**: After the operation was performed, the certificate is in the set of certificates. \
* **IsAbsent**: After the operation was performed, the certificate is no longer present in the set of certificates.
*/
export type CertificateModification = string;
/** Known values of {@link PolicyModification} that the service accepts. */
export enum KnownPolicyModification {
/** The specified policy object was updated. */
Updated = "Updated",
/** The specified policy object was removed. */
Removed = "Removed"
}
/**
* Defines values for PolicyModification. \
* {@link KnownPolicyModification} can be used interchangeably with PolicyModification,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Updated**: The specified policy object was updated. \
* **Removed**: The specified policy object was removed.
*/
export type PolicyModification = string;
/** Optional parameters. */
export interface PolicyGetOptionalParams extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type PolicyGetResponse = PolicyResponse;
/** Optional parameters. */
export interface PolicySetModelOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the set operation. */
export type PolicySetModelResponse = PolicyResponse;
/** Optional parameters. */
export interface PolicyResetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the reset operation. */
export type PolicyResetResponse = PolicyResponse;
/** Optional parameters. */
export interface PolicyCertificatesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type PolicyCertificatesGetResponse = PolicyCertificatesResponse;
/** Optional parameters. */
export interface PolicyCertificatesAddOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the add operation. */
export type PolicyCertificatesAddResponse = PolicyCertificatesModifyResponse;
/** Optional parameters. */
export interface PolicyCertificatesRemoveOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the remove operation. */
export type PolicyCertificatesRemoveResponse = PolicyCertificatesModifyResponse;
/** Optional parameters. */
export interface AttestationAttestOpenEnclaveOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the attestOpenEnclave operation. */
export type AttestationAttestOpenEnclaveResponse = AttestationResponse;
/** Optional parameters. */
export interface AttestationAttestSgxEnclaveOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the attestSgxEnclave operation. */
export type AttestationAttestSgxEnclaveResponse = AttestationResponse;
/** Optional parameters. */
export interface AttestationAttestTpmOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the attestTpm operation. */
export type AttestationAttestTpmResponse = TpmAttestationResponse;
/** Optional parameters. */
export interface SigningCertificatesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type SigningCertificatesGetResponse = JsonWebKeySet;
/** Optional parameters. */
export interface MetadataConfigurationGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type MetadataConfigurationGetResponse = Record<string, unknown>;
/** Optional parameters. */
export interface GeneratedClientOptionalParams
extends coreClient.ServiceClientOptions {
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import * as sinon from "sinon";
import * as Moq from "typemoq";
import { WidgetZoneId, ZonesManager, ZonesManagerProps } from "../../../appui-layout-react";
import { AdjacentZonesStrategy, BottomZones, LeftZones, RightZones, TopZones } from "../../../appui-layout-react/zones/manager/AdjacentZones";
describe("AdjacentZonesStrategy", () => {
class AdjacentZones extends AdjacentZonesStrategy {
public getInitial(_zoneId: WidgetZoneId, _isInFooterMode: boolean): WidgetZoneId | undefined {
throw new Error("Method not implemented.");
}
}
const manager = Moq.Mock.ofType<ZonesManager>();
const managerProps = Moq.Mock.ofType<ZonesManagerProps>();
const widgets = Moq.Mock.ofType<ZonesManagerProps["widgets"]>();
const zones = Moq.Mock.ofType<ZonesManagerProps["zones"]>();
beforeEach(() => {
managerProps.reset();
widgets.reset();
zones.reset();
manager.reset();
managerProps.setup((x) => x.zones).returns(() => zones.object);
managerProps.setup((x) => x.widgets).returns(() => widgets.object);
});
describe("getCurrent", () => {
it("should return no zones", () => {
const z1 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
zones.setup((x) => x[1]).returns(() => z1.object);
z1.setup((x) => x.widgets).returns(() => []);
const sut = new AdjacentZones(manager.object);
sinon.stub(sut, "getInitial").returns(undefined);
const adjacentZones = sut.getCurrent(1, managerProps.object);
adjacentZones.length.should.eq(0);
});
it("should return initial zone", () => {
const z2 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
zones.setup((x) => x[1]).returns(() => z2.object);
z2.setup((x) => x.widgets).returns(() => [2]);
manager.setup((x) => x.findZoneWithWidget(1, Moq.It.isAny())).returns(() => z2.object);
const sut = new AdjacentZones(manager.object);
sinon.stub(sut, "getInitial").returns(1);
const adjacentZones = sut.getCurrent(1, managerProps.object);
adjacentZones.length.should.eq(1, "length");
adjacentZones[0].should.eq(1);
});
it("should return zone to which the initial zone is merged", () => {
const z3 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
const z6 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
const z9 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
zones.setup((x) => x[3]).returns(() => z3.object);
zones.setup((x) => x[6]).returns(() => z6.object);
z3.setup((x) => x.id).returns(() => 3);
z3.setup((x) => x.widgets).returns(() => [3]);
z6.setup((x) => x.widgets).returns(() => []);
z9.setup((x) => x.id).returns(() => 9);
manager.setup((x) => x.findZoneWithWidget(6, Moq.It.isAny())).returns(() => z9.object);
const sut = new AdjacentZones(manager.object);
sinon.stub(sut, "getInitial").returns(6);
const adjacentZones = sut.getCurrent(3, managerProps.object);
adjacentZones.length.should.eq(1, "length");
adjacentZones[0].should.eq(9);
});
it("should return multiple zones", () => {
const z3 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
const z6 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
const z9 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
zones.setup((x) => x[3]).returns(() => z3.object);
zones.setup((x) => x[6]).returns(() => z6.object);
zones.setup((x) => x[9]).returns(() => z9.object);
z3.setup((x) => x.id).returns(() => 3);
z3.setup((x) => x.widgets).returns(() => [3, 6, 9]);
z6.setup((x) => x.id).returns(() => 6);
z6.setup((x) => x.widgets).returns(() => []);
z9.setup((x) => x.id).returns(() => 9);
manager.setup((x) => x.findZoneWithWidget(6, Moq.It.isAny())).returns(() => z9.object);
const sut = new AdjacentZones(manager.object);
const getInitial = sinon.stub(sut, "getInitial");
getInitial.withArgs(3, sinon.match.any).returns(2);
getInitial.withArgs(6, sinon.match.any).returns(undefined);
getInitial.withArgs(9, sinon.match.any).returns(8);
sinon.stub(sut, "getSingleMergedZone").returns(false);
const adjacentZones = sut.getCurrent(3, managerProps.object);
adjacentZones.length.should.eq(2, "length");
adjacentZones[0].should.eq(2);
adjacentZones[1].should.eq(8);
});
it("should return single zone if strategy expects single merged zone", () => {
const z3 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
const z6 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
const z9 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
zones.setup((x) => x[3]).returns(() => z3.object);
zones.setup((x) => x[6]).returns(() => z6.object);
zones.setup((x) => x[9]).returns(() => z9.object);
z3.setup((x) => x.id).returns(() => 3);
z3.setup((x) => x.widgets).returns(() => [3, 6]);
z6.setup((x) => x.id).returns(() => 6);
z6.setup((x) => x.widgets).returns(() => []);
z9.setup((x) => x.id).returns(() => 9);
manager.setup((x) => x.findZoneWithWidget(6, Moq.It.isAny())).returns(() => z9.object);
const sut = new AdjacentZones(manager.object);
sinon.stub(sut, "getInitial").withArgs(6, sinon.match.any).returns(9);
sinon.stub(sut, "reduceToFirstZone").returns(false);
const adjacentZones = sut.getCurrent(3, managerProps.object);
adjacentZones.length.should.eq(1, "length");
adjacentZones[0].should.eq(9);
});
it("should return initial of single first zone", () => {
const z3 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
const z6 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
const z9 = Moq.Mock.ofType<ZonesManagerProps["zones"][WidgetZoneId]>();
zones.setup((x) => x[3]).returns(() => z3.object);
zones.setup((x) => x[6]).returns(() => z6.object);
zones.setup((x) => x[9]).returns(() => z9.object);
z3.setup((x) => x.id).returns(() => 3);
z3.setup((x) => x.widgets).returns(() => [3, 6]);
z6.setup((x) => x.id).returns(() => 6);
z6.setup((x) => x.widgets).returns(() => []);
z9.setup((x) => x.id).returns(() => 9);
manager.setup((x) => x.findZoneWithWidget(6, Moq.It.isAny())).returns(() => z9.object);
const sut = new AdjacentZones(manager.object);
sinon.stub(sut, "getInitial").withArgs(6, sinon.match.any).returns(9);
const adjacentZones = sut.getCurrent(3, managerProps.object);
adjacentZones.length.should.eq(0, "length");
});
});
describe("getSingleMergedZone", () => {
it("should return true for zones that are merged vertically", () => {
const sut = new AdjacentZones(manager.object);
sut.getSingleMergedZone(true).should.true;
});
it("should return false for zones that are merged horizontally", () => {
const sut = new AdjacentZones(manager.object);
sut.getSingleMergedZone(false).should.false;
});
});
describe("reduceToFirstZone", () => {
it("should return true", () => {
const sut = new AdjacentZones(manager.object);
sut.reduceToFirstZone().should.true;
});
});
});
describe("LeftZones", () => {
const manager = Moq.Mock.ofType<ZonesManager>();
beforeEach(() => {
manager.reset();
});
describe("getInitial", () => {
it("for zone 1", () => {
(new LeftZones(manager.object).getInitial(1, false) === undefined).should.true;
});
it("for zone 2", () => {
(new LeftZones(manager.object).getInitial(2, false) === 1).should.true;
});
it("for zone 3", () => {
(new LeftZones(manager.object).getInitial(3, false) === 2).should.true;
});
it("for zone 4", () => {
(new LeftZones(manager.object).getInitial(4, false) === undefined).should.true;
});
it("for zone 6", () => {
(new LeftZones(manager.object).getInitial(6, false) === undefined).should.true;
});
it("for zone 7", () => {
(new LeftZones(manager.object).getInitial(7, false) === undefined).should.true;
});
it("for zone 8", () => {
(new LeftZones(manager.object).getInitial(8, false) === 7).should.true;
});
it("for zone 8 in footer mode", () => {
(new LeftZones(manager.object).getInitial(8, true) === undefined).should.true;
});
it("for zone 9", () => {
(new LeftZones(manager.object).getInitial(9, false) === 8).should.true;
});
it("for zone 9 in footer mode", () => {
(new LeftZones(manager.object).getInitial(9, true) === undefined).should.true;
});
});
describe("getSingleMergedZone", () => {
it("should return false for zones that are merged vertically", () => {
const sut = new LeftZones(manager.object);
sut.getSingleMergedZone(true).should.false;
});
it("should return true for zones that are merged horizontally", () => {
const sut = new LeftZones(manager.object);
sut.getSingleMergedZone(false).should.true;
});
});
});
describe("RightZones", () => {
const manager = Moq.Mock.ofType<ZonesManager>();
beforeEach(() => {
manager.reset();
});
describe("getInitial", () => {
it("for zone 1", () => {
(new RightZones(manager.object).getInitial(1, false) === 2).should.true;
});
it("for zone 2", () => {
(new RightZones(manager.object).getInitial(2, false) === 3).should.true;
});
it("for zone 3", () => {
(new RightZones(manager.object).getInitial(3, false) === undefined).should.true;
});
it("for zone 4", () => {
(new RightZones(manager.object).getInitial(4, false) === undefined).should.true;
});
it("for zone 6", () => {
(new RightZones(manager.object).getInitial(6, false) === undefined).should.true;
});
it("for zone 7", () => {
(new RightZones(manager.object).getInitial(7, false) === 8).should.true;
});
it("for zone 7 in footer mode", () => {
(new RightZones(manager.object).getInitial(7, true) === undefined).should.true;
});
it("for zone 8", () => {
(new RightZones(manager.object).getInitial(8, false) === 9).should.true;
});
it("for zone 8 in footer mode", () => {
(new RightZones(manager.object).getInitial(8, true) === undefined).should.true;
});
it("for zone 9", () => {
(new RightZones(manager.object).getInitial(9, false) === undefined).should.true;
});
});
describe("getSingleMergedZone", () => {
it("should return false for zones that are merged vertically", () => {
const sut = new RightZones(manager.object);
sut.getSingleMergedZone(true).should.false;
});
it("should return true for zones that are merged horizontally", () => {
const sut = new RightZones(manager.object);
sut.getSingleMergedZone(false).should.true;
});
});
describe("reduceToFirstZone", () => {
it("should return false", () => {
const sut = new RightZones(manager.object);
sut.reduceToFirstZone().should.false;
});
});
});
describe("TopZones", () => {
const manager = Moq.Mock.ofType<ZonesManager>();
beforeEach(() => {
manager.reset();
});
describe("getInitial", () => {
it("for zone 1", () => {
(new TopZones(manager.object).getInitial(1) === undefined).should.true;
});
it("for zone 2", () => {
(new TopZones(manager.object).getInitial(2) === undefined).should.true;
});
it("for zone 3", () => {
(new TopZones(manager.object).getInitial(3) === undefined).should.true;
});
it("for zone 4", () => {
(new TopZones(manager.object).getInitial(4) === 1).should.true;
});
it("for zone 6", () => {
(new TopZones(manager.object).getInitial(6) === 3).should.true;
});
it("for zone 7", () => {
(new TopZones(manager.object).getInitial(7) === 4).should.true;
});
it("for zone 8", () => {
(new TopZones(manager.object).getInitial(8) === undefined).should.true;
});
it("for zone 9", () => {
(new TopZones(manager.object).getInitial(9) === 6).should.true;
});
});
});
describe("BottomZones", () => {
const manager = Moq.Mock.ofType<ZonesManager>();
beforeEach(() => {
manager.reset();
});
describe("getInitial", () => {
it("for zone 1", () => {
(new BottomZones(manager.object).getInitial(1) === 4).should.true;
});
it("for zone 2", () => {
(new BottomZones(manager.object).getInitial(2) === undefined).should.true;
});
it("for zone 3", () => {
(new BottomZones(manager.object).getInitial(3) === 6).should.true;
});
it("for zone 4", () => {
(new BottomZones(manager.object).getInitial(4) === 7).should.true;
});
it("for zone 6", () => {
(new BottomZones(manager.object).getInitial(6) === 9).should.true;
});
it("for zone 7", () => {
(new BottomZones(manager.object).getInitial(7) === undefined).should.true;
});
it("for zone 8", () => {
(new BottomZones(manager.object).getInitial(8) === undefined).should.true;
});
it("for zone 9", () => {
(new BottomZones(manager.object).getInitial(9) === undefined).should.true;
});
});
describe("reduceToFirstZone", () => {
it("should return false", () => {
const sut = new BottomZones(manager.object);
sut.reduceToFirstZone().should.false;
});
});
}); | the_stack |
import { POST, BASE_API } from '../support/constants';
import { dayjsToString } from '../support/utils';
import { artemis } from '../support/ArtemisTesting';
import { MODELING_SPACE } from '../support/pageobjects/ModelingEditor';
// https://day.js.org/docs is a tool for date/time
import dayjs from 'dayjs';
// pageobjects
const courseManagement = artemis.pageobjects.courseManagement;
const createModelingExercise = artemis.pageobjects.modelingExercise.creation;
const modelingExerciseExampleSubmission = artemis.pageobjects.modelingExercise.assessmentEditor;
const modelingEditor = artemis.pageobjects.modelingExercise.editor;
// requests
const courseManagementRequests = artemis.requests.courseManagement;
// Users
const userManagement = artemis.users;
const admin = userManagement.getAdmin();
const student = userManagement.getStudentOne();
const tutor = userManagement.getTutor();
const instructor = userManagement.getInstructor();
let testCourse: any;
let modelingExercise: any;
const modelingExerciseTitle = 'Cypress Modeling Exercise';
describe('Modeling Exercise Spec', () => {
before('Log in as admin and create a course', () => {
cy.login(admin);
courseManagementRequests.createCourse().then((courseResp) => {
testCourse = courseResp.body;
cy.visit(`/course-management/${testCourse.id}`).get('.row-md > :nth-child(2)').should('contain.text', testCourse.title);
courseManagement.addTutorToCourse(tutor);
courseManagement.addStudentToCourse(student);
courseManagement.addInstructorToCourse(instructor);
});
});
after('Delete the test course', () => {
cy.login(admin);
courseManagementRequests.deleteCourse(testCourse.id);
});
describe('Create/Edit Modeling Exercise', () => {
beforeEach('Login as instructor', () => {
cy.login(instructor);
});
after('Delete Modeling Exercise', () => {
cy.login(admin);
courseManagementRequests.deleteModelingExercise(modelingExercise.id);
});
it('Create a new modeling exercise', () => {
cy.visit(`/course-management/${testCourse.id}/exercises`);
cy.get('#modeling-exercise-create-button').click();
createModelingExercise.setTitle(modelingExerciseTitle);
createModelingExercise.addCategories(['e2e-testing', 'test2']);
createModelingExercise.setPoints(10);
createModelingExercise
.save()
.its('response.body')
.then((body) => {
modelingExercise = body;
});
cy.contains(modelingExerciseTitle).should('exist');
});
it('Create Example Solution', () => {
cy.visit(`/course-management/${testCourse.id}/exercises`);
cy.contains(modelingExerciseTitle).click();
cy.get('.card-body').contains('Edit').click();
modelingEditor.addComponentToModel(1);
createModelingExercise.save();
cy.get('jhi-exercise-submission-export').should('be.visible');
cy.get(`${MODELING_SPACE} > :nth-child(1)`).should('exist');
});
it('Creates Example Submission', () => {
cy.visit(`/course-management/${testCourse.id}/modeling-exercises/${modelingExercise.id}/example-submissions`);
cy.get('[jhitranslate="artemisApp.modelingExercise.createExampleSubmission"]').click();
modelingEditor.addComponentToModel(1);
modelingEditor.addComponentToModel(2);
modelingEditor.addComponentToModel(3);
cy.get('[jhitranslate="artemisApp.modelingExercise.createNewExampleSubmission"]').click();
cy.get('.alerts').should('contain', 'Your diagram was saved successfully');
cy.get('[jhitranslate="artemisApp.modelingExercise.showExampleAssessment"]').click();
modelingExerciseExampleSubmission.openAssessmentForComponent(1);
modelingExerciseExampleSubmission.assessComponent(-1, 'False');
modelingExerciseExampleSubmission.openAssessmentForComponent(2);
modelingExerciseExampleSubmission.assessComponent(2, 'Good');
modelingExerciseExampleSubmission.openAssessmentForComponent(3);
modelingExerciseExampleSubmission.assessComponent(0, 'Unnecessary');
cy.contains('Save Example Assessment').click();
});
it('Edit Existing Modeling Exercise', () => {
cy.visit(`/course-management/${testCourse.id}/modeling-exercises/${modelingExercise.id}/edit`);
const newTitle = 'Cypress EDITED ME';
const points = 100;
createModelingExercise.setTitle(newTitle);
createModelingExercise.pickDifficulty({ hard: true });
createModelingExercise.setReleaseDate(dayjsToString(dayjs().add(1, 'day')));
createModelingExercise.setDueDate(dayjsToString(dayjs().add(2, 'day')));
createModelingExercise.setAssessmentDueDate(dayjsToString(dayjs().add(3, 'day')));
createModelingExercise.includeInOverallScore();
createModelingExercise.setPoints(points);
createModelingExercise.save();
cy.visit(`/course-management/${testCourse.id}/exercises`);
cy.get('tbody > tr > :nth-child(2)').should('contain.text', newTitle);
cy.get('tbody > tr > :nth-child(6)').should('contain.text', points.toString());
});
});
describe('Modeling Exercise Flow', () => {
before('Create Modeling Exercise with future release date', () => {
courseManagementRequests.createModelingExercise({ course: testCourse }, modelingExerciseTitle, dayjs().add(1, 'hour')).then((resp) => {
modelingExercise = resp.body;
});
});
it('Student can not see unreleased Modeling Exercise', () => {
cy.login(student, '/courses');
cy.get('.card-body').contains(testCourse.title).click({ force: true });
cy.contains('No exercises available for the course.').should('be.visible');
});
it('Release a Modeling Exercise', () => {
cy.login(instructor, `/course-management/${testCourse.id}/modeling-exercises/${modelingExercise.id}/edit`);
createModelingExercise.setReleaseDate(dayjsToString(dayjs().subtract(1, 'hour')));
createModelingExercise.save();
});
it('Student can start and submit their model', () => {
cy.intercept(BASE_API + 'courses/*/exercises/*/participations').as('createModelingParticipation');
cy.login(student, `/courses/${testCourse.id}`);
cy.get('.col-lg-8').contains(modelingExercise.title);
cy.get('.btn-sm').should('contain.text', 'Start exercise').click();
cy.wait('@createModelingParticipation');
cy.get('.course-exercise-row').find('.btn-primary').click();
modelingEditor.addComponentToModel(1);
modelingEditor.addComponentToModel(2);
modelingEditor.addComponentToModel(3);
cy.get('.submission-button').click();
cy.get('.alerts').should('contain.text', 'Your submission was successful! You can change your submission or wait for your feedback.');
cy.contains('No graded result').should('be.visible');
});
it('Close exercise for submissions', () => {
cy.login(instructor, `/course-management/${testCourse.id}/modeling-exercises/${modelingExercise.id}/edit`);
createModelingExercise.setDueDate(dayjsToString(dayjs().add(1, 'second')));
// so the submission is not considered 'late'
cy.wait(1000);
createModelingExercise.save();
cy.url().should('contain', '/modeling-exercises/');
});
it('Tutor can assess the submission', () => {
cy.login(tutor, '/course-management');
cy.get(`[href="/course-management/${testCourse.id}/assessment-dashboard"]`).click();
cy.url().should('contain', `/course-management/${testCourse.id}/assessment-dashboard`);
cy.get('#field_showFinishedExercise').should('be.visible').click();
cy.get('tbody > tr > :nth-child(6) >').click();
cy.get('.btn').click();
cy.wait(5000);
cy.get('.btn').click();
cy.get('#assessmentLockedCurrentUser').should('contain.text', 'You have the lock for this assessment');
cy.get('jhi-unreferenced-feedback > .btn').click();
cy.get('jhi-assessment-detail > .card > .card-body > :nth-child(1) > :nth-child(2)').clear().type('1');
cy.get('jhi-assessment-detail > .card > .card-body > :nth-child(2) > :nth-child(2)').clear().type('thanks, i hate it');
modelingExerciseExampleSubmission.openAssessmentForComponent(1);
modelingExerciseExampleSubmission.assessComponent(-1, 'False');
modelingExerciseExampleSubmission.openAssessmentForComponent(2);
modelingExerciseExampleSubmission.assessComponent(2, 'Good');
modelingExerciseExampleSubmission.openAssessmentForComponent(3);
modelingExerciseExampleSubmission.assessComponent(0, 'Unnecessary');
cy.get('[jhitranslate="entity.action.submit"]').click();
// TODO: The alert is currently broken
// cy.get('.alerts').should('contain.text', 'Your assessment was submitted successfully!');
});
it('Close assessment period', () => {
cy.login(instructor, `/course-management/${testCourse.id}/modeling-exercises/${modelingExercise.id}/edit`);
createModelingExercise.setAssessmentDueDate(dayjsToString(dayjs()));
createModelingExercise.save();
});
it('Student can view the assessment and complain', () => {
cy.login(student, `/courses/${testCourse.id}/exercises/${modelingExercise.id}`);
cy.get('jhi-submission-result-status > .col-auto').should('contain.text', 'Score').and('contain.text', '2 of 10 points');
cy.get('jhi-exercise-details-student-actions.col > > :nth-child(2)').click();
cy.url().should('contain', `/courses/${testCourse.id}/modeling-exercises/${modelingExercise.id}/participate/`);
cy.get('.col-xl-8').should('contain.text', 'thanks, i hate it');
cy.get('jhi-complaint-interactions > :nth-child(1) > .mt-4 > :nth-child(1)').click();
cy.get('#complainTextArea').type('Thanks i hate you :^)');
cy.intercept(POST, BASE_API + 'complaints').as('complaintCreated');
cy.get('.col-6 > .btn').click();
cy.wait('@complaintCreated');
});
it('Instructor can see complaint and reject it', () => {
cy.login(instructor, `/course-management/${testCourse.id}/assessment-dashboard`);
cy.get(`[href="/course-management/${testCourse.id}/complaints"]`).click();
cy.get('tr > .text-center >').click();
cy.get('#responseTextArea').type('lorem ipsum...');
cy.get('#rejectComplaintButton').click();
cy.get('.alerts').should('contain.text', 'Response to complaint has been submitted');
});
});
}); | the_stack |
import fs = require("fs");
import path = require("path");
import tl = require("azure-pipelines-task-lib/task");
export function extractVersion(injectversion, versionRegex, versionNumber ) {
var newVersion = versionNumber;
if (injectversion === false) {
console.log(`Extracting version number from build number`);
var regexp = new RegExp(versionRegex);
var versionData = regexp.exec(versionNumber);
if (!versionData) {
// extra check as we don't get zero size array but a null
tl.error(`Could not find version number data in ${versionNumber} that matches ${versionRegex}.`);
process.exit(1);
}
switch (versionData.length) {
case 0:
// this is trapped by the null check above
tl.error(`Could not find version number data in ${versionNumber} that matches ${versionRegex}.`);
process.exit(1);
case 1:
break;
default:
tl.warning(`Found more than instance of version data in ${versionNumber} that matches ${versionRegex}.`);
tl.warning(`Will assume first instance is version.`);
break;
}
newVersion = versionData[0];
} else {
console.log(`Using provided version number directly`);
}
return newVersion;
}
export function SplitSDKName(sdkstring) {
var array = [];
if (sdkstring !== undefined && sdkstring !== null && sdkstring.length > 0) {
array = sdkstring.trim().split(",").map(item => item.trim());
}
return array;
}
// List all files in a directory in Node.js recursively in a synchronous fashion
export function findFiles (dir, filename , filelist, sdknames: string[]) {
var path = path || require("path");
var fs = fs || require("fs"),
files = fs.readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
if (fs.statSync(path.join(dir, file)).isDirectory()) {
filelist = findFiles(path.join(dir, file), filename, filelist, sdknames);
}
else {
if (file.toLowerCase().endsWith(filename.toLowerCase())) {
var filecontent = fs.readFileSync(path.join(dir, file));
var matchingSDK = false;
if (file.toLowerCase().indexOf("directory.build.props") === -1 && sdknames.length > 0) {
// need to use a for loop to allow break, not the most elegent solution
for (let i = 0; i < sdknames.length; i++) {
if (filecontent.toString().toLowerCase().indexOf(`<project sdk=\"${sdknames[i].toLowerCase()}`) !== -1) {
console.log(`Matched the file '${file}' using the SDK name '${sdknames[i]}'`);
matchingSDK = true;
break;
}
}
if (matchingSDK) {
console.log(`Adding file ${file} as is a .NETCore Project`);
filelist.push(path.join(dir, file));
} else {
console.log(`Skipping file ${file} as is not a .NETCore Project`);
}
} else if (file.toLowerCase().indexOf("directory.build.props") !== -1) {
console.log(`Adding file ${file} as is a directory.build.props file`);
filelist.push(path.join(dir, file));
} else {
console.log(`${file} considered but not added either because has is not .NETCore project file or a directory.build.props file`);
}
}
}
});
return filelist;
}
export function stringToBoolean (value: string) {
switch (value.toLowerCase().trim()) {
case "true": case "yes": case "1": return true;
case "false": case "no": case "0": case null: return false;
default: return Boolean(value);
}
}
function UpdateSingleField(file, field, newVersion) {
var filecontent = fs.readFileSync(file);
let content: string = filecontent.toString();
fs.chmodSync(file, "600");
console.log (`Getting just the PropertyGroup that contains the single version fields`);
var propertyGroupMatches = content.match(/<PropertyGroup>([\s\S]*?)<\/PropertyGroup>/gmi);
if (propertyGroupMatches === null) {
console.log(`Cannot find any <PropertyGroup> blocks so adding one`);
var insertPropertyGroupText = `<PropertyGroup><${field}>${newVersion}<\/${field}></PropertyGroup></Project>`;
fs.writeFileSync(file, filecontent.toString().replace("</Project>", insertPropertyGroupText));
} else {
console.log(`Found <PropertyGroup> [${propertyGroupMatches.length}] blocks`);
var propertyGroupText = propertyGroupMatches[0];
// set a default of the first match incase we can't find a better one
propertyGroupText = "";
propertyGroupMatches.forEach(group => {
const csprojVersionRegex = `(<${field}>)(.*)(<\/${field}>)`;
var regexp = new RegExp(csprojVersionRegex, "gmi");
if (regexp.test(group)) {
propertyGroupText = group;
}
});
if (propertyGroupText === "") {
propertyGroupText = propertyGroupMatches[0];
}
var tmpField = `<${field}>`;
var newPropertyGroupText = "";
if (propertyGroupText.toString().toLowerCase().indexOf(tmpField.toLowerCase()) === -1) {
console.log (`The ${tmpField} version is not present in the file so adding it`);
// add the field, trying to avoid having to load library to parse xml
// Check for TargetFramework when only using a single framework
var regexp = new RegExp("</TargetFramework>", "gi");
tmpField = tmpField.replace("<", "").replace(">", "");
if (regexp.exec(propertyGroupText.toString())) {
console.log (`The ${file} file only targets 1 framework`);
var newVersionField = `</TargetFramework><${tmpField}>${newVersion}<\/${tmpField}>`;
newPropertyGroupText = propertyGroupText.replace(`</TargetFramework>`, newVersionField);
fs.writeFileSync(file, filecontent.toString().replace(propertyGroupText, newPropertyGroupText));
} else {
console.log (`Cannot find a <TargetFramework> block, so just adding the version field at the end of the first <PropertyGroup>`);
var forcedInsertPropertyGroupText = `<${field}>${newVersion}<\/${field}></PropertyGroup>`;
newPropertyGroupText = propertyGroupText.replace(`</PropertyGroup>`, forcedInsertPropertyGroupText);
fs.writeFileSync(file, filecontent.toString().replace(propertyGroupText, newPropertyGroupText));
}
} else {
console.log (`Updating only the ${field} version`);
const fieldRegex = `(<${field}>)(.*)(<\/${field}>)`;
var fieldRegexp = new RegExp(fieldRegex, "gi");
var matches = fieldRegexp.exec(propertyGroupText);
if (matches !== null) {
var existingTag1: string = matches[0];
console.log(`Existing Tag: ${existingTag1}`);
var replacementTag1: string = `${matches[1]}${newVersion}${matches[3]}`;
console.log(`Replacement Tag: ${replacementTag1}`);
newPropertyGroupText = propertyGroupText.replace(existingTag1, replacementTag1);
}
var updateFileContents = content.replace(propertyGroupText, newPropertyGroupText);
fs.writeFileSync(file, updateFileContents);
}
}
}
export function ProcessFile(file, field, newVersion, addDefault = false) {
var isVersionApplied: any = false;
// Check that the field to update is present
if (field && field.length > 0) {
UpdateSingleField(file, field, newVersion);
isVersionApplied = true;
} else {
console.log(`Checking if any version fields to update`);
var filecontent = fs.readFileSync(file);
let content: string = filecontent.toString();
fs.chmodSync(file, "600");
// set some defaults
var propertyGroupText = "<PropertyGroup></PropertyGroup>";
let versionFields = ["Version", "VersionPrefix", "AssemblyVersion"];
// We only need to consider the following fields in the main PropertyGroup block
console.log (`Getting just the PropertyGroup that contains the version fields`);
var matches = content.match(/<PropertyGroup>([\s\S]*?)<\/PropertyGroup>/gmi);
if (matches === null) {
console.log(`Cannot find any <PropertyGroup> blocks so adding one`);
} else {
console.log(`Found <PropertyGroup> [${matches.length}] block`);
console.log(`Scanning for existing version fields`);
// set a default of the first match incase we can't find a better one
propertyGroupText = "";
matches.forEach(group => {
versionFields.forEach(element => {
const csprojVersionRegex = `(<${element}>)(.*)(<\/${element}>)`;
var regexp = new RegExp(csprojVersionRegex, "gmi");
if (regexp.test(group)) {
propertyGroupText = group;
}
});
});
if (propertyGroupText === "") {
propertyGroupText = matches[0];
}
}
var hasUpdateFields: any = false;
var newPropertyGroupText = propertyGroupText;
versionFields.forEach(element => {
console.log(`Processing Field ${element}`);
const csprojVersionRegex = `(<${element}>)(.*)(<\/${element}>)`;
var regexp = new RegExp(csprojVersionRegex, "gmi");
let matches;
while ((matches = regexp.exec(newPropertyGroupText)) !== null) {
var existingTag1: string = matches[0];
console.log(`Existing Tag: ${existingTag1}`);
var replacementTag1: string = `${matches[1]}${newVersion}${matches[3]}`;
console.log(`Replacement Tag: ${replacementTag1}`);
newPropertyGroupText = newPropertyGroupText.replace(existingTag1, replacementTag1);
hasUpdateFields = true;
}
});
if (hasUpdateFields === true) {
var updateFileContents = content.replace(propertyGroupText, newPropertyGroupText);
fs.writeFileSync(file, updateFileContents);
isVersionApplied = true;
} else {
if (addDefault === true) {
console.log(`No version fields present, so add a Version field`);
UpdateSingleField(file, "Version", newVersion);
isVersionApplied = true;
} else {
console.log(`No version fields present, version field ignored because 'addDefault' is false`);
}
}
}
if (isVersionApplied) {
console.log (`${file} - version applied`);
} else {
console.log (`${file} - version not applied`);
}
} | the_stack |
import { inflateString, base64Decode, isNonEmptyArray } from './utility';
import { verifyTime } from './validator';
import libsaml from './libsaml';
import {
extract,
loginRequestFields,
loginResponseFields,
logoutRequestFields,
logoutResponseFields,
ExtractorFields,
logoutResponseStatusFields,
loginResponseStatusFields
} from './extractor';
import {
BindingNamespace,
ParserType,
wording,
MessageSignatureOrder,
StatusCode
} from './urn';
import simpleSignBinding from './binding-simplesign';
const bindDict = wording.binding;
const urlParams = wording.urlParams;
export interface FlowResult {
samlContent: string;
extract: any;
sigAlg?: string|null ;
}
// get the default extractor fields based on the parserType
function getDefaultExtractorFields(parserType: ParserType, assertion?: any): ExtractorFields {
switch (parserType) {
case ParserType.SAMLRequest:
return loginRequestFields;
case ParserType.SAMLResponse:
if (!assertion) {
// unexpected hit
throw new Error('ERR_EMPTY_ASSERTION');
}
return loginResponseFields(assertion);
case ParserType.LogoutRequest:
return logoutRequestFields;
case ParserType.LogoutResponse:
return logoutResponseFields;
default:
throw new Error('ERR_UNDEFINED_PARSERTYPE');
}
}
// proceed the redirect binding flow
async function redirectFlow(options): Promise<FlowResult> {
const { request, parserType, self, checkSignature = true, from } = options;
const { query, octetString } = request;
const { SigAlg: sigAlg, Signature: signature } = query;
const targetEntityMetadata = from.entityMeta;
// ?SAMLRequest= or ?SAMLResponse=
const direction = libsaml.getQueryParamByType(parserType);
const content = query[direction];
// query must contain the saml content
if (content === undefined) {
return Promise.reject('ERR_REDIRECT_FLOW_BAD_ARGS');
}
const xmlString = inflateString(decodeURIComponent(content));
// validate the xml
try {
await libsaml.isValidXml(xmlString);
} catch (e) {
return Promise.reject('ERR_INVALID_XML');
}
// check status based on different scenarios
await checkStatus(xmlString, parserType);
let assertion: string = '';
if (parserType === urlParams.samlResponse){
// Extract assertion shortcut
const verifiedDoc = extract(xmlString, [{
key: 'assertion',
localPath: ['~Response', 'Assertion'],
attributes: [],
context: true
}]);
if (verifiedDoc && verifiedDoc.assertion){
assertion = verifiedDoc.assertion as string;
}
}
const extractorFields = getDefaultExtractorFields(parserType, assertion.length > 0 ? assertion : null);
const parseResult: { samlContent: string, extract: any, sigAlg: (string | null) } = {
samlContent: xmlString,
sigAlg: null,
extract: extract(xmlString, extractorFields),
};
// see if signature check is required
// only verify message signature is enough
if (checkSignature) {
if (!signature || !sigAlg) {
return Promise.reject('ERR_MISSING_SIG_ALG');
}
// put the below two assignemnts into verifyMessageSignature function
const base64Signature = Buffer.from(decodeURIComponent(signature), 'base64');
const decodeSigAlg = decodeURIComponent(sigAlg);
const verified = libsaml.verifyMessageSignature(targetEntityMetadata, octetString, base64Signature, sigAlg);
if (!verified) {
// Fail to verify message signature
return Promise.reject('ERR_FAILED_MESSAGE_SIGNATURE_VERIFICATION');
}
parseResult.sigAlg = decodeSigAlg;
}
/**
* Validation part: validate the context of response after signature is verified and decrpyted (optional)
*/
const issuer = targetEntityMetadata.getEntityID();
const extractedProperties = parseResult.extract;
// unmatched issuer
if (
(parserType === 'LogoutResponse' || parserType === 'SAMLResponse')
&& extractedProperties
&& extractedProperties.issuer !== issuer
) {
return Promise.reject('ERR_UNMATCH_ISSUER');
}
// invalid session time
// only run the verifyTime when `SessionNotOnOrAfter` exists
if (
parserType === 'SAMLResponse'
&& extractedProperties.sessionIndex.sessionNotOnOrAfter
&& !verifyTime(
undefined,
extractedProperties.sessionIndex.sessionNotOnOrAfter,
self.entitySetting.clockDrifts
)
) {
return Promise.reject('ERR_EXPIRED_SESSION');
}
// invalid time
// 2.4.1.2 https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
if (
parserType === 'SAMLResponse'
&& extractedProperties.conditions
&& !verifyTime(
extractedProperties.conditions.notBefore,
extractedProperties.conditions.notOnOrAfter,
self.entitySetting.clockDrifts
)
) {
return Promise.reject('ERR_SUBJECT_UNCONFIRMED');
}
return Promise.resolve(parseResult);
}
// proceed the post flow
async function postFlow(options): Promise<FlowResult> {
const {
request,
from,
self,
parserType,
checkSignature = true
} = options;
const { body } = request;
const direction = libsaml.getQueryParamByType(parserType);
const encodedRequest = body[direction];
let samlContent = String(base64Decode(encodedRequest));
const verificationOptions = {
metadata: from.entityMeta,
signatureAlgorithm: from.entitySetting.requestSignatureAlgorithm,
};
const decryptRequired = from.entitySetting.isAssertionEncrypted;
let extractorFields: ExtractorFields = [];
// validate the xml first
await libsaml.isValidXml(samlContent);
if (parserType !== urlParams.samlResponse) {
extractorFields = getDefaultExtractorFields(parserType, null);
}
// check status based on different scenarios
await checkStatus(samlContent, parserType);
// verify the signatures (the repsonse is encrypted then signed, then verify first then decrypt)
if (
checkSignature &&
from.entitySetting.messageSigningOrder === MessageSignatureOrder.ETS
) {
const [verified, verifiedAssertionNode] = libsaml.verifySignature(samlContent, verificationOptions);
if (!verified) {
return Promise.reject('ERR_FAIL_TO_VERIFY_ETS_SIGNATURE');
}
if (!decryptRequired) {
extractorFields = getDefaultExtractorFields(parserType, verifiedAssertionNode);
}
}
if (parserType === 'SAMLResponse' && decryptRequired) {
const result = await libsaml.decryptAssertion(self, samlContent);
samlContent = result[0];
extractorFields = getDefaultExtractorFields(parserType, result[1]);
}
// verify the signatures (the repsonse is signed then encrypted, then decrypt first then verify)
if (
checkSignature &&
from.entitySetting.messageSigningOrder === MessageSignatureOrder.STE
) {
const [verified, verifiedAssertionNode] = libsaml.verifySignature(samlContent, verificationOptions);
if (verified) {
extractorFields = getDefaultExtractorFields(parserType, verifiedAssertionNode);
} else {
return Promise.reject('ERR_FAIL_TO_VERIFY_STE_SIGNATURE');
}
}
const parseResult = {
samlContent: samlContent,
extract: extract(samlContent, extractorFields),
};
/**
* Validation part: validate the context of response after signature is verified and decrpyted (optional)
*/
const targetEntityMetadata = from.entityMeta;
const issuer = targetEntityMetadata.getEntityID();
const extractedProperties = parseResult.extract;
// unmatched issuer
if (
(parserType === 'LogoutResponse' || parserType === 'SAMLResponse')
&& extractedProperties
&& extractedProperties.issuer !== issuer
) {
return Promise.reject('ERR_UNMATCH_ISSUER');
}
// invalid session time
// only run the verifyTime when `SessionNotOnOrAfter` exists
if (
parserType === 'SAMLResponse'
&& extractedProperties.sessionIndex.sessionNotOnOrAfter
&& !verifyTime(
undefined,
extractedProperties.sessionIndex.sessionNotOnOrAfter,
self.entitySetting.clockDrifts
)
) {
return Promise.reject('ERR_EXPIRED_SESSION');
}
// invalid time
// 2.4.1.2 https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
if (
parserType === 'SAMLResponse'
&& extractedProperties.conditions
&& !verifyTime(
extractedProperties.conditions.notBefore,
extractedProperties.conditions.notOnOrAfter,
self.entitySetting.clockDrifts
)
) {
return Promise.reject('ERR_SUBJECT_UNCONFIRMED');
}
return Promise.resolve(parseResult);
}
// proceed the post simple sign binding flow
async function postSimpleSignFlow(options): Promise<FlowResult> {
const { request, parserType, self, checkSignature = true, from } = options;
const { body, octetString } = request;
const targetEntityMetadata = from.entityMeta;
// ?SAMLRequest= or ?SAMLResponse=
const direction = libsaml.getQueryParamByType(parserType);
const encodedRequest: string = body[direction];
const sigAlg: string = body['SigAlg'];
const signature: string = body['Signature'];
// query must contain the saml content
if (encodedRequest === undefined) {
return Promise.reject('ERR_SIMPLESIGN_FLOW_BAD_ARGS');
}
const xmlString = String(base64Decode(encodedRequest));
// validate the xml
try {
await libsaml.isValidXml(xmlString);
} catch (e) {
return Promise.reject('ERR_INVALID_XML');
}
// check status based on different scenarios
await checkStatus(xmlString, parserType);
let assertion: string = '';
if (parserType === urlParams.samlResponse){
// Extract assertion shortcut
const verifiedDoc = extract(xmlString, [{
key: 'assertion',
localPath: ['~Response', 'Assertion'],
attributes: [],
context: true
}]);
if (verifiedDoc && verifiedDoc.assertion){
assertion = verifiedDoc.assertion as string;
}
}
const extractorFields = getDefaultExtractorFields(parserType, assertion.length > 0 ? assertion : null);
const parseResult: { samlContent: string, extract: any, sigAlg: (string | null) } = {
samlContent: xmlString,
sigAlg: null,
extract: extract(xmlString, extractorFields),
};
// see if signature check is required
// only verify message signature is enough
if (checkSignature) {
if (!signature || !sigAlg) {
return Promise.reject('ERR_MISSING_SIG_ALG');
}
// put the below two assignemnts into verifyMessageSignature function
const base64Signature = Buffer.from(signature, 'base64');
const verified = libsaml.verifyMessageSignature(targetEntityMetadata, octetString, base64Signature, sigAlg);
if (!verified) {
// Fail to verify message signature
return Promise.reject('ERR_FAILED_MESSAGE_SIGNATURE_VERIFICATION');
}
parseResult.sigAlg = sigAlg;
}
/**
* Validation part: validate the context of response after signature is verified and decrpyted (optional)
*/
const issuer = targetEntityMetadata.getEntityID();
const extractedProperties = parseResult.extract;
// unmatched issuer
if (
(parserType === 'LogoutResponse' || parserType === 'SAMLResponse')
&& extractedProperties
&& extractedProperties.issuer !== issuer
) {
return Promise.reject('ERR_UNMATCH_ISSUER');
}
// invalid session time
// only run the verifyTime when `SessionNotOnOrAfter` exists
if (
parserType === 'SAMLResponse'
&& extractedProperties.sessionIndex.sessionNotOnOrAfter
&& !verifyTime(
undefined,
extractedProperties.sessionIndex.sessionNotOnOrAfter,
self.entitySetting.clockDrifts
)
) {
return Promise.reject('ERR_EXPIRED_SESSION');
}
// invalid time
// 2.4.1.2 https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
if (
parserType === 'SAMLResponse'
&& extractedProperties.conditions
&& !verifyTime(
extractedProperties.conditions.notBefore,
extractedProperties.conditions.notOnOrAfter,
self.entitySetting.clockDrifts
)
) {
return Promise.reject('ERR_SUBJECT_UNCONFIRMED');
}
return Promise.resolve(parseResult);
}
function checkStatus(content: string, parserType: string): Promise<string> {
// only check response parser
if (parserType !== urlParams.samlResponse && parserType !== urlParams.logoutResponse) {
return Promise.resolve('SKIPPED');
}
const fields = parserType === urlParams.samlResponse
? loginResponseStatusFields
: logoutResponseStatusFields;
const {top, second} = extract(content, fields);
// only resolve when top-tier status code is success
if (top === StatusCode.Success) {
return Promise.resolve('OK');
}
if (!top) {
throw new Error('ERR_UNDEFINED_STATUS');
}
// returns a detailed error for two-tier error code
throw new Error(`ERR_FAILED_STATUS with top tier code: ${top}, second tier code: ${second}`);
}
export function flow(options): Promise<FlowResult> {
const binding = options.binding;
const parserType = options.parserType;
options.supportBindings = [BindingNamespace.Redirect, BindingNamespace.Post, BindingNamespace.SimpleSign];
// saml response allows POST, REDIRECT
if (parserType === ParserType.SAMLResponse) {
options.supportBindings = [BindingNamespace.Post, BindingNamespace.Redirect, BindingNamespace.SimpleSign];
}
if (binding === bindDict.post) {
return postFlow(options);
}
if (binding === bindDict.redirect) {
return redirectFlow(options);
}
if (binding === bindDict.simpleSign) {
return postSimpleSignFlow(options);
}
return Promise.reject('ERR_UNEXPECTED_FLOW');
} | the_stack |
import Logger from '../../Logger';
import ItemChange from '../../models/ItemChange';
import Setting from '../../models/Setting';
import Note from '../../models/Note';
import BaseModel from '../../BaseModel';
import ItemChangeUtils from '../ItemChangeUtils';
import shim from '../../shim';
import filterParser from './filterParser';
import queryBuilder from './queryBuilder';
import { ItemChangeEntity, NoteEntity } from '../database/types';
const { sprintf } = require('sprintf-js');
const { pregQuote, scriptType, removeDiacritics } = require('../../string-utils.js');
export default class SearchEngine {
public static instance_: SearchEngine = null;
public static relevantFields = 'id, title, body, user_created_time, user_updated_time, is_todo, todo_completed, todo_due, parent_id, latitude, longitude, altitude, source_url';
public static SEARCH_TYPE_AUTO = 'auto';
public static SEARCH_TYPE_BASIC = 'basic';
public static SEARCH_TYPE_NONLATIN_SCRIPT = 'nonlatin';
public static SEARCH_TYPE_FTS = 'fts';
public dispatch: Function = (_o: any) => {};
private logger_ = new Logger();
private db_: any = null;
private isIndexing_ = false;
private syncCalls_: any[] = [];
private scheduleSyncTablesIID_: any;
static instance() {
if (SearchEngine.instance_) return SearchEngine.instance_;
SearchEngine.instance_ = new SearchEngine();
return SearchEngine.instance_;
}
setLogger(logger: Logger) {
this.logger_ = logger;
}
logger() {
return this.logger_;
}
setDb(db: any) {
this.db_ = db;
}
db() {
return this.db_;
}
noteById_(notes: NoteEntity[], noteId: string) {
for (let i = 0; i < notes.length; i++) {
if (notes[i].id === noteId) return notes[i];
}
// The note may have been deleted since the change was recorded. For example in this case:
// - Note created (Some Change object is recorded)
// - Note is deleted
// - ResourceService indexer runs.
// In that case, there will be a change for the note, but the note will be gone.
return null;
}
async rebuildIndex_() {
let noteIds: string[] = await this.db().selectAll('SELECT id FROM notes WHERE is_conflict = 0 AND encryption_applied = 0');
noteIds = noteIds.map((n: any) => n.id);
const lastChangeId = await ItemChange.lastChangeId();
// First delete content of note_normalized, in case the previous initial indexing failed
await this.db().exec('DELETE FROM notes_normalized');
while (noteIds.length) {
const currentIds = noteIds.splice(0, 100);
const notes = await Note.modelSelectAll(`
SELECT ${SearchEngine.relevantFields}
FROM notes
WHERE id IN ("${currentIds.join('","')}") AND is_conflict = 0 AND encryption_applied = 0`);
const queries = [];
for (let i = 0; i < notes.length; i++) {
const note = notes[i];
const n = this.normalizeNote_(note);
queries.push({ sql: `
INSERT INTO notes_normalized(${SearchEngine.relevantFields})
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
params: [n.id, n.title, n.body, n.user_created_time, n.user_updated_time, n.is_todo, n.todo_completed, n.todo_due, n.parent_id, n.latitude, n.longitude, n.altitude, n.source_url] }
);
}
await this.db().transactionExecBatch(queries);
}
Setting.setValue('searchEngine.lastProcessedChangeId', lastChangeId);
}
scheduleSyncTables() {
if (this.scheduleSyncTablesIID_) return;
this.scheduleSyncTablesIID_ = shim.setTimeout(async () => {
try {
await this.syncTables();
} catch (error) {
this.logger().error('SearchEngine::scheduleSyncTables: Error while syncing tables:', error);
}
this.scheduleSyncTablesIID_ = null;
}, 10000);
}
async rebuildIndex() {
Setting.setValue('searchEngine.lastProcessedChangeId', 0);
Setting.setValue('searchEngine.initialIndexingDone', false);
return this.syncTables();
}
async syncTables_() {
if (this.isIndexing_) return;
this.isIndexing_ = true;
this.logger().info('SearchEngine: Updating FTS table...');
await ItemChange.waitForAllSaved();
if (!Setting.value('searchEngine.initialIndexingDone')) {
await this.rebuildIndex_();
Setting.setValue('searchEngine.initialIndexingDone', true);
this.isIndexing_ = false;
return;
}
const startTime = Date.now();
const report = {
inserted: 0,
deleted: 0,
};
let lastChangeId = Setting.value('searchEngine.lastProcessedChangeId');
try {
while (true) {
const changes: ItemChangeEntity[] = await ItemChange.modelSelectAll(
`
SELECT id, item_id, type
FROM item_changes
WHERE item_type = ?
AND id > ?
ORDER BY id ASC
LIMIT 10
`,
[BaseModel.TYPE_NOTE, lastChangeId]
);
if (!changes.length) break;
const queries = [];
const noteIds = changes.map(a => a.item_id);
const notes = await Note.modelSelectAll(`
SELECT ${SearchEngine.relevantFields}
FROM notes WHERE id IN ("${noteIds.join('","')}") AND is_conflict = 0 AND encryption_applied = 0`
);
for (let i = 0; i < changes.length; i++) {
const change = changes[i];
if (change.type === ItemChange.TYPE_CREATE || change.type === ItemChange.TYPE_UPDATE) {
queries.push({ sql: 'DELETE FROM notes_normalized WHERE id = ?', params: [change.item_id] });
const note = this.noteById_(notes, change.item_id);
if (note) {
const n = this.normalizeNote_(note);
queries.push({ sql: `
INSERT INTO notes_normalized(${SearchEngine.relevantFields})
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
params: [change.item_id, n.title, n.body, n.user_created_time, n.user_updated_time, n.is_todo, n.todo_completed, n.todo_due, n.parent_id, n.latitude, n.longitude, n.altitude, n.source_url] });
report.inserted++;
}
} else if (change.type === ItemChange.TYPE_DELETE) {
queries.push({ sql: 'DELETE FROM notes_normalized WHERE id = ?', params: [change.item_id] });
report.deleted++;
} else {
throw new Error(`Invalid change type: ${change.type}`);
}
lastChangeId = change.id;
}
await this.db().transactionExecBatch(queries);
Setting.setValue('searchEngine.lastProcessedChangeId', lastChangeId);
await Setting.saveAll();
}
} catch (error) {
this.logger().error('SearchEngine: Error while processing changes:', error);
}
await ItemChangeUtils.deleteProcessedChanges();
this.logger().info(sprintf('SearchEngine: Updated FTS table in %dms. Inserted: %d. Deleted: %d', Date.now() - startTime, report.inserted, report.deleted));
this.isIndexing_ = false;
}
async syncTables() {
this.syncCalls_.push(true);
try {
await this.syncTables_();
} finally {
this.syncCalls_.pop();
}
}
async countRows() {
const sql = 'SELECT count(*) as total FROM notes_fts';
const row = await this.db().selectOne(sql);
return row && row['total'] ? row['total'] : 0;
}
fieldNamesFromOffsets_(offsets: any[]) {
const notesNormalizedFieldNames = this.db().tableFieldNames('notes_normalized');
const occurenceCount = Math.floor(offsets.length / 4);
const output: string[] = [];
for (let i = 0; i < occurenceCount; i++) {
const colIndex = offsets[i * 4];
const fieldName = notesNormalizedFieldNames[colIndex];
if (!output.includes(fieldName)) output.push(fieldName);
}
return output;
}
calculateWeight_(offsets: any[], termCount: number) {
// Offset doc: https://www.sqlite.org/fts3.html#offsets
// - If there's only one term in the query string, the content with the most matches goes on top
// - If there are multiple terms, the result with the most occurences that are closest to each others go on top.
// eg. if query is "abcd efgh", "abcd efgh" will go before "abcd XX efgh".
const occurenceCount = Math.floor(offsets.length / 4);
if (termCount === 1) return occurenceCount;
let spread = 0;
let previousDist = null;
for (let i = 0; i < occurenceCount; i++) {
const dist = offsets[i * 4 + 2];
if (previousDist !== null) {
const delta = dist - previousDist;
spread += delta;
}
previousDist = dist;
}
// Divide the number of occurences by the spread so even if a note has many times the searched terms
// but these terms are very spread appart, they'll be given a lower weight than a note that has the
// terms once or twice but just next to each others.
return occurenceCount / spread;
}
calculateWeightBM25_(rows: any[]) {
// https://www.sqlite.org/fts3.html#matchinfo
// pcnalx are the arguments passed to matchinfo
// p - The number of matchable phrases in the query.
// c - The number of user defined columns in the FTS table
// n - The number of rows in the FTS4 table.
// a - avg number of tokens in the text values stored in the column.
// l - For each column, the length of the value stored in the current
// row of the FTS4 table, in tokens.
// x - For each distinct combination of a phrase and table column, the
// following three values:
// hits_this_row
// hits_all_rows
// docs_with_hits
if (rows.length === 0) return;
const matchInfo = rows.map(row => new Uint32Array(row.matchinfo.buffer));
const generalInfo = matchInfo[0];
const K1 = 1.2;
const B = 0.75;
const TITLE_COLUMN = 1;
const BODY_COLUMN = 2;
const columns = [TITLE_COLUMN, BODY_COLUMN];
// const NUM_COLS = 12;
const numPhrases = generalInfo[0]; // p
const numColumns = generalInfo[1]; // c
const numRows = generalInfo[2]; // n
const avgTitleTokens = generalInfo[4]; // a
const avgBodyTokens = generalInfo[5];
const avgTokens = [null, avgTitleTokens, avgBodyTokens]; // we only need cols 1 and 2
const numTitleTokens = matchInfo.map(m => m[4 + numColumns]); // l
const numBodyTokens = matchInfo.map(m => m[5 + numColumns]);
const numTokens = [null, numTitleTokens, numBodyTokens];
const X = matchInfo.map(m => m.slice(27)); // x
const hitsThisRow = (array: any, c: number, p: number) => array[3 * (c + p * numColumns) + 0];
// const hitsAllRows = (array, c, p) => array[3 * (c + p*NUM_COLS) + 1];
const docsWithHits = (array: any, c: number, p: number) => array[3 * (c + p * numColumns) + 2];
// if a term occurs in over half the documents in the collection
// then this model gives a negative term weight, which is presumably undesirable.
// But, assuming the use of a stop list, this normally doesn't happen,
// and the value for each summand can be given a floor of 0.
const IDF = (n: number, N: number) => Math.max(Math.log((N - n + 0.5) / (n + 0.5)), 0);
// https://en.wikipedia.org/wiki/Okapi_BM25
const BM25 = (idf: any, freq: any, numTokens: number, avgTokens: any) => {
if (avgTokens === 0) {
return 0; // To prevent division by zero
}
return idf * (freq * (K1 + 1)) / (freq + K1 * (1 - B + B * (numTokens / avgTokens)));
};
const msSinceEpoch = Math.round(new Date().getTime());
const msPerDay = 86400000;
const weightForDaysSinceLastUpdate = (row: any) => {
// BM25 weights typically range 0-10, and last updated date should weight similarly, though prioritizing recency logarithmically.
// An alpha of 200 ensures matches in the last week will show up front (11.59) and often so for matches within 2 weeks (5.99),
// but is much less of a factor at 30 days (2.84) or very little after 90 days (0.95), focusing mostly on content at that point.
if (!row.user_updated_time) {
return 0;
}
const alpha = 200;
const daysSinceLastUpdate = (msSinceEpoch - row.user_updated_time) / msPerDay;
return alpha * Math.log(1 + 1 / Math.max(daysSinceLastUpdate, 0.5));
};
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
row.weight = 0;
for (let j = 0; j < numPhrases; j++) {
columns.forEach(column => {
const rowsWithHits = docsWithHits(X[i], column, j);
const frequencyHits = hitsThisRow(X[i], column, j);
const idf = IDF(rowsWithHits, numRows);
row.weight += BM25(idf, frequencyHits, numTokens[column][i], avgTokens[column]);
});
}
row.weight += weightForDaysSinceLastUpdate(row);
}
}
processBasicSearchResults_(rows: any[], parsedQuery: any) {
const valueRegexs = parsedQuery.keys.includes('_') ? parsedQuery.terms['_'].map((term: any) => term.valueRegex || term.value) : [];
const isTitleSearch = parsedQuery.keys.includes('title');
const isOnlyTitle = parsedQuery.keys.length === 1 && isTitleSearch;
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const testTitle = (regex: any) => new RegExp(regex, 'ig').test(row.title);
const matchedFields: any = {
title: isTitleSearch || valueRegexs.some(testTitle),
body: !isOnlyTitle,
};
row.fields = Object.keys(matchedFields).filter((key: any) => matchedFields[key]);
row.weight = 0;
row.fuzziness = 0;
}
}
processResults_(rows: any[], parsedQuery: any, isBasicSearchResults = false) {
if (isBasicSearchResults) {
this.processBasicSearchResults_(rows, parsedQuery);
} else {
this.calculateWeightBM25_(rows);
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const offsets = row.offsets.split(' ').map((o: any) => Number(o));
row.fields = this.fieldNamesFromOffsets_(offsets);
}
}
rows.sort((a, b) => {
if (a.fields.includes('title') && !b.fields.includes('title')) return -1;
if (!a.fields.includes('title') && b.fields.includes('title')) return +1;
if (a.weight < b.weight) return +1;
if (a.weight > b.weight) return -1;
if (a.is_todo && a.todo_completed) return +1;
if (b.is_todo && b.todo_completed) return -1;
if (a.user_updated_time < b.user_updated_time) return +1;
if (a.user_updated_time > b.user_updated_time) return -1;
return 0;
});
}
// https://stackoverflow.com/a/13818704/561309
queryTermToRegex(term: any) {
while (term.length && term.indexOf('*') === 0) {
term = term.substr(1);
}
let regexString = pregQuote(term);
if (regexString[regexString.length - 1] === '*') {
regexString = `${regexString.substr(0, regexString.length - 2)}[^${pregQuote(' \t\n\r,.,+-*?!={}<>|:"\'()[]')}]` + '*?';
// regexString = regexString.substr(0, regexString.length - 2) + '.*?';
}
return regexString;
}
async parseQuery(query: string) {
const trimQuotes = (str: string) => str.startsWith('"') ? str.substr(1, str.length - 2) : str;
let allTerms: any[] = [];
try {
allTerms = filterParser(query);
} catch (error) {
console.warn(error);
}
const textTerms = allTerms.filter(x => x.name === 'text' && !x.negated).map(x => trimQuotes(x.value));
const titleTerms = allTerms.filter(x => x.name === 'title' && !x.negated).map(x => trimQuotes(x.value));
const bodyTerms = allTerms.filter(x => x.name === 'body' && !x.negated).map(x => trimQuotes(x.value));
const terms: any = { _: textTerms, 'title': titleTerms, 'body': bodyTerms };
// Filter terms:
// - Convert wildcards to regex
// - Remove columns with no results
// - Add count of terms
let termCount = 0;
const keys = [];
for (const col in terms) {
if (!terms.hasOwnProperty(col)) continue;
if (!terms[col].length) {
delete terms[col];
continue;
}
for (let i = terms[col].length - 1; i >= 0; i--) {
const term = terms[col][i];
// SQlLite FTS doesn't allow "*" queries and neither shall we
if (term === '*') {
terms[col].splice(i, 1);
continue;
}
if (term.indexOf('*') >= 0) {
terms[col][i] = { type: 'regex', value: term, scriptType: scriptType(term), valueRegex: this.queryTermToRegex(term) };
} else {
terms[col][i] = { type: 'text', value: term, scriptType: scriptType(term) };
}
}
termCount += terms[col].length;
keys.push(col);
}
//
// The object "allTerms" is used for query construction purposes (this contains all the filter terms)
// Since this is used for the FTS match query, we need to normalize text, title and body terms.
// Note, we're not normalizing terms like tag because these are matched using SQL LIKE operator and so we must preserve their diacritics.
//
// The object "terms" only include text, title, body terms and is used for highlighting.
// By not normalizing the text, title, body in "terms", highlighting still works correctly for words with diacritics.
//
allTerms = allTerms.map(x => {
if (x.name === 'text' || x.name === 'title' || x.name === 'body') {
return Object.assign(x, { value: this.normalizeText_(x.value) });
}
return x;
});
return {
termCount: termCount,
keys: keys,
terms: terms, // text terms
allTerms: allTerms,
any: !!allTerms.find(term => term.name === 'any'),
};
}
allParsedQueryTerms(parsedQuery: any) {
if (!parsedQuery || !parsedQuery.termCount) return [];
let output: any[] = [];
for (const col in parsedQuery.terms) {
if (!parsedQuery.terms.hasOwnProperty(col)) continue;
output = output.concat(parsedQuery.terms[col]);
}
return output;
}
normalizeText_(text: string) {
const normalizedText = text.normalize ? text.normalize() : text;
return removeDiacritics(normalizedText.toLowerCase());
}
normalizeNote_(note: NoteEntity) {
const n = Object.assign({}, note);
n.title = this.normalizeText_(n.title);
n.body = this.normalizeText_(n.body);
return n;
}
async basicSearch(query: string) {
query = query.replace(/\*/, '');
const parsedQuery = await this.parseQuery(query);
const searchOptions: any = {};
for (const key of parsedQuery.keys) {
if (parsedQuery.terms[key].length === 0) continue;
const term = parsedQuery.terms[key].map((x: any) => x.value).join(' ');
if (key === '_') searchOptions.anywherePattern = `*${term}*`;
if (key === 'title') searchOptions.titlePattern = `*${term}*`;
if (key === 'body') searchOptions.bodyPattern = `*${term}*`;
}
return Note.previews(null, searchOptions);
}
determineSearchType_(query: string, preferredSearchType: any) {
if (preferredSearchType === SearchEngine.SEARCH_TYPE_BASIC) return SearchEngine.SEARCH_TYPE_BASIC;
if (preferredSearchType === SearchEngine.SEARCH_TYPE_NONLATIN_SCRIPT) return SearchEngine.SEARCH_TYPE_NONLATIN_SCRIPT;
// If preferredSearchType is "fts" we auto-detect anyway
// because it's not always supported.
let allTerms: any[] = [];
try {
allTerms = filterParser(query);
} catch (error) {
console.warn(error);
}
const textQuery = allTerms.filter(x => x.name === 'text' || x.name == 'title' || x.name == 'body').map(x => x.value).join(' ');
const st = scriptType(textQuery);
if (!Setting.value('db.ftsEnabled')) {
return SearchEngine.SEARCH_TYPE_BASIC;
}
// Non-alphabetical languages aren't support by SQLite FTS (except with extensions which are not available in all platforms)
if (['ja', 'zh', 'ko', 'th'].indexOf(st) >= 0) {
return SearchEngine.SEARCH_TYPE_NONLATIN_SCRIPT;
}
return SearchEngine.SEARCH_TYPE_FTS;
}
async search(searchString: string, options: any = null) {
if (!searchString) return [];
options = Object.assign({}, {
searchType: SearchEngine.SEARCH_TYPE_AUTO,
}, options);
const searchType = this.determineSearchType_(searchString, options.searchType);
const parsedQuery = await this.parseQuery(searchString);
if (searchType === SearchEngine.SEARCH_TYPE_BASIC) {
searchString = this.normalizeText_(searchString);
const rows = await this.basicSearch(searchString);
this.processResults_(rows, parsedQuery, true);
return rows;
} else {
// SEARCH_TYPE_FTS
// FTS will ignore all special characters, like "-" in the index. So if
// we search for "this-phrase" it won't find it because it will only
// see "this phrase" in the index. Because of this, we remove the dashes
// when searching.
// https://github.com/laurent22/joplin/issues/1075#issuecomment-459258856
const useFts = searchType === SearchEngine.SEARCH_TYPE_FTS;
try {
const { query, params } = queryBuilder(parsedQuery.allTerms, useFts);
const rows = await this.db().selectAll(query, params);
this.processResults_(rows, parsedQuery, !useFts);
return rows;
} catch (error) {
this.logger().warn(`Cannot execute MATCH query: ${searchString}: ${error.message}`);
return [];
}
}
}
async destroy() {
if (this.scheduleSyncTablesIID_) {
shim.clearTimeout(this.scheduleSyncTablesIID_);
this.scheduleSyncTablesIID_ = null;
}
SearchEngine.instance_ = null;
return new Promise((resolve) => {
const iid = shim.setInterval(() => {
if (!this.syncCalls_.length) {
shim.clearInterval(iid);
SearchEngine.instance_ = null;
resolve(null);
}
}, 100);
});
}
} | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import { PostStruct } from "../rpc/rpc-package";
import { blogDirName, blogIndexName } from '../constants';
import { PostIndexInfo, PostFile, PostBaseInfo } from './shared';
import { BlogPostFile } from './blog-post-file';
import { blogWorkspace } from './blog-workspace';
import { postImageReplace } from './post-image-replace';
export class BlogFile {
private _postIndexs: Array<PostIndexInfo>;
constructor() {
this._postIndexs = new Array<PostIndexInfo>();
}
/**
* 工作空间目录
*/
private get folderPath(): string {
return blogWorkspace.folderPath;
}
/**
* 索引路径
*/
private get indexPath(): string {
return path.join(this.folderPath, blogDirName, blogIndexName);
}
/**
* 索引Id
*/
private get indexId(): number {
return this.postIndexs.length === 0 ?
1 : this.postIndexs[this.postIndexs.length - 1].id + 1;
}
/**
* 读取文章索引
* @param folderPath
*/
private get postIndexs(): Array<PostIndexInfo> {
if (this._postIndexs.length === 0) {
let indexPath = this.indexPath;
if (fs.existsSync(indexPath)) {
let context = fs.readFileSync(indexPath, { encoding: 'utf8' });
this._postIndexs = JSON.parse(context);
}
}
return this._postIndexs;
}
/**
* 保存索引
* @param folderPath
* @param postIndexs
*/
private set postIndexs(postIndexs: Array<PostIndexInfo>) {
this._postIndexs = postIndexs;
this.savePostIndexs();
}
/**
* 持久化文章索引
*/
private savePostIndexs() {
fs.writeFileSync(this.indexPath, JSON.stringify(this.postIndexs));
}
/**
* 索引里面是否存在标题为title
* @param postIndexs
* @param title
*/
private hasIndexByTitle(title: string): boolean {
return this.postIndexs.findIndex(p => p.title === title) !== -1;
}
/**
* 更新或者添加索引
* @param postIndex
*/
private updateOrAddPostIndex(postIndex: PostIndexInfo): PostIndexInfo {
let oldPostIndex = this.postIndexs.find(p => p.postid === postIndex.postid);
if (oldPostIndex && postIndex.postid) {
postIndex.id = oldPostIndex.id;
if (oldPostIndex.title === oldPostIndex.remoteTitle) {//不相等不要覆盖
oldPostIndex.title = postIndex.title;
}
oldPostIndex.remoteTitle = postIndex.remoteTitle;
oldPostIndex.categories = postIndex.categories;
oldPostIndex.link = postIndex.link;
oldPostIndex.permalink = postIndex.permalink;
}
else {
postIndex.id = this.indexId;
this.postIndexs.push(postIndex);
}
this.savePostIndexs();
return postIndex;
}
private updataOrAddIndex(postIndex: PostIndexInfo) {
let oldPostIndex = this.postIndexs.find(p => p.id === postIndex.id);
if (oldPostIndex) {
oldPostIndex.postid = postIndex.postid;
oldPostIndex.title = postIndex.title;
oldPostIndex.remoteTitle = postIndex.remoteTitle;
oldPostIndex.categories = postIndex.categories;
oldPostIndex.link = postIndex.link;
oldPostIndex.permalink = postIndex.permalink;
}
else {
this.postIndexs.push(postIndex);
}
this.savePostIndexs();
}
/**
* 根据文章文件填补索引
* @param postIndexs
*/
private fillPostIndex(): void {
this.readPostFiles()
.filter(postFile => !this.hasIndexByTitle(postFile.title))
.forEach(postFile => {
this.updateOrAddPostIndex({
id: 0,
postid: 0,
title: postFile.title,
});
});
}
/**
* 读取文章索引的内容,并合并文件信息
*/
private postBaseInfosByIndex(): Array<PostBaseInfo> {
return this.postIndexs.map<PostBaseInfo>(postIndex => {
let blogPostFile = new BlogPostFile(postIndex);
let postBaseInfo: PostBaseInfo = {
id: postIndex.id,
postId: postIndex.postid,
title: postIndex.title,
remoteTitle: postIndex.remoteTitle,
categories: postIndex.categories,
link: postIndex.link,
permalink: postIndex.permalink,
state: blogPostFile.postState(),
fsPath: blogPostFile.postPath,
remotePath: blogPostFile.remotePostPath
};
return postBaseInfo;
});
}
/**
* 获取文章的文件列表
* @param folderPath
*/
private readPostFiles(): Array<PostFile> {
let folderPath = this.folderPath;
let postFiles = new Array<PostFile>();
const children = fs.readdirSync(folderPath);
for (let i = 0; i < children.length; i++) {
const child = children[i];
const filePath = path.join(folderPath, child);
const stat = fs.statSync(filePath);
if (stat.isFile()) {
let lastIndex = child.lastIndexOf('.');
let childSub = child.substring(0, lastIndex);
lastIndex = childSub.lastIndexOf('.');
postFiles.push({
title: this.titleDecodeURI(childSub.substring(0, lastIndex)),
fsPath: filePath
});
}
}
return postFiles;
}
/**
* 解码不符合文件名称的标题
*/
private titleDecodeURI(title:string): string{
return decodeURIComponent(title)
}
/**
* 读取本地的文章列表
*/
public readPosts(): Array<PostBaseInfo> {
let postBaseInfos = new Array<PostBaseInfo>();
if (blogWorkspace.hasWorkspace) {
this.fillPostIndex();
postBaseInfos.push(...this.postBaseInfosByIndex());
}
return postBaseInfos;
}
/**
* 更新多个文章到本地
* @param posts
*/
public async pullPosts(posts: Array<PostStruct>): Promise<void> {
if (await blogWorkspace.tryCreateBlogWorkspace()) {
for (let index = 0; index < posts.length; index++) {
await this.pullPost(posts[index]);
}
}
}
/**
* 根据postid创建一个BlogPostFile
* @param postId
*/
private createBlogPostFileByPostId(postId: string): BlogPostFile {
let postIndex = this.postIndexs.find(p => p.postid === postId.toString());
if (!postIndex || !postId) {
postIndex = { id: this.indexId, postid: postId, title: "" };
}
return new BlogPostFile(postIndex);
}
/**
* 根据id创建一个BlogPostFile
* @param id
*/
private createBlogPostFileById(id: number): BlogPostFile {
let postIndex = this.postIndexs.find(p => p.id === id);
if (!postIndex) {
throw new Error("该文章不存在");
}
return new BlogPostFile(postIndex);
}
/**
* 更新一个文章到本地
* @param post
*/
public async pullPost(post: PostStruct): Promise<void> {
let blogPostFile = this.createBlogPostFileByPostId(post.postid);
let description = await postImageReplace.toLocal(post.description);
blogPostFile.updatePost(post.title, description);
blogPostFile.updateRemotePost(post.title, description);
blogPostFile.updateCategories(post.categories);
let postIndex: PostIndexInfo = {
...blogPostFile.getPostIndexInfo(),
link: post.link,
permalink: post.permalink
};
this.updataOrAddIndex(postIndex);
}
/**
* 新建一个文章
* @param title
*/
public createPost(title: string): void {
if (this.hasIndexByTitle(title)) {
throw new Error("不能相同标题");
}
let blogPostFile = this.createBlogPostFileByPostId("");
blogPostFile.create(title);
this.updataOrAddIndex(blogPostFile.getPostIndexInfo());
}
/**
* 重命名标题
* @param postBaseInfo
* @param newTitle
*/
public renameTitle(postBaseInfo: PostBaseInfo, newTitle: string): string | undefined {
if (this.hasIndexByTitle(newTitle)) {
throw new Error("不能相同标题");
}
let blogPostFile = this.createBlogPostFileById(postBaseInfo.id);
blogPostFile.rename(newTitle);
this.updataOrAddIndex(blogPostFile.getPostIndexInfo());
return blogPostFile.postPath;
}
/**
* 查找文章
* @param id
*/
public async getPost(id: number): Promise<PostStruct> {
let blogPostFile = this.createBlogPostFileById(id);
let postIndex = blogPostFile.getPostIndexInfo();
let description = await postImageReplace.toRemote(blogPostFile.description());
let categories: string[] = postIndex.categories ? postIndex.categories : [];
if (!categories.includes("[Markdown]")) {
categories.push("[Markdown]");
}
let post: PostStruct = {
postid: postIndex.postid,
title: postIndex.title,
description: description,
categories: categories
};
return post;
}
/**
*
* @param postId
* @param id
*/
public updatePostId(postId: string, id: number): void {
let postIndex = this.postIndexs.find(p => p.id === id);
if (postIndex) {
postIndex.postid = postId;
this.updataOrAddIndex(postIndex);
}
}
/**
* 删除文章
* @param postBaseInfo
*/
public deletePost(postBaseInfo: PostBaseInfo): void {
let index = this.postIndexs.findIndex(p => p.id === postBaseInfo.id);
if (index !== -1) {
let blogPostFile = new BlogPostFile(this.postIndexs[index]);
blogPostFile.delete();
this.postIndexs.splice(index, 1);
this.savePostIndexs();
}
}
/**
* 添加一个或者多个分类
* @param id
* @param categories
*/
public addCategories(id: number, categories: string[]) {
let postIndex = this.postIndexs.find(p => p.id === id);
if (postIndex) {
if (postIndex.categories) {
postIndex.categories.push(...categories);
} else {
postIndex.categories = categories;
}
this.updataOrAddIndex(postIndex);
}
}
/**
* 删除一个分类
* @param id
* @param category
*/
public removeCategory(id: number, category: string) {
let postIndex = this.postIndexs.find(p => p.id === id);
if (postIndex) {
if (postIndex.categories) {
let index = postIndex.categories.indexOf(category);
postIndex.categories.splice(index, 1);
this.updataOrAddIndex(postIndex);
}
}
}
}
export const blogFile: BlogFile = new BlogFile(); | the_stack |
import { PointTuple, OutNode, Edge, ForceAtlas2LayoutOptions } from "../types";
import { Base } from "../base";
import { getEdgeTerminal, isArray, isNumber, isObject } from "../../util";
import Body from './body';
import Quad from './quad';
import QuadTree from './quadTree';
export class ForceAtlas2Layout extends Base {
/** 布局中心 */
public center: PointTuple = [0, 0];
/** 宽度 */
public width: number = 300;
/** 高度 */
public height: number = 300;
public nodes: OutNode[] = [];
public edges: Edge[] = [];
/**
* the parameter for repulsive forces,
* it will scale the layout but won't change the layout
* larger the kr, looser the layout
* @type {number}
*/
public kr: number = 5;
/**
* the parameter for gravity forces
* @type {number}
*/
public kg: number = 1;
/**
* modes:
* 'normal' for normal using
* 'linlog' for compact clusters.
* @type {string}
*/
public mode: 'normal' | 'linlog' = 'normal';
/**
* whether preventing the node overlapping
* @type {boolean}
*/
public preventOverlap: boolean = false;
/**
* whether active the dissuade hub mode
* true: grant authorities (nodes with a high indegree)
* a more central position than hubs (nodes with a high outdegree)
* @type {boolean}
*/
public dissuadeHubs: boolean = false;
/**
* whether active the barnes hut optimization on computing repulsive forces
* @type {boolean}
*/
public barnesHut: boolean | undefined = undefined;
/**
* the max iteration number
* @type {number}
*/
public maxIteration: number = 0;
/**
* control the global velocity
* defualt: 0.1(gephi)
* @type {number}
*/
public ks: number = 0.1;
/**
* the max global velocity
* @type {number}
*/
public ksmax: number = 10;
/**
* the tolerance for the global swinging
* @type {number}
*/
public tao: number = 0.1;
/**
* the function of layout complete listener, display the legend and minimap after layout
* @type {function}
*/
public onLayoutEnd: () => void = () => {};
public tick: () => void;
/**
* activate prune or not.
* prune the leaves during most iterations, layout the leaves in the last 50 iteraitons.
* if prune === '', it will be activated when the nodes number > 100
* note that it will reduce the quality of the layout
* @type {boolean}
*/
public prune: boolean | undefined = undefined;
public getWidth: (node: any) => number;
public getHeight: (node: any) => number;
constructor(options?: ForceAtlas2LayoutOptions) {
super();
this.updateCfg(options);
}
public getDefaultCfg() {
return {};
}
// execute the layout
public execute() {
const self = this;
const {
nodes,
onLayoutEnd,
prune,
} = self;
let maxIteration = self.maxIteration;
if (!self.width && typeof window !== "undefined") {
self.width = window.innerWidth;
}
if (!self.height && typeof window !== "undefined") {
self.height = window.innerHeight;
}
// the whidth of each nodes
const sizes = [];
const nodeNum = nodes.length;
for (let i = 0; i < nodeNum; i += 1) {
const node = nodes[i] as any;
let nodeWidth = 10;
let nodeHeight = 10;
if (isNumber(node.size)) {
nodeWidth = node.size;
nodeHeight = node.size;
}
if (isArray(node.size)) {
if (!isNaN(node.size[0])) nodeWidth = node.size[0];
if (!isNaN(node.size[1])) nodeHeight = node.size[1];
} else if (isObject(node.size)) {
nodeWidth = node.size.width;
nodeHeight = node.size.height;
}
if (self.getWidth && !isNaN(self.getWidth(node))) nodeHeight = self.getWidth(node);
if (self.getHeight && !isNaN(self.getHeight(node))) nodeWidth = self.getHeight(node);
const maxSize = Math.max(nodeWidth, nodeHeight);
sizes.push(maxSize);
}
if (self.barnesHut === undefined && nodeNum > 250) self.barnesHut = true;
if (self.prune === undefined && nodeNum > 100) self.prune = true;
if (this.maxIteration === 0 && !self.prune) {
maxIteration = 250;
if (nodeNum <= 200 && nodeNum > 100) maxIteration = 1000;
else if (nodeNum > 200) maxIteration = 1200;
this.maxIteration = maxIteration;
} else if (this.maxIteration === 0 && prune) {
maxIteration = 100;
if (nodeNum <= 200 && nodeNum > 100) maxIteration = 500;
else if (nodeNum > 200) maxIteration = 950;
this.maxIteration = maxIteration;
}
if (!self.kr) {
self.kr = 50;
if (nodeNum > 100 && nodeNum <= 500) self.kr = 20;
else if (nodeNum > 500) self.kr = 1;
}
if (!self.kg) {
self.kg = 20;
if (nodeNum > 100 && nodeNum <= 500) self.kg = 10;
else if (nodeNum > 500) self.kg = 1;
}
this.nodes = self.updateNodesByForces(sizes);
onLayoutEnd();
}
updateNodesByForces(sizes: number[]) {
const self = this;
const { edges, maxIteration } = self;
let nodes = self.nodes;
const nonLoopEdges = edges.filter((edge: any) => {
const source = getEdgeTerminal(edge, 'source');
const target = getEdgeTerminal(edge, 'target');
return source !== target;
});
const size = nodes.length;
const esize = nonLoopEdges.length;
const degrees = [];
const idMap: {[key: string]: number} = {};
const edgeEndsIdMap: {[key: number]: {sourceIdx: number, targetIdx: number}} = {};
// tslint:disable-next-line
const Es = []
for (let i = 0; i < size; i += 1) {
idMap[nodes[i].id] = i;
degrees[i] = 0;
if (nodes[i].x === undefined || isNaN(nodes[i].x)) { nodes[i].x = Math.random() * 1000; }
if (nodes[i].y === undefined || isNaN(nodes[i].y)) { nodes[i].y = Math.random() * 1000; }
Es.push({ x: nodes[i].x, y: nodes[i].y });
}
for (let i = 0; i < esize; i += 1) {
let node1;
let node2;
let sIdx = 0;
let tIdx = 0;
for (let j = 0; j < size; j += 1) {
const source = getEdgeTerminal(nonLoopEdges[i], 'source');
const target = getEdgeTerminal(nonLoopEdges[i], 'target');
if (nodes[j].id === source) {
node1 = nodes[j];
sIdx = j;
} else if (nodes[j].id === target) {
node2 = nodes[j];
tIdx = j;
}
edgeEndsIdMap[i] = { sourceIdx: sIdx, targetIdx: tIdx };
}
if (node1) degrees[idMap[node1.id]] += 1;
if (node2) degrees[idMap[node2.id]] += 1;
}
let iteration = maxIteration;
nodes = this.iterate(iteration, idMap, edgeEndsIdMap, esize, degrees, sizes);
// if prune, place the leaves around their parents, and then re-layout for several iterations.
if (self.prune) {
for (let j = 0; j < esize; j += 1) {
if (degrees[edgeEndsIdMap[j].sourceIdx] <= 1) {
nodes[edgeEndsIdMap[j].sourceIdx].x = nodes[edgeEndsIdMap[j].targetIdx].x;
nodes[edgeEndsIdMap[j].sourceIdx].y = nodes[edgeEndsIdMap[j].targetIdx].y;
} else if (degrees[edgeEndsIdMap[j].targetIdx] <= 1) {
nodes[edgeEndsIdMap[j].targetIdx].x = nodes[edgeEndsIdMap[j].sourceIdx].x;
nodes[edgeEndsIdMap[j].targetIdx].y = nodes[edgeEndsIdMap[j].sourceIdx].y;
}
}
self.prune = false;
self.barnesHut = false;
iteration = 100;
nodes = this.iterate(
iteration,
idMap,
edgeEndsIdMap,
esize,
degrees,
sizes
);
}
return nodes;
}
iterate(
iteration: number,
idMap: {[key: string]: number},
edgeEndsIdMap: {[key: number]: {sourceIdx: number, targetIdx: number}},
esize: number,
degrees: number[],
sizes: number[],
) {
const self = this;
let { nodes } = self;
const { kr, preventOverlap } = self;
const { barnesHut } = self;
const nodeNum = nodes.length;
let sg = 0;
const krPrime = 100;
let iter = iteration;
const prevoIter = 50;
let forces = [];
const preForces = [];
const bodies = [];
for (let i = 0; i < nodeNum; i += 1) {
forces[2 * i] = 0;
forces[2 * i + 1] = 0;
if (barnesHut) {
const params = {
id: i,
rx: nodes[i].x,
ry: nodes[i].y,
mass: 1,
g: kr,
degree: degrees[i]
};
bodies[i] = new Body(params);
}
}
while (iter > 0) {
for (let i = 0; i < nodeNum; i += 1) {
preForces[2 * i] = forces[2 * i];
preForces[2 * i + 1] = forces[2 * i + 1];
forces[2 * i] = 0;
forces[2 * i + 1] = 0;
}
// attractive forces, existing on every actual edge
forces = this.getAttrForces(
iter,
prevoIter,
esize,
idMap,
edgeEndsIdMap,
degrees,
sizes,
forces
);
// repulsive forces and Gravity, existing on every node pair
// if preventOverlap, using the no-optimized method in the last prevoIter instead.
if (barnesHut && ((preventOverlap && iter > prevoIter) || !preventOverlap)) {
forces = this.getOptRepGraForces(forces, bodies, degrees);
} else {
forces = this.getRepGraForces(iter, prevoIter, forces, krPrime, sizes, degrees);
}
// update the positions
const res = this.updatePos(forces, preForces, sg, degrees);
nodes = res.nodes;
sg = res.sg;
iter --;
if (self.tick) self.tick();
}
return nodes;
}
getAttrForces(
iter: number,
prevoIter: number,
esize: number,
idMap: {[key: string]: number},
edgeEndsIdMap: {[key: number]: {sourceIdx: number, targetIdx: number}},
degrees: number[],
sizes: number[],
forces: number[],
): number[] {
const self = this;
const { nodes, preventOverlap, dissuadeHubs, mode, prune } = self;
for (let i = 0; i < esize; i += 1) {
const sourceNode = nodes[edgeEndsIdMap[i].sourceIdx];
const sourceIdx = edgeEndsIdMap[i].sourceIdx;
const targetNode = nodes[edgeEndsIdMap[i].targetIdx];
const targetIdx = edgeEndsIdMap[i].targetIdx;
if (prune && (degrees[sourceIdx] <= 1 || degrees[targetIdx] <= 1)) continue;
const dir = [ targetNode.x - sourceNode.x, targetNode.y - sourceNode.y ];
let eucliDis = Math.hypot(dir[0], dir[1]);
eucliDis = eucliDis < 0.0001 ? 0.0001 : eucliDis;
dir[0] = dir[0] / eucliDis;
dir[1] = dir[1] / eucliDis;
if (preventOverlap && iter < prevoIter) eucliDis = eucliDis - sizes[sourceIdx] - sizes[targetIdx];
let Fa1 = eucliDis // tslint:disable-line
let Fa2 = Fa1 // tslint:disable-line
if (mode === 'linlog') {
Fa1 = Math.log(1 + eucliDis);
Fa2 = Fa1;
}
if (dissuadeHubs) {
Fa1 = eucliDis / degrees[sourceIdx];
Fa2 = eucliDis / degrees[targetIdx];
}
if (preventOverlap && iter < prevoIter && eucliDis <= 0) {
Fa1 = 0;
Fa2 = 0;
} else if (preventOverlap && iter < prevoIter && eucliDis > 0) {
Fa1 = eucliDis;
Fa2 = eucliDis;
}
forces[2 * idMap[sourceNode.id]] += Fa1 * dir[0];
forces[2 * idMap[targetNode.id]] -= Fa2 * dir[0];
forces[2 * idMap[sourceNode.id] + 1] += Fa1 * dir[1];
forces[2 * idMap[targetNode.id] + 1] -= Fa2 * dir[1];
}
return forces;
}
getRepGraForces(iter: number, prevoIter: number, forces: number[], krPrime: number, sizes: number[], degrees: number[]) {
const self = this;
const { nodes, preventOverlap, kr, kg, center, prune } = self;
const nodeNum = nodes.length;
for (let i = 0; i < nodeNum; i += 1) {
for (let j = i + 1; j < nodeNum; j += 1) {
if (prune && (degrees[i] <= 1 || degrees[j] <= 1)) continue;
const dir = [ nodes[j].x - nodes[i].x, nodes[j].y - nodes[i].y ];
let eucliDis = Math.hypot(dir[0], dir[1]);
eucliDis = eucliDis < 0.0001 ? 0.0001 : eucliDis;
dir[0] = dir[0] / eucliDis;
dir[1] = dir[1] / eucliDis;
if (preventOverlap && iter < prevoIter) eucliDis = eucliDis - sizes[i] - sizes[j];
let Fr = kr * (degrees[i] + 1) * (degrees[j] + 1) / eucliDis // tslint:disable-line
if (preventOverlap && iter < prevoIter && eucliDis < 0) {
Fr = krPrime * (degrees[i] + 1) * (degrees[j] + 1);
} else if (preventOverlap && iter < prevoIter && eucliDis === 0) {
Fr = 0;
} else if (preventOverlap && iter < prevoIter && eucliDis > 0) {
Fr = kr * (degrees[i] + 1) * (degrees[j] + 1) / eucliDis;
}
forces[2 * i] -= Fr * dir[0];
forces[2 * j] += Fr * dir[0];
forces[2 * i + 1] -= Fr * dir[1];
forces[2 * j + 1] += Fr * dir[1];
}
// gravity
const dir = [ nodes[i].x - center[0], nodes[i].y - center[1] ];
const eucliDis = Math.hypot(dir[0], dir[1]);
dir[0] = dir[0] / eucliDis;
dir[1] = dir[1] / eucliDis;
const Fg = kg * (degrees[i] + 1) // tslint:disable-line
forces[2 * i] -= Fg * dir[0];
forces[2 * i + 1] -= Fg * dir[1];
}
return forces;
}
getOptRepGraForces(forces: number[], bodies: any, degrees: number[]) {
const self = this;
const { nodes, kg, center, prune } = self;
const nodeNum = nodes.length;
let minx = 9e10;
let maxx = -9e10;
let miny = 9e10;
let maxy = -9e10;
for (let i = 0; i < nodeNum; i += 1) {
if (prune && (degrees[i] <= 1)) continue;
bodies[i].setPos(nodes[i].x, nodes[i].y);
if (nodes[i].x >= maxx) maxx = nodes[i].x;
if (nodes[i].x <= minx) minx = nodes[i].x;
if (nodes[i].y >= maxy) maxy = nodes[i].y;
if (nodes[i].y <= miny) miny = nodes[i].y;
}
const width = Math.max(maxx - minx, maxy - miny);
const quadParams = {
xmid: (maxx + minx) / 2,
ymid: (maxy + miny) / 2,
length: width,
massCenter: center,
mass: nodeNum
};
const quad = new Quad(quadParams);
const quadTree = new QuadTree(quad);
// build the tree, insert the nodes(quads) into the tree
for (let i = 0; i < nodeNum; i += 1) {
if (prune && (degrees[i] <= 1)) continue;
if (bodies[i].in(quad)) quadTree.insert(bodies[i]);
}
// update the repulsive forces and the gravity.
for (let i = 0; i < nodeNum; i += 1) {
if (prune && (degrees[i] <= 1)) continue;
bodies[i].resetForce();
quadTree.updateForce(bodies[i]);
forces[2 * i] -= bodies[i].fx;
forces[2 * i + 1] -= bodies[i].fy;
// gravity
const dir = [ nodes[i].x - center[0], nodes[i].y - center[1] ];
let eucliDis = Math.hypot(dir[0], dir[1]);
eucliDis = eucliDis < 0.0001 ? 0.0001 : eucliDis;
dir[0] = dir[0] / eucliDis;
dir[1] = dir[1] / eucliDis;
const Fg = kg * (degrees[i] + 1) // tslint:disable-line
forces[2 * i] -= Fg * dir[0];
forces[2 * i + 1] -= Fg * dir[1];
}
return forces;
}
updatePos(
forces: number[],
preForces: number[],
sg: number,
degrees: number[]
): { nodes: any, sg: number } {
const self = this;
const { nodes, ks, tao, prune, ksmax } = self;
const nodeNum = nodes.length;
const swgns = [];
const trans = [];
// swg(G) and tra(G)
let swgG = 0;
let traG = 0;
for (let i = 0; i < nodeNum; i += 1) {
if (prune && (degrees[i] <= 1)) continue;
const minus = [ forces[2 * i] - preForces[2 * i],
forces[2 * i + 1] - preForces[2 * i + 1]
];
const minusNorm = Math.hypot(minus[0], minus[1]);
const add = [ forces[2 * i] + preForces[2 * i],
forces[2 * i + 1] + preForces[2 * i + 1]
];
const addNorm = Math.hypot(add[0], add[1]);
swgns[i] = minusNorm;
trans[i] = addNorm / 2;
swgG += (degrees[i] + 1) * swgns[i];
traG += (degrees[i] + 1) * trans[i];
}
const preSG = sg;
sg = tao * traG / swgG // tslint:disable-line
if (preSG !== 0) {
sg = sg > (1.5 * preSG) ? (1.5 * preSG) : sg // tslint:disable-line
}
// update the node positions
for (let i = 0; i < nodeNum; i += 1) {
if (prune && (degrees[i] <= 1)) continue;
let sn = ks * sg / (1 + sg * Math.sqrt(swgns[i]));
let absForce = Math.hypot(forces[2 * i], forces[2 * i + 1]);
absForce = absForce < 0.0001 ? 0.0001 : absForce;
const max = ksmax / absForce;
sn = sn > max ? max : sn;
const dnx = sn * forces[2 * i];
const dny = sn * forces[2 * i + 1];
nodes[i].x += dnx;
nodes[i].y += dny;
}
return { nodes, sg };
}
} | the_stack |
declare namespace smarthome {
/**
* Smart home intents for discovery and control of local devices.
*/
enum Intents {
/**
* Received when a [[Constants.EventType]] event is sent from the platform.
* Currently only available for BLE Seamless Setup projects. For more
* details, see [[EventHandler]].
*/
EVENT = 'action.devices.EVENT',
/**
* Handle an execution request for a device with an established local
* execution path. For more details, see [[ExecuteHandler]].
*/
EXECUTE = 'action.devices.EXECUTE',
/**
* Report devices discovered using your scan configuration that support
* local fulfillment. For more details, see [[IdentifyHandler]].
*/
IDENTIFY = 'action.devices.IDENTIFY',
/**
* Sent when the user selects a device on Google Home app before
* clicking setup. The purpose is to give the user some visual indicator on
* which device is being set up. Currently only available for BLE Seamless
* Setup projects. For more details, see [[IndicateHandler]].
*/
INDICATE = 'action.devices.INDICATE',
/**
* A BLE notification is received by the platform. Currently only available
* for BLE Seamless Setup projects. For more details, see
* [[ParseNotificationHandler]].
*/
PARSE_NOTIFICATION = 'action.devices.PARSE_NOTIFICATION',
/**
* Sent when the user clicks setup on Google Home app to initiate device
* setup. Currently only available for BLE Seamless Setup projects. For more
* details, see [[ProvisionHandler]].
*/
PROVISION = 'action.devices.PROVISION',
/**
* A proxy is selected for reachable devices. For more details, see
* [[ProxySelectedHandler]].
*/
PROXY_SELECTED = 'action.devices.PROXY_SELECTED',
/**
* Fetch the state of the device.
* For more details, see [[QueryHandler]].
*/
QUERY = 'action.devices.QUERY',
/**
* Report additional devices connected through a local proxy or hub.
* For more details, see [[ReachableDevicesHandler]].
*/
REACHABLE_DEVICES = 'action.devices.REACHABLE_DEVICES',
/**
* Sent after a device is provisioned to ask for types and traits
* information. The purpose of the local intent is equivalent to the SYNC
* intent sent to your cloud fulfillment, so the logic for locally
* processing the intent resembles how you handle it in the cloud. Currently
* only available for BLE Seamless Setup projects. For more details, see
* [[RegisterHandler]].
*/
REGISTER = 'action.devices.REGISTER',
/**
* Sent when the user chooses to unlink from Google Home app or factory
* reset your device. Currently only available for BLE Seamless Setup
* projects. For more details, see [[UnprovisionHandler]].
*/
UNPROVISION = 'action.devices.UNPROVISION',
/**
* Sent when the device information has matched the OTA rules. Currently
* only available for BLE Seamless Setup projects. For more details, see
* [[UpdateHandler]].
*
* @hidden
*/
UPDATE = 'action.devices.UPDATE',
}
/**
* Encapsulates all intent request and response objects.
* @preferred
*/
namespace IntentFlow {
/**
* Describes the type of scannable code printed on the device, will be used
* by the GHA to know how to decode the scanned code.
* @hidden
*/
type ScanMode = 'QR_CODE'|'BAR_CODE'|'ALPHA_NUMERIC_CODE';
// Placeholder interface. Actual implementation depends on integration.
interface DeviceScanData {}
interface LocalUnIdentifiedDevice extends DeviceScanData {}
/**
* Scan data and device IDs provided by an [[IdentifyRequest]] to the
* application's `IDENTIFY` handler.
*/
interface LocalIdentifiedDevice extends DeviceScanData {
/** Device ID provided in the `SYNC` response. */
id?: string;
/**
* Custom data provided in the `SYNC` response. Not present if
* the device has `isLocalOnly` set to `true`.
*/
customData?: unknown;
/** Proxy data provided by `PROXY_SELECTED` response */
proxyData?: unknown;
}
/**
* Request passed to the application's `IDENTIFY` intent handler,
* containing a [[LocalIdentifiedDevice]] detected by the local
* scan configuration.
*
* See [[IdentifyHandler]] for more details.
*/
type IdentifyRequest = RequestInterface<LocalIdentifiedDevice>;
/**
* Request passed to the application's `REACHABLE_DEVICES` intent handler,
* containing a [[LocalIdentifiedDevice]] successfully identified as a proxy
* or hub.
*
* See [[ReachableDevicesHandler]] for more details.
*/
type ReachableDevicesRequest = RequestInterface<LocalIdentifiedDevice>;
/** Generally for CLOUD_SYNCED devices, verificationId is sufficient */
interface DeviceWithVerificationId {
/**
* Local device ID. This value must match one of the `otherDeviceIds`
* in the `SYNC` response.
*/
verificationId: string;
}
/** For LOCAL_SYNCED devices, id is required */
interface DeviceWithId {
/** Device ID from `IdentifyRequest` */
id: string;
}
// Other device characteristics, in addition to `id` or `verificationId`
interface DeviceCharacteristics {
/** Hardware type of the device */
type?: string;
/** Metadata describing the device */
deviceInfo?: DeviceInfo;
/**
* Describes how the device will behave when sent an INDICATE intent.
*/
indicationMode?: IndicationMode;
/**
* If true, this device can act as a proxy for other devices, enabling
* the `REACHABLE_DEVICES` intent.
* This is common for hub devices.
*/
isProxy?: boolean;
/**
* If true, indicates that the device can receive proxy commands from
* other devices.
*/
commandedOverProxy?: boolean;
/**
* If true, this device does not appear in the `SYNC` response.
* This is common for hub devices.
*/
isLocalOnly?: boolean;
/**
* If true, indicates that the BLE device must be bonded to before
* sending commands.
*/
requiresBonding?: boolean;
/**
* If true, indicates that a connection to the BLE device should
* not be established automatically.
*/
avoidAutoconnect?: boolean;
/**
* If true, indicates that the device is capable of being updated via
* commands from other devices.
* @hidden
*/
canBeUpdatedOverProxy?: boolean;
/**
* If true, indicates that the device is capable of being unprovisioned
* via commands from other devices.
* @hidden
*/
canBeUnprovisionedOverProxy?: boolean;
/**
* Describes the type of scannable code printed on the device.
* @hidden
*/
scanMode?: ScanMode;
/**
* If true, the platform will periodically send QUERY intents for the
* expecting JS to report state.
*/
willReportStateViaPoll?: boolean;
}
interface LocalDeviceInterface extends DeviceWithId,
DeviceCharacteristics {}
interface CloudSyncedDeviceInterface extends DeviceWithVerificationId,
DeviceCharacteristics {}
/**
* Content of the [[IdentifyResponse]] returned by the application's
* `IDENTIFY` intent handler.
*/
interface IdentifyResponsePayload extends ResponsePayload {
device: CloudSyncedDeviceInterface|LocalDeviceInterface;
}
/**
* Content of the [[ReachableDevicesResponse]] returned by the application's
* `REACHABLE_DEVICES` intent handler.
*/
interface ReachableDevicesPayload extends ResponsePayload {
/**
* List of device identifiers visible to the proxy device.
*
* Use `id` value if the reachable device is
* local-only and is not represented in the `SYNC` response.
*
* Use `verificationId` value if the reachable device should
* match one of the `otherDeviceIds` in the `SYNC` response.
*/
devices: Array<DeviceWithId|DeviceWithVerificationId>;
}
/**
* Response returned by the application's `IDENTIFY` intent handler
* to describe the locally discovered device.
*
* See [[IdentifyHandler]] for more details.
*/
type IdentifyResponse = ResponseInterface<IdentifyResponsePayload>;
/**
* Response returned by the application's `REACHABLE_DEVICES` intent handler
* to describe additional devices visible to the proxy device.
*
* See [[ReachableDevicesHandler]] for more details.
*/
type ReachableDevicesResponse = ResponseInterface<ReachableDevicesPayload>;
/**
* Callback registered with the [[App]] via [[App.onIdentify]] to process
* incoming device discovery requests.
*
* To support local fulfillment, the local home platform sends an `IDENTIFY`
* intent to discover what devices are present locally, then uses the
* `SYNC` intent to verify with the provider's cloud service that the
* device is available for local fulfillment.
*
* To learn more about how the platform establishes a local fulfillment
* path, see the [developer guide](/assistant/smarthome/develop/local).
*
* ```typescript
* const identifyHandler = (request: IntentFlow.IdentifyRequest):
* IntentFlow.IdentifyResponse => {
*
* // Obtain scan data from protocol defined in your scan config
* const device = request.inputs[0].payload.device;
* const scanData = device.udpScanData;
*
* // Decode scan data to obtain metadata about local device
* const verificationId = "local-device-id";
*
* // Return a response
* const response: IntentFlow.IdentifyResponse = {
* intent: Intents.IDENTIFY,
* requestId: request.requestId,
* payload: {
* device: {
* id: device.id || "",
* verificationId, // Must match otherDeviceIds in SYNC response
* },
* },
* };
* return response;
* };
* ```
*
*/
interface IdentifyHandler extends
IntentHandler<IdentifyRequest, IdentifyResponse> {}
/**
* Callback registered with the [[App]] via [[App.onReachableDevices]] to
* discover additional devices connected to a proxy or hub.
*
* When a device that is discovered by the [[IdentifyHandler]] is a proxy
* which enables indirect access to other devices (identified by the
* [[IdentifyResponsePayload.device|isProxy]] flag in the
* [[IdentifyResponse]]), the local home platform sends a
* `REACHABLE_DEVICES` intent to discover the additional devices visible
* to the proxy.
*
* To learn more about how the platform verifies reachable devices,
* see the [developer guide](/assistant/smarthome/develop/local).
*
* ```typescript
* const devicesHandler = (request: IntentFlow.ReachableDevicesRequest):
* IntentFlow.ReachableDevicesResponse => {
*
* // Reference to the local proxy device
* const proxyDevice = request.inputs[0].payload.device.proxyDevice;
*
* // Query local proxy device for additional visible ids
* // ...
* const reachableDevices = [
* // Each verificationId must match one of the otherDeviceIds
* // in the SYNC response
* { verificationId: "local-device-id-1" },
* { verificationId: "local-device-id-2" },
* ];
*
* // Return a response
* const response: IntentFlow.ReachableDevicesResponse = {
* intent: Intents.REACHABLE_DEVICES,
* requestId: request.requestId,
* payload: {
* devices: reachableDevices,
* },
* };
* return response;
* };
* ```
*
*/
interface ReachableDevicesHandler extends
IntentHandler<ReachableDevicesRequest, ReachableDevicesResponse> {}
/** BLE Seamless Setup interfaces & classes */
/** Reusable interfaces. */
interface BleNotification {
serviceUuid: string;
characteristicUuid: string;
value: string;
}
interface LocalNotifyingDevice extends DeviceScanData {
id: string;
customData?: unknown;
protocol: Constants.Protocol;
notificationData: BleNotification;
}
/**
* Scan data and device IDs provided by an [[ProvisionRequest]] to the
* application's `PROVISION` handler.
*/
interface LocalProvisioningDevice extends DeviceScanData {
/** Device ID provided in the `SYNC` response. */
id?: string;
/** @hidden WiFi SSID to be used in provisioning. */
ssid?: string;
/** @hidden Pin code entered by the user, when code scan fails. */
pinCode?: string;
/**
* @hidden Present if the device represents a 3P device in softAP mode.
* The length of passwordPlaceholder is equal to the length of the actual
* WiFi credential but the value is only a placeholder (it is not the real
* password).
*/
passwordPlaceholder?: string;
}
interface LocalRegisteringDevice extends DeviceScanData {
id?: string;
name: string;
}
interface LocalRegisteredDevice extends DeviceScanData {
id: string;
customData?: unknown;
}
interface LocalEventEmitterDevice {
id: string;
}
// Intent specific params.EventRequest
interface IndicateRequestParams {
start: boolean;
}
interface UpdateRequestParams {
url: string;
}
/** Request Object for EVENT intent. */
type EventRequest = RequestInterface<LocalEventEmitterDevice>;
/** Request Object for INDICATE intent. */
type IndicateRequest =
RequestInterface<LocalIdentifiedDevice, IndicateRequestParams>;
/** Request Object for PARSE_NOTIFICATION intent. */
type ParseNotificationRequest = RequestInterface<LocalNotifyingDevice>;
/** Request Object for PROVISION intent. */
type ProvisionRequest = RequestInterface<LocalProvisioningDevice>;
/** Request Object for REGISTER intent. */
type RegisterRequest = RequestInterface<LocalRegisteringDevice>;
/** Request Object for UNPROVISION intent. */
type UnprovisionRequest = RequestInterface<LocalRegisteredDevice>;
/** Request Object for UPDATE intent. */
type UpdateRequest =
RequestInterface<LocalRegisteredDevice, UpdateRequestParams>;
/**
* Request passed to the application's `PROXY_SELECTED` intent handler,
* containing a [[LocalIdentifiedDevice]] detected by the local
* scan configuration.
*/
type ProxySelectedRequest = RequestInterface<LocalIdentifiedDevice>;
interface ParseNotificationResponsePayload extends ResponsePayload {}
interface ProvisionResponsePayload extends ResponsePayload {
structureData: object;
}
interface RegisterResponsePayload extends ResponsePayload {
devices: Device[];
}
interface UpdateResponsePayload extends ResponsePayload {
swVersion: string;
}
/**
* Content of the [[ProxySelectedResponse]] returned by the application's
* `PROXY_SELECTED` intent handler.
*/
interface ProxySelectedPayload extends ResponsePayload {
/**
* Proxy data is a JSON similar to customData for the Bridge/Hub devices.
* It can be retrieved from the `proxyData` field of the JSON returned by
* [[DeviceManager.getProxyInfo]] API.
*/
proxyData?: unknown;
}
/** Response Object for EVENT intent. */
type EventResponse = ResponseInterface<ResponsePayload>;
/** Response Object for INDICATE intent. */
type IndicateResponse = ResponseInterface<ResponsePayload>;
/** Response Object for PARSE_NOTIFICATION intent. */
type ParseNotificationResponse =
ResponseInterface<ParseNotificationResponsePayload>;
/** Response Object for PROVISION intent. */
type ProvisionResponse = ResponseInterface<ProvisionResponsePayload>;
/** Response Object for REGISTER intent. */
type RegisterResponse = ResponseInterface<RegisterResponsePayload>;
/** Response Object for UPDATE intent. */
type UpdateResponse = ResponseInterface<UpdateResponsePayload>;
/** Response Object for UNPROVISION intent. */
type UnprovisionResponse = ResponseInterface<ResponsePayload>;
/**
* Response returned by the application's `PROXY_SELECTED` intent handler
* to save information about the selected proxy.
*/
type ProxySelectedResponse = ResponseInterface<ProxySelectedPayload>;
/** Handler type for EVENT intent. */
type EventHandler = IntentHandler<EventRequest, EventResponse>;
/** Handler type for INDICATE intent. */
type IndicateHandler = IntentHandler<IndicateRequest, IndicateResponse>;
/** Handler type for REGISTER intent. */
type RegisterHandler = IntentHandler<RegisterRequest, RegisterResponse>;
/** Handler type for PROVISION intent. */
type ProvisionHandler = IntentHandler<ProvisionRequest, ProvisionResponse>;
/** Handler type for UNPROVISION intent. */
type UnprovisionHandler =
IntentHandler<UnprovisionRequest, UnprovisionResponse>;
/** Handler type for UPDATE intent. */
type UpdateHandler = IntentHandler<UpdateRequest, UpdateResponse>;
/** Handler type for PARSE_NOTIFICATION intent. */
type ParseNotificationHandler = IntentHandler<
ParseNotificationRequest,
ParseNotificationResponse|ReportState.Response.Payload>;
/**
* Callback registered with the [[App]] via `onProxySelected()` to
* allow app to save proxyData for the hub device.
*/
type ProxySelectedHandler =
IntentHandler<ProxySelectedRequest, ProxySelectedResponse>;
}
} | the_stack |
import {
Logger, logger,
LoggingDebugSession,
StoppedEvent, OutputEvent,
Thread, Source, Module, ModuleEvent, InitializedEvent, Scope, Variable, Event, TerminatedEvent, LoadedSourceEvent
} from 'vscode-debugadapter';
import { DebugProtocol } from 'vscode-debugprotocol';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import * as semver from 'semver';
import * as vscode from 'vscode';
import { Uri } from 'vscode';
import { encodeBreakpoints, luaBlockQuote } from './EncodingUtil';
import { Profile } from './Profile';
import { FactorioProcess } from './FactorioProcess';
import { ModInfo } from './ModPackageProvider';
import { assert } from 'console';
import { ModManager } from './ModManager';
import { ModSettings } from './ModSettings';
import { LuaFunction } from './LuaDisassembler';
import { BufferStream } from './BufferStream';
interface ModPaths{
uri: Uri
name: string
version: string
info: ModInfo
}
type EvaluateResponseBody = DebugProtocol.EvaluateResponse['body'] & {
// sequence number of this eval
seq: number
// translation ID for time this eval ran
timer?: number
};
type resolver<T> = (value?: T | PromiseLike<T> | undefined)=>void;
interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
factorioPath: string // path of factorio binary to launch
nativeDebugger: string // path to native debugger if in use
modsPath: string // path of `mods` directory
modsPathSource: string
configPath: string // path to config.ini
configPathDetected?: boolean
dataPath: string // path of `data` directory, always comes from config.ini
manageMod?: boolean
useInstrumentMode?: boolean
checkPrototypes?: boolean
checkGlobals?: string[]|boolean
factorioArgs?: Array<string>
adjustMods?:{[key:string]:boolean|string}
adjustModSettings?:{
scope: "startup"|"runtime-global"|"runtime-per-user"
name: string
value?:boolean|number|string
}[]
disableExtraMods?:boolean
allowDisableBaseMod?:boolean
hookSettings?:boolean
hookData?:boolean
hookControl?:string[]|boolean
hookMode?:"debug"|"profile"
hookLog?:boolean
keepOldLog?:boolean
runningBreak?:number
runningTimeout?:number
profileLines?:boolean
profileFuncs?:boolean
profileTree?:boolean
profileSlowStart?: number
profileUpdateRate?: number
/** enable logging the Debug Adapter Protocol */
trace?: boolean
}
export class FactorioModDebugSession extends LoggingDebugSession {
private context: vscode.ExtensionContext;
// we don't support multiple threads, so we can use a hardcoded ID for the default thread
private static THREAD_ID = 1;
private _configurationDone: resolver<void>;
private configDone: Promise<void>;
private readonly breakPoints = new Map<string, DebugProtocol.SourceBreakpoint[]>();
private readonly breakPointsChanged = new Set<string>();
// unhandled only by default
private readonly exceptionFilters = new Set<string>(["unhandled"]);
private readonly _modules = new Map<string,DebugProtocol.Module>();
private readonly _responses = new Map<number,DebugProtocol.Response>();
private readonly _dumps = new Map<number, resolver<string>>();
private readonly _scopes = new Map<number, resolver<Scope[]>>();
private readonly _vars = new Map<number, resolver<Variable[]>>();
private readonly _setvars = new Map<number, resolver<Variable>>();
private readonly _evals = new Map<number, resolver<EvaluateResponseBody>>();
private readonly translations = new Map<number, string>();
private nextRef = 1;
private factorio : FactorioProcess;
private stdinQueue:{buffer:Buffer;resolve:resolver<boolean>;consumed?:Promise<void>;token?:vscode.CancellationToken}[] = [];
private launchArgs: LaunchRequestArguments;
private inPrompt:boolean = false;
private pauseRequested:boolean = false;
private profile?: Profile;
private workspaceModInfoReady:Promise<void>;
private readonly workspaceModInfo = new Array<ModPaths>();
private editorWatcher?:vscode.Disposable;
/**
* Creates a new debug adapter that is used for one debug session.
* We configure the default implementation of a debug adapter here.
*/
public constructor() {
super();
this.setDebuggerLinesStartAt1(true);
this.setDebuggerColumnsStartAt1(true);
this.setDebuggerPathFormat("uri");
this.workspaceModInfoReady = new Promise(async (resolve)=>{
const infos = await vscode.workspace.findFiles('**/info.json');
infos.forEach(this.updateInfoJson,this);
resolve();
});
this.editorWatcher = vscode.window.onDidChangeActiveTextEditor(editor =>{
if (editor && this.profile && (editor.document.uri.scheme==="file"||editor.document.uri.scheme==="zip"))
{
const profname = this.convertClientPathToDebugger(editor.document.uri.toString());
this.profile.render(editor,profname);
}
});
}
public setContext(context: vscode.ExtensionContext)
{
assert(!this.context);
this.context = context;
}
/**
* The 'initialize' request is the first request called by the frontend
* to interrogate the features the debug adapter provides.
*/
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
// build and return the capabilities of this debug adapter:
response.body = response.body || {};
response.body.supportsConditionalBreakpoints = true;
response.body.supportsHitConditionalBreakpoints = true;
response.body.supportsEvaluateForHovers = true;
response.body.exceptionBreakpointFilters = [
{ filter: "pcall", label: "Caught by pcall", default:false },
{ filter: "xpcall", label: "Caught by xpcall", default:false },
{ filter: "unhandled", label: "Unhandled Exceptions", default:true },
];
response.body.supportsSetVariable = true;
response.body.supportsModulesRequest = true;
response.body.supportsLogPoints = true;
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsLoadedSourcesRequest = true;
response.body.supportsDisassembleRequest = true;
response.body.supportsSteppingGranularity = true;
response.body.supportsInstructionBreakpoints = false;
this.sendResponse(response);
}
/**
* Called at the end of the configuration sequence.
* Indicates that all breakpoints etc. have been sent to the DA and that the 'launch' can start.
*/
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
super.configurationDoneRequest(response, args);
// notify that configuration has finished
// eslint-disable-next-line no-unused-expressions
this._configurationDone?.();
}
protected terminateRequest(response: DebugProtocol.TerminateResponse, args: DebugProtocol.TerminateArguments): void {
this.terminate();
this.sendResponse(response);
}
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments): void {
this.terminate();
this.sendResponse(response);
}
protected async launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments) {
// make sure to 'Stop' the buffered logging if 'trace' is not set
logger.setup(args.trace ? Logger.LogLevel.Verbose : Logger.LogLevel.Stop, false);
this.launchArgs = args;
args.hookSettings = args.hookSettings ?? false;
args.hookData = args.hookData ?? false;
args.hookControl = args.hookControl ?? true;
args.hookMode = args.hookMode ?? "debug";
args.trace = args.trace ?? false;
if (args.hookMode === "profile" && !args.noDebug) {
this.profile = new Profile(args.profileTree ?? true, this.context);
this.profile.on("flameclick", async (mesg)=>{
if (mesg.filename && mesg.line)
{
vscode.window.showTextDocument(
Uri.parse(this.convertDebuggerPathToClient(mesg.filename)),
{
selection: new vscode.Range(mesg.line,0,mesg.line,0),
viewColumn: vscode.ViewColumn.One
}
);
}
});
}
const tasks = (await vscode.tasks.fetchTasks({type:"factorio"})).filter(
(task)=>task.definition.command === "compile"
);
if (tasks.length > 0)
{
this.sendEvent(new OutputEvent(`Running ${tasks.length} compile tasks: ${tasks.map(task=>task.name).join(", ")}\n`,"stdout"));
await Promise.all(tasks.map(FactorioModDebugSession.runTask));
}
this.sendEvent(new OutputEvent(`using ${args.configPathDetected?"auto-detected":"manually-configured"} config.ini: ${args.configPath}\n`,"stdout"));
args.modsPath = args.modsPath.replace(/\\/g,"/");
// check for folder or symlink and leave it alone, if zip update if mine is newer
this.sendEvent(new OutputEvent(`using modsPath ${args.modsPath} (${args.modsPathSource})\n`,"stdout"));
if(args.manageMod === false)
{
this.sendEvent(new OutputEvent(`automatic management of mods disabled\n`,"stdout"));
}
else
{
if (!args.adjustMods) {args.adjustMods = {};}
if (!args.allowDisableBaseMod) {args.adjustMods["base"] = true;}
const packagedModsList = this.context.asAbsolutePath("./modpackage/mods.json");
if(!fs.existsSync(packagedModsList))
{
this.sendEvent(new OutputEvent(`package list missing in extension\n`,"stdout"));
}
else
{
const manager = new ModManager(args.modsPath);
if (args.disableExtraMods) {
manager.disableAll();
}
for (const mod in args.adjustMods) {
if (args.adjustMods.hasOwnProperty(mod))
{
const adjust = args.adjustMods[mod];
manager.set(mod,adjust);
}
}
const packages:{[key:string]:{version:string;debugOnly?:boolean;deleteOld?:boolean}} = JSON.parse(fs.readFileSync(packagedModsList, "utf8"));
if (!args.noDebug)
{
manager.set("coverage",false);
manager.set("profiler",false);
for (const mod in packages) {
if (packages.hasOwnProperty(mod))
{
const modpackage = packages[mod];
const zippath = this.context.asAbsolutePath(`./modpackage/${mod}.zip`);
const result = manager.installMod(mod,modpackage.version,zippath,modpackage.deleteOld);
this.sendEvent(new OutputEvent(`package install ${mod} ${JSON.stringify(result)}\n`,"stdout"));
}
}
}
else
{
for (const mod in packages) {
if (packages.hasOwnProperty(mod))
{
const modpackage = packages[mod];
if (modpackage.debugOnly)
{
manager.set(mod,false);
}
}
}
}
manager.write();
this.sendEvent(new OutputEvent(`debugadapter ${args.noDebug?"disabled":"enabled"} in mod-list.json\n`,"stdout"));
}
}
args.dataPath = args.dataPath.replace(/\\/g,"/");
this.sendEvent(new OutputEvent(`using dataPath ${args.dataPath}\n`,"stdout"));
await this.workspaceModInfoReady;
args.factorioArgs = args.factorioArgs||[];
if(!args.noDebug)
{
if (args.useInstrumentMode ?? true)
{
args.factorioArgs.push("--instrument-mod","debugadapter");
}
if((args.checkPrototypes ?? true) && !args.factorioArgs.includes("--check-unused-prototype-data"))
{
args.factorioArgs.push("--check-unused-prototype-data");
}
}
if (!args.configPathDetected)
{
args.factorioArgs.push("--config",args.configPath);
}
if (args.modsPathSource !== "config")
{
let mods = args.modsPath;
if (!mods.endsWith("/"))
{
mods += "/";
}
args.factorioArgs.push("--mod-directory",mods);
}
this.createSteamAppID(args.factorioPath);
if (args.adjustModSettings)
{
const settings = new ModSettings(fs.readFileSync(path.join(args.modsPath,"mod-settings.dat")));
for (const s of args.adjustModSettings) {
settings.set(s.scope,s.name,s.value);
}
fs.writeFileSync(path.join(args.modsPath,"mod-settings.dat"),settings.save());
}
this.factorio = new FactorioProcess(args.factorioPath,args.factorioArgs,args.nativeDebugger);
this.factorio.on("exit", (code:number|null, signal:string) => {
if (this.profile)
{
this.profile.dispose();
this.profile = undefined;
}
if (code)
{
// exit event in case somebody cares about the return code
this.sendEvent(new Event("exited",{exitCode:code}));
}
// and terminate event to actually stop the debug session
this.sendEvent(new TerminatedEvent());
});
let resolveModules:resolver<void>;
const modulesReady = new Promise<void>((resolve)=>{
resolveModules = resolve;
});
this.factorio.on("stderr",(mesg:string)=>this.sendEvent(new OutputEvent(mesg+"\n","stderr")));
this.factorio.on("stdout",async (mesg:string)=>{
if (this.launchArgs.trace && mesg.startsWith("DBG")){this.sendEvent(new OutputEvent(`> ${mesg}\n`, "console"));}
if (mesg.startsWith("DBG: ")) {
const wasInPrompt = this.inPrompt;
this.inPrompt = true;
let event = mesg.substring(5).trim();
if (event === "on_tick") {
//if on_tick, then update breakpoints if needed and continue
await this.runQueuedStdin();
this.continue();
} else if (event === "on_data") {
//data/settings main chunk - force all breakpoints each time this comes up because it can only set them locally
await this.configDone;
this.clearQueuedStdin();
this.allocateRefBlock();
this.continue(true);
} else if (event === "on_parse") {
//control.lua main chunk - force all breakpoints each time this comes up because it can only set them locally
this.clearQueuedStdin();
this.allocateRefBlock();
this.continue(true);
} else if (event === "on_init") {
//if on_init, set initial breakpoints and continue
await this.runQueuedStdin();
this.continue(true);
} else if (event === "on_load") {
//on_load set initial breakpoints and continue
await this.runQueuedStdin();
this.continue(true);
} else if (event === "getref") {
//pass in nextref
this.allocateRefBlock();
this.continue();
this.inPrompt = wasInPrompt;
} else if (event === "leaving" || event === "running") {
//run queued commands
await this.runQueuedStdin();
if (this.pauseRequested)
{
this.pauseRequested = false;
if(this.breakPointsChanged.size !== 0)
{
this.updateBreakpoints();
}
this.sendEvent(new StoppedEvent('pause', FactorioModDebugSession.THREAD_ID));
}
else
{
this.continue();
this.inPrompt = wasInPrompt;
}
} else if (event === "terminate") {
this.terminate();
} else if (event.startsWith("step")) {
// notify stoponstep
await this.runQueuedStdin();
if(this.breakPointsChanged.size !== 0)
{
this.updateBreakpoints();
}
this.sendEvent(new StoppedEvent('step', FactorioModDebugSession.THREAD_ID));
} else if (event === "breakpoint") {
// notify stop on breakpoint
await this.runQueuedStdin();
if(this.breakPointsChanged.size !== 0)
{
this.updateBreakpoints();
}
this.sendEvent(new StoppedEvent('breakpoint', FactorioModDebugSession.THREAD_ID));
} else if (event.startsWith("exception")) {
// notify stop on exception
await this.runQueuedStdin();
const sub = event.substr(10);
const split = sub.indexOf("\n");
const filter = sub.substr(0,split).trim();
const err = sub.substr(split+1);
if (filter === "manual" || this.exceptionFilters.has(filter))
{
this.sendEvent(new StoppedEvent('exception', FactorioModDebugSession.THREAD_ID,err));
}
else
{
this.continue();
}
} else if (event === "on_instrument_settings") {
await modulesReady;
this.clearQueuedStdin();
if (this.launchArgs.hookMode === "profile")
{
this.continueRequire(false,"#settings");
}
else
{
this.continueRequire(this.launchArgs.hookSettings ?? false,"#settings");
}
} else if (event === "on_instrument_data") {
this.clearQueuedStdin();
if (this.launchArgs.hookMode === "profile")
{
this.continueRequire(false,"#data");
}
else
{
this.continueRequire(this.launchArgs.hookData ?? false,"#data");
}
} else if (event.startsWith("on_instrument_control ")) {
this.clearQueuedStdin();
const modname = event.substring(22).trim();
const hookmods = this.launchArgs.hookControl ?? true;
const shouldhook =
// DA has to be specifically requested for hooks
modname === "debugadapter" ? Array.isArray(hookmods) && hookmods.includes(modname) :
// everything else...
hookmods !== false && (hookmods === true || hookmods.includes(modname));
if (this.launchArgs.hookMode === "profile")
{
this.continueProfile(shouldhook);
}
else
{
this.continueRequire(shouldhook,modname);
}
} else if (event === "on_da_control") {
const hookmods = this.launchArgs.hookControl ?? true;
const dahooked = ((Array.isArray(hookmods) && hookmods.includes("debugadapter")) || hookmods === false);
if (this.launchArgs.hookMode === "profile")
{
this.continueProfile(!dahooked);
}
else
{
this.continueRequire(false,"debugadapter");
}
} else {
// unexpected event?
this.sendEvent(new OutputEvent("unexpected event: " + event + "\n","stderr"));
this.continue();
}
} else if (mesg.startsWith("DBGlogpoint: ")) {
const body = JSON.parse(mesg.substring(13).trim());
const e:DebugProtocol.OutputEvent = new OutputEvent(body.output+"\n", "console");
if(body.variablesReference) {
e.body.variablesReference = body.variablesReference;
}
if(body.source) {
e.body.source = this.createSource(body.source);
}
if (body.line) {
e.body.line = this.convertDebuggerLineToClient(body.line);
}
this.sendEvent(e);
} else if (mesg.startsWith("DBGprint: ")) {
const body = JSON.parse(mesg.substring(10).trim());
const lsid = body.output.match(/\{LocalisedString ([0-9]+)\}/);
if (lsid)
{
const id = Number.parseInt(lsid[1]);
body.output = this.translations.get(id) ?? `{Missing Translation ID ${id}}`;
}
const e:DebugProtocol.OutputEvent = new OutputEvent(body.output+"\n", body.category ?? "console");
if(body.variablesReference) {
e.body.variablesReference = body.variablesReference;
}
if(body.source.path) {
body.source.path = this.convertDebuggerPathToClient(body.source.path);
}
e.body.source = body.source;
if (body.line) {
e.body.line = this.convertDebuggerLineToClient(body.line);
}
this.sendEvent(e);
} else if (mesg.startsWith("DBGstack: ")) {
const stackresult:{frames:DebugProtocol.StackFrame[];seq:number} = JSON.parse(mesg.substring(10).trim());
this.finishStackTrace(stackresult.frames,stackresult.seq);
} else if (mesg.startsWith("DBGdump: ")) {
const dump:{dump:string|undefined;source:string|undefined;ref:number} = JSON.parse(mesg.substring(9).trim());
this.finishSource(dump);
} else if (mesg.startsWith("EVTmodules: ")) {
if (this.launchArgs.trace){this.sendEvent(new OutputEvent(`> EVTmodules\n`, "console"));}
await this.updateModules(JSON.parse(mesg.substring(12).trim()));
resolveModules();
this.configDone = new Promise<void>((resolve)=>{
this._configurationDone = resolve;
});
// and finally send the initialize event to get breakpoints and such...
this.sendEvent(new InitializedEvent());
} else if (mesg.startsWith("EVTsource: ")) {
if (this.launchArgs.trace){this.sendEvent(new OutputEvent(`> EVTsource\n`, "console"));}
await this.loadedSourceEvent(JSON.parse(mesg.substring(11).trim()));
} else if (mesg.startsWith("DBGscopes: ")) {
const scopes = JSON.parse(mesg.substring(11).trim());
this._scopes.get(scopes.frameId)!(scopes.scopes);
this._scopes.delete(scopes.frameId);
} else if (mesg.startsWith("DBGvars: ")) {
const vars = JSON.parse(mesg.substring(9).trim());
this._vars.get(vars.seq)!(vars.vars);
this._vars.delete(vars.seq);
} else if (mesg.startsWith("DBGsetvar: ")) {
const result = JSON.parse(mesg.substring(11).trim());
this._setvars.get(result.seq)!(result.body);
this._setvars.delete(result.seq);
} else if (mesg.startsWith("DBGeval: ")) {
const evalresult:EvaluateResponseBody = JSON.parse(mesg.substring(9).trim());
this._evals.get(evalresult.seq)!(evalresult);
this._evals.delete(evalresult.seq);
} else if (mesg.startsWith("DBGtranslate: ")) {
const sub = mesg.substr(14);
const split = sub.indexOf("\n");
const id = Number.parseInt(sub.substr(0,split).trim());
const translation = sub.substr(split+1);
this.translations.set(id,translation);
} else if (mesg === "DBGuntranslate") {
this.translations.clear();
} else if (mesg.startsWith("PROFILE:")) {
if (this.profile)
{
const editor = vscode.window.activeTextEditor;
this.profile.parse(mesg);
if (editor && (editor.document.uri.scheme==="file"||editor.document.uri.scheme==="zip"))
{
const profname = this.convertClientPathToDebugger(editor.document.uri.toString());
this.profile.render(editor,profname);
}
}
} else {
//raise this as a stdout "Output" event
this.sendEvent(new OutputEvent(mesg+"\n", "stdout"));
}
});
this.sendResponse(response);
}
private allocateRefBlock()
{
const nextRef = this.nextRef;
this.nextRef += 65536;
this.writeStdin(`__DebugAdapter.transferRef(${nextRef})`);
}
protected convertClientPathToDebugger(clientPath: string): string
{
if(clientPath.startsWith("output:")){return clientPath;}
clientPath = clientPath.replace(/\\/g,"/");
let thismodule:DebugProtocol.Module|undefined;
this._modules.forEach(m=>{
if (m.symbolFilePath && clientPath.startsWith(m.symbolFilePath) &&
m.symbolFilePath.length > (thismodule?.symbolFilePath||"").length)
{
thismodule = m;
}
});
if (thismodule)
{
return clientPath.replace(thismodule.symbolFilePath!,"@__"+thismodule.name+"__");
}
this.sendEvent(new OutputEvent(`unable to translate path ${clientPath}\n`,"stderr"));
return clientPath;
}
protected convertDebuggerPathToClient(debuggerPath: string): string
{
const matches = debuggerPath.match(/^@__(.*?)__\/(.*)$/);
if (matches)
{
const thismodule = this._modules.get(matches[1]);
if (thismodule?.symbolFilePath)
{
return Uri.joinPath(Uri.parse(thismodule.symbolFilePath),matches[2]).toString();
}
}
return debuggerPath;
}
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void {
let bpuri:Uri;
let bppath:string;
if (args.source.path)
{
const inpath = <string>args.source.path;
if (inpath.match(/^[a-zA-Z]:/)) // matches c:\... or c:/... style windows paths, single drive letter
{
bpuri = Uri.file(inpath.replace(/\\/g,"/"));
}
else // everything else is already a URI
{
bpuri = Uri.parse(inpath);
}
bppath = this.convertClientPathToDebugger(bpuri.toString());
} else {
bppath = `&ref ${args.source.sourceReference}`;
}
const bps = (args.breakpoints || []).map((bp)=>{
bp.line = this.convertClientLineToDebugger(bp.line);
return bp;
});
this.breakPoints.set(bppath, bps || []);
this.breakPointsChanged.add(bppath);
const actualBreakpoints = (bps || []).map((bp) => { return {line:bp.line, verified:true }; });
// send back the actual breakpoint positions
response.body = {
breakpoints: actualBreakpoints
};
this.sendResponse(response);
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
// runtime supports no threads so just return a default thread.
response.body = {
threads: [
new Thread(FactorioModDebugSession.THREAD_ID, "thread 1")
]
};
this.sendResponse(response);
}
protected async stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments) {
const startFrame = typeof args.startFrame === 'number' ? args.startFrame : 0;
this._responses.set(response.request_seq,response);
this.writeStdin(`__DebugAdapter.stackTrace(${startFrame},false,${response.request_seq})`);
}
private async finishStackTrace(stack:DebugProtocol.StackFrame[], seq:number) {
const response = <DebugProtocol.StackTraceResponse>this._responses.get(seq);
this._responses.delete(seq);
response.body = { stackFrames: (stack||[]).map(
(frame:DebugProtocol.StackFrame&{linedefined:number; currentpc:number}) =>{
if (frame && frame.source)
{
if (frame.source.path)
{
frame.source.path = this.convertDebuggerPathToClient(frame.source.path);
}
const sourceid = frame.source.path ?? frame.source.sourceReference;
if (sourceid) {
const dump = this.dumps.get(sourceid);
if (dump) {
const f = dump.getFunctionAtStartLine(frame.linedefined);
if (f?.baseAddr) {
frame.instructionPointerReference = "0x"+(f.baseAddr + frame.currentpc).toString(16);
}
}
}
}
return frame;
}
) };
this.sendResponse(response);
}
protected async modulesRequest(response: DebugProtocol.ModulesResponse, args: DebugProtocol.ModulesArguments) {
const modules = Array.from(this._modules.values());
response.body = { modules: modules };
this.sendResponse(response);
}
protected async scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments) {
const scopes = new Promise<DebugProtocol.Scope[]>((resolve)=>{
this._scopes.set(args.frameId, resolve);
this.writeStdin(`__DebugAdapter.scopes(${args.frameId})\n`);
});
response.body = { scopes: await scopes };
this.sendResponse(response);
}
protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments, request?: DebugProtocol.Request) {
let consume:resolver<void>;
const consumed = new Promise<void>((resolve)=>consume=resolve);
const cts = new vscode.CancellationTokenSource();
const vars = await Promise.race([
new Promise<DebugProtocol.Variable[]>(async (resolve)=>{
this._vars.set(response.request_seq, resolve);
if (!await this.writeOrQueueStdin(
`__DebugAdapter.variables(${args.variablesReference},${response.request_seq},${args.filter? `"${args.filter}"`:"nil"},${args.start || "nil"},${args.count || "nil"})\n`,
consumed,
cts.token))
{
this._vars.delete(response.request_seq);
consume!();
resolve([
{
name: "",
value: `Expired variablesReference ref=${args.variablesReference} seq=${response.request_seq}`,
type: "error",
variablesReference: 0,
}
]);
}
}),
new Promise<DebugProtocol.Variable[]>((resolve) => {
// just time out if we're in a menu with no lua running to empty the queue...
// in which case it's just expired anyway
setTimeout(()=>{
cts.cancel();
resolve(<DebugProtocol.Variable[]>[
{
name: "",
value: `No Lua State Available ref=${args.variablesReference} seq=${response.request_seq}`,
type: "error",
variablesReference: 0,
}
]);
}, this.launchArgs.runningTimeout ?? 2000);
})
]);
consume!();
vars.forEach((a)=>{
const lsid = a.value.match(/\{LocalisedString ([0-9]+)\}/);
if (lsid)
{
const id = Number.parseInt(lsid[1]);
a.value = this.translations.get(id) ?? `{Missing Translation ID ${id}}`;
}
});
response.body = { variables: vars };
if (vars.length === 1 && vars[0].type === "error")
{
response.success = false;
response.message = vars[0].value;
}
cts.dispose();
this.sendResponse(response);
}
protected async setVariableRequest(response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments, request?: DebugProtocol.Request) {
const body = await new Promise<DebugProtocol.Variable>((resolve)=>{
this._setvars.set(response.request_seq, resolve);
this.writeStdin(`__DebugAdapter.setVariable(${args.variablesReference},${luaBlockQuote(Buffer.from(args.name))},${luaBlockQuote(Buffer.from(args.value))},${response.request_seq})\n`);
});
if (body.type === "error") {
response.success = false;
response.message = body.value;
} else {
response.body = body;
}
this.sendResponse(response);
}
protected async evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments, request?: DebugProtocol.Request) {
let consume:resolver<void>;
const consumed = new Promise<void>((resolve)=>consume=resolve);
const cts = new vscode.CancellationTokenSource();
const body = await Promise.race([
new Promise<EvaluateResponseBody>(async (resolve)=>{
this._evals.set(response.request_seq, resolve);
if (!await this.writeOrQueueStdin(
`__DebugAdapter.evaluate(${args.frameId??"nil"},"${args.context}",${luaBlockQuote(Buffer.from(args.expression.replace(/\n/g," ")))},${response.request_seq})\n`,
consumed,
cts.token))
{
this._evals.delete(response.request_seq);
consume!();
resolve({
result: `Expired evaluate seq=${response.request_seq}`,
type:"error",
variablesReference: 0,
seq: response.request_seq,
});
}
}),
new Promise<EvaluateResponseBody>((resolve) => {
// just time out if we're in a menu with no lua running to empty the queue...
// in which case it's just expired anyway
setTimeout(()=>{
cts.cancel();
resolve(<EvaluateResponseBody>{
result: `No Lua State Available seq=${response.request_seq}`,
type: "error",
variablesReference: 0,
seq: response.request_seq,
});
}, this.launchArgs.runningTimeout ?? 2000);
})
]);
consume!();
if (body.type === "error")
{
response.success = false;
response.message = body.result;
}
response.body = body;
const lsid = body.result.match(/\{LocalisedString ([0-9]+)\}/);
if (lsid)
{
const id = Number.parseInt(lsid[1]);
body.result = this.translations.get(id) ?? `{Missing Translation ID ${id}}`;
}
if (body.timer)
{
const time = this.translations.get(body.timer)?.replace(/^.*: /,"") ??
`{Missing Translation ID ${body.timer}}`;
body.result += "\n⏱️ " + time;
}
cts.dispose();
this.sendResponse(response);
}
protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void {
this.continue();
this.sendResponse(response);
}
protected pauseRequest(response: DebugProtocol.PauseResponse, args: DebugProtocol.PauseArguments, request?: DebugProtocol.Request): void {
this.pauseRequested = true;
this.sendResponse(response);
}
private step(event:'in'|'out'|'over' = 'in', granularity:DebugProtocol.SteppingGranularity = "statement") {
const stepdepth = {
in: -1,
over: 0,
out: 1,
};
if(this.breakPointsChanged.size !== 0)
{
this.updateBreakpoints();
}
this.writeStdin(`__DebugAdapter.step(${stepdepth[event]},${granularity==="instruction"})`);
this.writeStdin("cont");
}
protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
this.step("over", args.granularity);
this.sendResponse(response);
}
protected stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments): void {
this.step("in", args.granularity);
this.sendResponse(response);
}
protected stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments): void {
this.step("out", args.granularity);
this.sendResponse(response);
}
protected setExceptionBreakPointsRequest(response: DebugProtocol.SetExceptionBreakpointsResponse, args: DebugProtocol.SetExceptionBreakpointsArguments, request?: DebugProtocol.Request): void {
this.exceptionFilters.clear();
args.filters.forEach(f=>this.exceptionFilters.add(f));
this.sendResponse(response);
}
private nextdump = 1;
private dumps = new Map<number|string,LuaFunction>();
private loadedSources:(Source&DebugProtocol.Source)[] = [];
protected async loadedSourceEvent(loaded:{ source:Source&DebugProtocol.Source; dump:string }) {
if (loaded.source.path){
loaded.source.path = this.convertDebuggerPathToClient(loaded.source.path);
}
const dumpid = loaded.source.path ?? loaded.source.sourceReference;
const dump = new LuaFunction(new BufferStream(Buffer.from(loaded.dump,"base64")),true);
this.nextdump = dump.rebase(this.nextdump);
this.dumps.set(dumpid,dump);
this.sendEvent(new LoadedSourceEvent("new",loaded.source));
}
protected async disassembleRequest(response: DebugProtocol.DisassembleResponse, args: DebugProtocol.DisassembleArguments, request: DebugProtocol.DisassembleRequest) {
const ref = parseInt(args.memoryReference);
const instrs:DebugProtocol.DisassembledInstruction[] = [];
response.body = { instructions:instrs };
let start = ref + (args.instructionOffset??0);
let len = args.instructionCount;
//fill in invalid instruction at <= 0
while (start < 1) {
instrs.push({
address: "0x"+start.toString(16),
instruction: "<no instruction>",
});
start++;
len--;
}
do {
this.dumps.forEach(f=>{
const ins = f.getInstructionsAtBase(start,len);
if (ins) {
instrs.push(...ins);
len -= ins.length;
start += ins.length;
}
});
} while (len > 0 && start < this.nextdump);
//fill in invalid instruction at >= last loaded
while (len > 0)
{
instrs.push({
address: "0x"+start.toString(16),
instruction: "<no instruction>",
});
len--;
}
// and push next ahead in case more functions get loaded later...
this.nextdump += len;
this.sendResponse(response);
}
protected async loadedSourcesRequest(response: DebugProtocol.LoadedSourcesResponse, args: DebugProtocol.LoadedSourcesArguments, request: DebugProtocol.LoadedSourcesRequest) {
response.body = {sources: this.loadedSources};
this.sendResponse(response);
}
protected async sourceRequest(response: DebugProtocol.SourceResponse, args: DebugProtocol.SourceArguments): Promise<void> {
const ref = args.source?.sourceReference;
if (ref) {
let consume:resolver<void>;
const consumed = new Promise<void>((resolve)=>consume=resolve);
const cts = new vscode.CancellationTokenSource();
const body = await Promise.race([
new Promise<string>(async (resolve)=>{
this._dumps.set(ref, resolve);
if (!await this.writeOrQueueStdin(
`__DebugAdapter.source(${ref})\n`,
consumed,
cts.token))
{
this._dumps.delete(ref);
consume!();
resolve(`Expired source ref=${ref}`);
}
}),
new Promise<string>((resolve) => {
// just time out if we're in a menu with no lua running to empty the queue...
// in which case it's just expired anyway
setTimeout(()=>{
cts.cancel();
resolve(`No Lua State Available ref=${ref} seq=${response.request_seq}`);
}, this.launchArgs.runningTimeout ?? 2000);
})
]);
consume!();
response.body = { content: body };
cts.dispose();
}
this.sendResponse(response);
}
private finishSource(dump:{dump:string|undefined;source:string|undefined;ref:number}) {
let source:string;
if (dump.dump) {
const func = new LuaFunction(new BufferStream(Buffer.from(dump.dump,"base64")),true);
source = func.getDisassembledSingleFunction();
} else if (dump.source) {
source = dump.source;
} else {
return this._dumps.get(dump.ref)?.("Invalid Source ID");
}
const resolver = this._dumps.get(dump.ref);
this._dumps.delete(dump.ref);
return resolver?.(source);
}
private createSource(filePath: string): Source {
return new Source(path.basename(filePath), this.convertDebuggerPathToClient(filePath));
}
public static async runTask(task: vscode.Task) {
const execution = await vscode.tasks.executeTask(task);
return new Promise<void>(resolve => {
const disposable = vscode.tasks.onDidEndTask(e => {
if (e.execution === execution) {
disposable.dispose();
resolve();
}
});
});
}
private updateInfoJson(uri:Uri)
{
try {
let jsonpath = uri.path;
if (os.platform() === "win32" && jsonpath.startsWith("/")) {jsonpath = jsonpath.substr(1);}
const jsonstr = fs.readFileSync(jsonpath, "utf8");
if (jsonstr)
{
const moddata = JSON.parse(jsonstr);
if (moddata)
{
const mp = {
uri: uri.with({path:path.posix.dirname(uri.path)}),
name: moddata.name,
version: moddata.version,
info: moddata
};
this.workspaceModInfo.push(mp);
}
}
} catch (error) {
this.sendEvent(new OutputEvent(`failed to read ${uri} ${error}\n`,"stderr"));
}
}
private createSteamAppID(factorioPath:string)
{
if (fs.existsSync(path.resolve(factorioPath,"../steam_api64.dll")) ||// windows
fs.existsSync(path.resolve(factorioPath,"../libsteam_api.dylib")) ||// mac
fs.existsSync(path.resolve(factorioPath,"../libsteam_api.so"))) // linux
{
this.sendEvent(new OutputEvent("detected steam...\n","stdout"));
const appidPath = path.resolve(factorioPath,"../steam_appid.txt");
try {
if (fs.existsSync(appidPath))
{
this.sendEvent(new OutputEvent(`found ${appidPath}\n`,"stdout"));
}
else
{
fs.writeFileSync(appidPath,"427520");
this.sendEvent(new OutputEvent(`wrote ${appidPath}\n`,"stdout"));
}
} catch (error) {
this.sendEvent(new OutputEvent(`failed to write ${appidPath}: ${error}\n`,"stderr"));
}
}
}
private writeStdin(s:string|Buffer,fromQueue?:boolean):void
{
if (!this.inPrompt)
{
if (this.launchArgs.trace) { this.sendEvent(new OutputEvent(`!! Attempted to writeStdin "${s instanceof Buffer ? `Buffer[${s.length}]` : s}" while not in a prompt\n`, "console")); }
return;
}
if (this.launchArgs.trace) { this.sendEvent(new OutputEvent(`${fromQueue?"<q":"<"} ${s instanceof Buffer ? `Buffer[${s.length}] ${fromQueue?s.toString("utf-8"):""}` : s.replace(/^[\r\n]*/,"").replace(/[\r\n]*$/,"")}\n`, "console")); }
this.factorio.writeStdin(Buffer.concat([s instanceof Buffer ? s : Buffer.from(s),Buffer.from("\n")]));
}
private async writeOrQueueStdin(s:string|Buffer,consumed?:Promise<void>,token?:vscode.CancellationToken):Promise<boolean>
{
if (this.launchArgs.trace) {
this.sendEvent(new OutputEvent(`${this.inPrompt?"<":"q<"} ${s instanceof Buffer ? `Buffer[${s.length}]` : s.replace(/^[\r\n]*/,"").replace(/[\r\n]*$/,"")}\n`,"console"));
}
const b = Buffer.concat([s instanceof Buffer ? s : Buffer.from(s),Buffer.from("\n")]);
if (this.inPrompt)
{
this.factorio.writeStdin(b);
if (consumed) { await consumed; }
return true;
}
else
{
const p = new Promise<boolean>((resolve)=>
this.stdinQueue.push({buffer:b,resolve:resolve,consumed:consumed,token:token}));
return p;
}
}
private async runQueuedStdin()
{
if (this.stdinQueue.length > 0)
{
for await (const b of this.stdinQueue) {
if (b.token?.isCancellationRequested)
{
b.resolve(false);
}
else
{
this.writeStdin(b.buffer,true);
b.resolve(true);
if (b.consumed)
{
await b.consumed;
}
}
}
this.stdinQueue = [];
}
}
private clearQueuedStdin():void
{
if (this.stdinQueue.length > 0)
{
this.stdinQueue.forEach(b=>{
if (this.launchArgs.trace) {
this.sendEvent(new OutputEvent(`x< ${b.buffer.toString("utf-8")}\n`, "console"));
}
b.resolve(false);
});
this.stdinQueue = [];
}
}
public continue(updateAllBreakpoints?:boolean) {
if (!this.inPrompt)
{
if (this.launchArgs.trace) { this.sendEvent(new OutputEvent(`!! Attempted to continue while not in a prompt\n`, "console")); }
return;
}
if(updateAllBreakpoints || this.breakPointsChanged.size !== 0)
{
this.updateBreakpoints(updateAllBreakpoints);
}
this.writeStdin("cont");
this.inPrompt = false;
}
public continueRequire(shouldRequire:boolean,modname:string) {
if (!this.inPrompt)
{
if (this.launchArgs.trace) { this.sendEvent(new OutputEvent(`!! Attempted to continueRequire while not in a prompt\n`, "console")); }
return;
}
if (shouldRequire) {
let hookopts = "";
if (this.launchArgs.hookLog !== undefined)
{
hookopts += `hooklog=${this.launchArgs.hookLog},`;
}
if (this.launchArgs.keepOldLog !== undefined)
{
hookopts += `keepoldlog=${this.launchArgs.keepOldLog},`;
}
if (this.launchArgs.runningBreak !== undefined)
{
hookopts += `runningBreak=${this.launchArgs.runningBreak},`;
}
if (this.launchArgs.checkGlobals !== undefined)
{
hookopts += `checkGlobals=${
Array.isArray(this.launchArgs.checkGlobals)?
this.launchArgs.checkGlobals.includes(modname):
this.launchArgs.checkGlobals},`;
}
this.writeStdin(`__DebugAdapter={${hookopts}}`);
}
this.writeStdin("cont");
this.inPrompt = false;
}
public continueProfile(shouldRequire:boolean) {
if (!this.inPrompt)
{
if (this.launchArgs.trace) { this.sendEvent(new OutputEvent(`!! Attempted to continueProfile while not in a prompt\n`, "console")); }
return;
}
if (shouldRequire) {
let hookopts = "";
if (this.launchArgs.profileSlowStart !== undefined)
{
hookopts += `slowStart=${this.launchArgs.profileSlowStart},`;
}
if (this.launchArgs.profileUpdateRate !== undefined)
{
hookopts += `updateRate=${this.launchArgs.profileUpdateRate},`;
}
if (this.launchArgs.profileLines !== undefined)
{
hookopts += `trackLines=${this.launchArgs.profileLines},`;
}
if (this.launchArgs.profileFuncs !== undefined)
{
hookopts += `trackFuncs=${this.launchArgs.profileFuncs},`;
}
if (this.launchArgs.profileTree !== undefined)
{
hookopts += `trackTree=${this.launchArgs.profileTree},`;
}
this.writeStdin(`__Profiler={${hookopts}}`);
}
this.writeStdin("cont");
this.inPrompt = false;
}
private async trydir(dir:Uri,module:DebugProtocol.Module): Promise<boolean>
{
try
{
const stat = await vscode.workspace.fs.stat(dir);
// eslint-disable-next-line no-bitwise
if (stat.type&vscode.FileType.Directory)
{
const modinfo:ModInfo = JSON.parse(Buffer.from(
await vscode.workspace.fs.readFile(Uri.joinPath(dir,"info.json"))).toString("utf8"));
if (modinfo.name===module.name && semver.eq(modinfo.version,module.version!,{"loose":true}))
{
module.symbolFilePath = dir.toString();
module.symbolStatus = "Loaded Mod Directory";
this.sendEvent(new OutputEvent(`loaded ${module.name} ${module.version} from modspath ${module.symbolFilePath}\n`,"stdout"));
return true;
}
}
}
catch (ex)
{
if ((<vscode.FileSystemError>ex).code !== "FileNotFound")
{
this.sendEvent(new OutputEvent(`failed loading ${module.name} ${module.version} from modspath: ${ex}\n`,"stderr"));
}
return false;
}
return false;
}
private async updateModules(modules: DebugProtocol.Module[]) {
const zipext = vscode.extensions.getExtension("slevesque.vscode-zipexplorer");
if (zipext)
{
await zipext.activate();
await vscode.commands.executeCommand("zipexplorer.clear");
}
for (const module of modules) {
try {
this._modules.set(module.name,module);
if (module.name === "level")
{
// find `level` nowhere
module.symbolStatus = "No Symbols (Level)";
continue;
}
if (module.name === "core" || module.name === "base")
{
// find `core` and `base` in data
module.symbolFilePath = Uri.joinPath(Uri.file(this.launchArgs.dataPath),module.name).toString();
module.symbolStatus = "Loaded Data Directory";
this.sendEvent(new OutputEvent(`loaded ${module.name} from data ${module.symbolFilePath}\n`,"stdout"));
continue;
}
try
{
const wm = this.workspaceModInfo.find(m=>m.name===module.name && semver.eq(m.version,module.version!,{"loose":true}));
if (wm)
{
// find it in workspace
module.symbolFilePath = wm.uri.toString();
module.symbolStatus = "Loaded Workspace Directory";
this.sendEvent(new OutputEvent(`loaded ${module.name} ${module.version} from workspace ${module.symbolFilePath}\n`,"stdout"));
continue;
}
}
catch (ex)
{
if ((<vscode.FileSystemError>ex).code !== "FileNotFound")
{
this.sendEvent(new OutputEvent(`failed loading ${module.name} ${module.version} from workspace: ${ex}\n`,"stderr"));
}
}
if (this.launchArgs.modsPath)
{
// find it in mods dir:
// 1) unversioned folder
let dir = Uri.joinPath(Uri.file(this.launchArgs.modsPath),module.name);
if(await this.trydir(dir,module)){continue;};
// 2) versioned folder
dir = Uri.joinPath(Uri.file(this.launchArgs.modsPath),module.name+"_"+module.version);
if(await this.trydir(dir,module)){continue;};
// 3) versioned zip
if (zipext)
{
const zipuri = Uri.joinPath(Uri.file(this.launchArgs.modsPath),module.name+"_"+module.version+".zip");
let stat:vscode.FileStat|undefined;
try
{
stat = await vscode.workspace.fs.stat(zipuri);
}
catch (ex)
{
if ((<vscode.FileSystemError>ex).code !== "FileNotFound")
{
this.sendEvent(new OutputEvent(`${ex}\n`,"stderr"));
}
}
// eslint-disable-next-line no-bitwise
if (stat && (stat.type&vscode.FileType.File))
{
try
{
// if zip exists, try to mount it
//TODO: can i check if it's already mounted somehow?
//TODO: can i actually read dirname inside? doesn't seem to be registered as an fs handler
await vscode.commands.executeCommand("zipexplorer.exploreZipFile", zipuri);
const zipinside = Uri.joinPath(zipuri,module.name+"_"+module.version).with({scheme: "zip"});
module.symbolFilePath = zipinside.toString();
module.symbolStatus = "Loaded Zip";
this.sendEvent(new OutputEvent(`loaded ${module.name} ${module.version} from mod zip ${zipuri.toString()}\n`,"stdout"));
continue;
}
catch (ex)
{
this.sendEvent(new OutputEvent(`failed loading ${module.name} ${module.version} from mod zip ${zipuri.toString()}: ${ex}\n`,"stderr"));
}
}
}
}
module.symbolStatus = "Unknown";
this.sendEvent(new OutputEvent(`no source found for ${module.name} ${module.version}\n`,"console"));
} catch (ex) {
module.symbolStatus = "Error";
this.sendEvent(new OutputEvent(`failed locating source for ${module.name} ${module.version}: ${ex}\n`,"stderr"));
}
}
//TODO: another event to update it with levelpath for __level__ eventually?
this._modules.forEach((module:Module) =>{
this.sendEvent(new ModuleEvent('new', module));
});
}
updateBreakpoints(updateAll:boolean = false) {
const changes = Array<Buffer>();
this.breakPoints.forEach((breakpoints:DebugProtocol.SourceBreakpoint[], filename:string) => {
if (updateAll || this.breakPointsChanged.has(filename))
{
changes.push(Buffer.concat([
Buffer.from("__DebugAdapter.updateBreakpoints("),
luaBlockQuote(encodeBreakpoints(filename,breakpoints)),
Buffer.from(")\n")
]));
}
});
this.breakPointsChanged.clear();
this.writeStdin(Buffer.concat(changes));
}
private terminate()
{
if (this.profile)
{
this.profile.dispose();
this.profile = undefined;
}
if (this.editorWatcher)
{
this.editorWatcher.dispose();
this.editorWatcher = undefined;
}
this.factorio.kill();
const modsPath = this.launchArgs.modsPath;
if (modsPath) {
const modlistpath = path.resolve(modsPath,"./mod-list.json");
if (fs.existsSync(modlistpath))
{
if(this.launchArgs.manageMod === false)
{
this.sendEvent(new OutputEvent(`automatic management of mods disabled by launch config\n`,"stdout"));
}
else
{
const manager = new ModManager(modsPath);
manager.set("debugadapter",false);
manager.write();
this.sendEvent(new OutputEvent(`debugadapter disabled in mod-list.json\n`,"stdout"));
}
}
}
}
} | the_stack |
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import '../../prefs/prefs.js';
import '../../settings_shared_css.js';
import './privacy_review_clear_on_exit_fragment.js';
import './privacy_review_cookies_fragment.js';
import './privacy_review_history_sync_fragment.js';
import './privacy_review_msbb_fragment.js';
import './privacy_review_welcome_fragment.js';
import './step_indicator.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {I18nMixin, I18nMixinInterface} from 'chrome://resources/js/i18n_mixin.js';
import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {SyncBrowserProxy, SyncBrowserProxyImpl, SyncStatus} from '../../people_page/sync_browser_proxy.js';
import {PrefsMixin, PrefsMixinInterface} from '../../prefs/prefs_mixin.js';
import {routes} from '../../route.js';
import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../../router.js';
import {CookiePrimarySetting} from '../../site_settings/site_settings_prefs_browser_proxy.js';
import {StepIndicatorModel} from './step_indicator.js';
/**
* Steps in the privacy review flow in their order of appearance. The page
* updates from those steps to show the corresponding page content.
*/
enum PrivacyReviewStep {
WELCOME = 'welcome',
MSBB = 'msbb',
CLEAR_ON_EXIT = 'clearOnExit',
HISTORY_SYNC = 'historySync',
COOKIES = 'cookies',
COMPLETION = 'completion',
}
interface PrivacyReviewStepComponents {
headerString?: string;
onForwardNavigation(): void;
onBackNavigation?(): void;
isAvailable(): boolean;
}
const PrivacyReviewBase = RouteObserverMixin(WebUIListenerMixin(
I18nMixin(PrefsMixin(PolymerElement)))) as {
new (): PolymerElement & I18nMixinInterface & WebUIListenerMixinInterface &
RouteObserverMixinInterface & PrefsMixinInterface
};
export class SettingsPrivacyReviewPageElement extends PrivacyReviewBase {
static get is() {
return 'settings-privacy-review-page';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
/**
* Valid privacy review states.
*/
privacyReviewStepEnum_: {
type: Object,
value: PrivacyReviewStep,
},
/**
* The current step in the privacy review flow.
*/
privacyReviewStep_: {
type: String,
value: PrivacyReviewStep.WELCOME,
},
/**
* Used by the 'step-indicator' element to display its dots.
*/
stepIndicatorModel_: {
type: Object,
computed:
'computeStepIndicatorModel_(privacyReviewStep_, prefs.generated.cookie_primary_setting)',
},
};
}
static get observers() {
return [`onPrefChanged_(prefs.generated.cookie_primary_setting)`];
}
private privacyReviewStep_: PrivacyReviewStep;
private stepIndicatorModel_: StepIndicatorModel;
private privacyReviewStepToComponentsMap_:
Map<PrivacyReviewStep, PrivacyReviewStepComponents>;
private syncBrowserProxy_: SyncBrowserProxy =
SyncBrowserProxyImpl.getInstance();
private syncStatus_: SyncStatus;
constructor() {
super();
this.privacyReviewStepToComponentsMap_ =
this.computePrivacyReviewStepToComponentsMap_();
}
ready() {
super.ready();
this.addWebUIListener(
'sync-status-changed',
(syncStatus: SyncStatus) => this.onSyncStatusChange_(syncStatus));
this.syncBrowserProxy_.getSyncStatus().then(
(syncStatus: SyncStatus) => this.onSyncStatusChange_(syncStatus));
}
/** RouteObserverBehavior */
currentRouteChanged(newRoute: Route) {
if (newRoute === routes.PRIVACY_REVIEW) {
this.updateStateFromQueryParameters_();
}
}
/**
* @return the map of privacy review steps to their components.
*/
private computePrivacyReviewStepToComponentsMap_():
Map<PrivacyReviewStep, PrivacyReviewStepComponents> {
return new Map([
[
PrivacyReviewStep.WELCOME,
{
onForwardNavigation: () => {
this.navigateToCard_(PrivacyReviewStep.MSBB);
},
isAvailable: () => this.shouldShowWelcomeCard_(),
},
],
[
PrivacyReviewStep.COMPLETION,
{
onForwardNavigation: () => {
Router.getInstance().navigateToPreviousRoute();
},
isAvailable: () => true,
},
],
[
PrivacyReviewStep.MSBB,
{
headerString: this.i18n('privacyReviewMsbbCardHeader'),
onForwardNavigation: () => {
this.navigateToCard_(PrivacyReviewStep.CLEAR_ON_EXIT);
},
isAvailable: () => true,
},
],
[
PrivacyReviewStep.CLEAR_ON_EXIT,
{
headerString: this.i18n('privacyReviewClearOnExitCardHeader'),
onForwardNavigation: () => {
this.navigateToCard_(PrivacyReviewStep.HISTORY_SYNC);
},
onBackNavigation: () => {
this.navigateToCard_(PrivacyReviewStep.MSBB, true);
},
// TODO(crbug/1215630): Enable the CoE step when it's ready.
isAvailable: () => false,
},
],
[
PrivacyReviewStep.HISTORY_SYNC,
{
headerString: this.i18n('privacyReviewHistorySyncCardHeader'),
onForwardNavigation: () => {
this.navigateToCard_(PrivacyReviewStep.COOKIES);
},
onBackNavigation: () => {
this.navigateToCard_(PrivacyReviewStep.CLEAR_ON_EXIT, true);
},
isAvailable: () => this.isSyncOn_(),
},
],
[
PrivacyReviewStep.COOKIES,
{
headerString: this.i18n('privacyReviewCookiesCardHeader'),
onForwardNavigation: () => {
this.navigateToCard_(PrivacyReviewStep.COMPLETION);
},
onBackNavigation: () => {
this.navigateToCard_(PrivacyReviewStep.HISTORY_SYNC, true);
},
isAvailable: () => this.shouldShowCookiesCard_(),
},
],
]);
}
/** Handler for when the sync state is pushed from the browser. */
private onSyncStatusChange_(syncStatus: SyncStatus) {
this.syncStatus_ = syncStatus;
this.navigateToNextCardIfCurrentCardNoLongerAvailable();
}
/** Update the privacy review state based on changed pref. */
private onPrefChanged_() {
// If this change resulted in the user no longer being in one of the
// available states for the given card, we need to skip it.
this.navigateToNextCardIfCurrentCardNoLongerAvailable();
}
private navigateToNextCardIfCurrentCardNoLongerAvailable() {
if (!this.privacyReviewStepToComponentsMap_.get(this.privacyReviewStep_)!
.isAvailable()) {
// This card is currently shown but is no longer available. Navigate to
// the next card in the flow.
this.privacyReviewStepToComponentsMap_.get(this.privacyReviewStep_)!
.onForwardNavigation();
}
}
/** Sets the privacy review step from the URL parameter. */
private updateStateFromQueryParameters_() {
assert(Router.getInstance().getCurrentRoute() === routes.PRIVACY_REVIEW);
const step = Router.getInstance().getQueryParameters().get('step');
// TODO(crbug/1215630): If the parameter is welcome but the user has opted
// to skip the welcome card in a previous flow, then navigate to the first
// settings card instead
if (Object.values(PrivacyReviewStep).includes(step as PrivacyReviewStep)) {
this.privacyReviewStep_ = step as PrivacyReviewStep;
} else {
// If no step has been specified, then navigate to the welcome step.
this.navigateToCard_(PrivacyReviewStep.WELCOME);
}
}
private navigateToCard_(
step: PrivacyReviewStep, isBackwardNavigation?: boolean) {
const nextState = this.privacyReviewStepToComponentsMap_.get(step)!;
if (!nextState.isAvailable()) {
// This card is currently not available. Navigate to the next one, or
// the previous one if this was a back navigation.
if (isBackwardNavigation) {
if (nextState.onBackNavigation) {
nextState.onBackNavigation();
}
} else {
nextState.onForwardNavigation();
}
} else {
Router.getInstance().updateRouteParams(
new URLSearchParams('step=' + step));
// TODO(crbug/1215630): Programmatically put the focus to the
// corresponding element.
}
}
private onNextButtonClick_() {
this.privacyReviewStepToComponentsMap_.get(this.privacyReviewStep_)!
.onForwardNavigation();
}
private computeBackButtonClass_(): string {
return 'cr-button' +
(this.privacyReviewStepToComponentsMap_.get(this.privacyReviewStep_)!
.onBackNavigation === undefined ?
' visibility-hidden' :
'');
}
private onBackButtonClick_() {
this.privacyReviewStepToComponentsMap_.get(this.privacyReviewStep_)!
.onBackNavigation!();
}
private computeStepIndicatorModel_(): StepIndicatorModel {
let stepCount = 0;
let activeIndex = 0;
for (const step of Object.values(PrivacyReviewStep)) {
if (step === PrivacyReviewStep.WELCOME) {
// This card has no step in the step indicator.
continue;
}
if (this.privacyReviewStepToComponentsMap_.get(step)!.isAvailable()) {
if (step === this.privacyReviewStep_) {
activeIndex = stepCount;
}
++stepCount;
}
}
return {
active: activeIndex,
total: stepCount,
};
}
private computeHeaderString_(): string|undefined {
return this.privacyReviewStepToComponentsMap_.get(this.privacyReviewStep_)!
.headerString;
}
private isSyncOn_(): boolean {
return !!this.syncStatus_ && !!this.syncStatus_.signedIn &&
!this.syncStatus_.hasError;
}
private shouldShowWelcomeCard_(): boolean {
return this.getPref('privacy_review.show_welcome_card').value;
}
private shouldShowCookiesCard_(): boolean {
const currentCookieSetting =
this.getPref('generated.cookie_primary_setting').value;
return currentCookieSetting === CookiePrimarySetting.BLOCK_THIRD_PARTY ||
currentCookieSetting ===
CookiePrimarySetting.BLOCK_THIRD_PARTY_INCOGNITO;
}
private showHeader_(): boolean {
return !!this.computeHeaderString_();
}
private showFragment_(step: PrivacyReviewStep): boolean {
return this.privacyReviewStep_ === step;
}
private showAnySettingFragment_(): boolean {
return this.privacyReviewStep_ !== PrivacyReviewStep.WELCOME &&
this.privacyReviewStep_ !== PrivacyReviewStep.COMPLETION;
}
}
customElements.define(
SettingsPrivacyReviewPageElement.is, SettingsPrivacyReviewPageElement); | the_stack |
import { XarcOptions } from "../config/opt2/xarc-options";
import { getDevAdminPortFromEnv } from "./utils";
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable object-shorthand, max-statements, no-magic-numbers */
/* eslint-disable no-console, no-process-exit, global-require, no-param-reassign */
import Fs from "fs";
import Path from "path";
import assert from "assert";
import requireAt from "require-at";
import { makeOptionalRequire } from "optional-require";
import xrun from "@xarc/run";
import { getDevOptions } from "../config/archetype";
import ck from "chalker";
import * as xaa from "xaa"; // really import ESM into single xaa var
import { psChildren } from "ps-get";
import chokidar from "chokidar";
import { spawn } from "child_process";
import scanDir from "filter-scan-dir";
import _ from "lodash";
import xsh from "xsh";
import { logger } from "./logger";
import { createGitIgnoreDir } from "./utils";
import { jestTestDirectories } from "./tasks/constants";
import { eslintTasks } from "./tasks/eslint";
import { updateAppDep } from "./tasks/package-json";
const { getWebpackStartConfig, setWebpackProfile } = require("@xarc/webpack/lib/util/custom-check");
const optionalRequire = makeOptionalRequire(require);
export {
/** The task runner @xarc/run */
xrun,
/** The task runner @xarc/run */
xrun as xclap,
};
let xarcCwd: string;
/**
* Get the webpack's CLI command from @xarc/webpack
*
* @returns webpack's CLI command
*/
function webpackCmd() {
const cmd = "xarc-webpack-cli";
// This command comes from my dependency @xarc/webpack, so the package manager should either
// installed it in my node_modules /.bin or hoisted it to the top level node_modules/.bin
const exactCmd = Path.join(__dirname, "..", "node_modules", ".bin", cmd);
return Fs.existsSync(exactCmd) ? Path.relative(xarcCwd, exactCmd) : cmd;
}
/**
* @param str
*/
function quote(str) {
return str.startsWith(`"`) ? str : `"${str}"`;
}
/**
*
*/
function setProductionEnv() {
process.env.NODE_ENV = "production";
}
/**
*
*/
function setDevelopmentEnv() {
process.env.NODE_ENV = "development";
}
/**
*
*/
function setKarmaCovEnv() {
process.env.ENABLE_KARMA_COV = "true";
}
/**
*
*/
function setStaticFilesEnv() {
process.env.STATIC_FILES = "true";
}
/**
*
*/
function setWebpackDev() {
process.env.WEBPACK_DEV = "true";
}
export { XarcOptions } from "../config/opt2/xarc-options";
/**
* Get the dev task runner (@xarc/run) from Electrode module's perspective.
*
* @param cwd - current working dir for your app - default to `process.cwd()`
*
* @returns the instance of @xarc/run that's required
*/
export const getDevTaskRunner = (cwd: string = process.cwd()) => {
return requireAt(cwd)("@xarc/run") || xrun;
};
/**
* Load xarc development tasks that can be invoked using @xarc/run
*
* You can override any of the tasks here by loading your own using the same
* name with a different namespace (ie: "user").
*
* **For example:**
*
* ```js
* import { getDevTaskRunner, loadXarcDevTasks } from "@xarc/app-dev/lib/dev-tasks"
*
* const xrun = getDevTaskRunner();
*
* xrun.load("user", {
* check: xrun.exec("echo my custom check task")
* });
*
* loadXarcDevTasks();
* ```
*
* @param userXrun - `@xarc/run` task runner. pass `null` and an
* internal version will be used.
* @param userOptions user provided options to configure features etc
*
* @returns The `@xarc/run` task runner instance that was used.
*/
export function loadXarcDevTasks(userXrun?: any, userOptions: XarcOptions = {}) {
let xarcOptions = getDevOptions(userOptions);
xarcCwd = xarcOptions.cwd;
/**
*
*/
function setupPath() {
const nmBin = Path.join("node_modules", ".bin");
xsh.envPath.addToFront(Path.resolve(xarcCwd, nmBin));
xsh.envPath.addToFront(Path.join(xarcOptions.devDir, nmBin));
}
setupPath();
const mergeIsomorphicAssets = require(`../scripts/merge-isomorphic-assets.js`);
const flattenMessagesL10n = require(`../scripts/l10n/flatten-messages.js`);
const mapIsomorphicCdn = require(`../scripts/map-isomorphic-cdn.js`);
const config = xarcOptions.config;
const karmaConfig = (file) => Path.join(config.karma, file);
const mochaConfig = (file) => Path.join(config.mocha, file);
const shell = xsh.$;
const exec = xsh.exec;
const mkCmd = xsh.mkCmd;
const penthouse = optionalRequire("penthouse");
const CleanCSS = optionalRequire("clean-css");
const watchExec = (files: string | string[], cmd) => {
let timer;
let child;
const defer = xaa.makeDefer();
const doExec = () => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(async () => {
timer = undefined;
const run = (msg) => {
child = true;
console.log(`${msg} '${cmd}'`);
const ch = spawn(cmd, {
shell: true,
stdio: "inherit",
});
ch.on("close", () => {
if (child === "restart") {
run("Restarting");
} else {
defer.resolve();
}
});
child = ch;
};
if (!child) {
run("Running");
} else if (child.kill && child.pid) {
const ch = child;
child = "restart";
(await psChildren(ch.pid)).reverse().forEach((c) => process.kill(c.pid));
ch.kill();
}
}, 500);
};
const watcher = chokidar.watch([].concat(files));
watcher.on("change", doExec);
doExec();
return defer.promise;
};
// By default, the dev proxy server will be hosted from PORT (3000)
// and the app from APP_SERVER_PORT.
// If the APP_SERVER_PORT is set to the empty string however,
// leave it empty and therefore disable the dev proxy server.
xrun.updateEnv({ APP_SERVER_PORT: "0", WEBPACK_DEV_PORT: "0" }, { override: false });
const eTmpDir = xarcOptions.eTmpDir;
/**
*
*/
function removeLogFiles() {
try {
Fs.unlinkSync(Path.resolve(xarcCwd, "archetype-exceptions.log"));
} catch (e) {} // eslint-disable-line
try {
Fs.unlinkSync(Path.resolve(xarcCwd, "archetype-debug.log"));
} catch (e) {} // eslint-disable-line
}
/*
* [generateServiceWorker clap task to generate service worker code that will precache specific
* resources so they work offline.]
*
*/
/**
*
*/
function generateServiceWorker() {
const NODE_ENV = process.env.NODE_ENV;
const serviceWorkerExists = Fs.existsSync("./service-worker.js");
const serviceWorkerConfigExists = Fs.existsSync("config/sw-precache-config.json");
/**
* Determines whether the fetch event handler is included in the generated service worker code,
* by default value is set to true for development builds set the value to false
*
* https://github.com/GoogleChrome/sw-precache#handlefetch-boolean
*
*/
const cacheRequestFetch = NODE_ENV !== "production" ? "--no-handle-fetch" : "";
if (serviceWorkerConfigExists) {
// generate-service-worker
return exec(
`sw-precache --config=config/sw-precache-config.json --verbose ${cacheRequestFetch}`
);
} else if (serviceWorkerExists && !serviceWorkerConfigExists) {
// this is the case when service-worker exists from the previous build but service-worker-config
// does not exist/deleted on purpose for future builds
return shell.rm("-rf", "./service-worker.js");
} else {
// default case
return false;
}
}
/**
*
*/
function inlineCriticalCSS() {
const HOST = process.env.HOST || "localhost";
const PORT = process.env.PORT || 3000;
const PATH = process.env.CRITICAL_PATH || "/";
const url = `http://${HOST}:${PORT}${PATH}`;
const statsPath = Path.resolve(xarcCwd, "dist/server/stats.json");
const stats = JSON.parse(Fs.readFileSync(statsPath, "utf-8"));
const cssAsset = stats.assets.find((asset) => asset.name.endsWith(".css"));
const cssAssetPath = Path.resolve(xarcCwd, `dist/js/${cssAsset.name}`);
const targetPath = Path.resolve(xarcCwd, "dist/js/critical.css");
const serverPromise = require(Path.resolve(
xarcCwd,
`${xarcOptions.AppMode.src.server}/index.js`
))();
const penthouseOptions = {
url,
css: cssAssetPath,
width: 1440,
height: 900,
timeout: 30000,
strict: false,
maxEmbeddedBase64Length: 1000,
renderWaitTime: 2000,
blockJSRequests: false,
};
serverPromise.then(() => {
penthouse(penthouseOptions, (err, css) => {
if (err) {
throw err;
}
const minifiedCSS = new CleanCSS().minify(css).styles;
Fs.writeFile(targetPath, minifiedCSS, (writeErr) => {
if (writeErr) {
throw writeErr;
}
process.exit(0);
});
});
});
}
/**
* @param argFlags
*/
function startAppServer(argFlags = []) {
argFlags = argFlags || [];
const x = argFlags.length > 0 ? ` with options: ${argFlags.join(" ")}` : "";
logger.info(`Starting app server${x}`);
logger.info("To terminate press Ctrl+C.");
xarcOptions.AppMode.setEnv(xarcOptions.AppMode.lib.dir);
return exec(`node`, argFlags, Path.join(xarcOptions.AppMode.lib.server, "index.js"));
}
/**
*
*/
function generateBrowsersListRc() {
const configRcFile = ".browserslistrc";
const destRcFile = Path.resolve(xarcCwd, configRcFile);
if (Fs.existsSync(destRcFile)) {
return;
}
// generate the config
Fs.writeFileSync(
destRcFile,
`# Browsers that we support
last 2 versions
ie >= 11
> 5%
`
);
logger.info(`Generating ${configRcFile} for you - please commit it.`);
}
updateAppDep(xarcCwd);
/*
*
* For information on how to specify a task, see:
*
* https://www.npmjs.com/package/`@xarc/run`
*
*/
// quick tips name naming and invoking tasks:
// - task name without . or - are primary tasks
// - task name starts with . are hidden in help output
// - when invoking tasks in [], starting name with ? means optional (ie: won't fail if task not found)
// eslint-disable-next-line complexity
/**
* @param xrun2
*/
function makeTasks(xrun2) {
process.env.ENABLE_KARMA_COV = "false";
const checkFrontendCov = (minimum = "5") => {
if (typeof minimum !== "string") {
minimum = "5";
}
return exec(
`nyc check-coverage --temp-dir "coverage/client" --branches ${minimum} --lines ${minimum} --functions ${minimum} --statements ${minimum} --per-file`
);
};
const optimizeModuleForProd = (module) => {
const modulePath = Path.resolve(xarcCwd, "node_modules", module);
assert(shell.test("-d", modulePath), `${modulePath} is not a directory`);
createGitIgnoreDir(
Path.resolve(xarcCwd, xarcOptions.prodModulesDir),
"Electrode production modules dir"
);
const prodPath = Path.join(xarcOptions.prodModulesDir, module);
const cmd = mkCmd(
`babel -q ${quote(modulePath)} --no-babelrc --ignore dist -D`,
`--plugins transform-node-env-inline,minify-dead-code-elimination`,
`-d ${quote(prodPath)}`
);
return exec(cmd).then(() => {
const dist = Path.join(modulePath, "dist");
if (Fs.existsSync(dist)) {
shell.cp("-rf", dist, prodPath);
}
});
};
const makeBabelConfig = (destDir, _rcFile, resultFile = "babel.config.js") => {
destDir = Path.resolve(xarcCwd, destDir);
const files = [".babelrc.js", resultFile];
if (
!Fs.existsSync(destDir) ||
files.find((file) => Fs.existsSync(Path.join(destDir, file)))
) {
return;
}
const newName = Path.join(destDir, resultFile);
console.log(ck`<orange>Generating <cyan>${newName}</> for you - please commit it.</>`);
Fs.writeFileSync(
newName,
// NOTE: do not change module.exports below, this is .js file for app
`"use strict";
const { babelPresetFile } = require("@xarc/app-dev");
module.exports = {
presets: [babelPresetFile]
};
`
);
};
const AppMode = xarcOptions.AppMode;
const babelCliIgnore = quote(
[...jestTestDirectories.map((dir) => `**/${dir}`), `**/*.spec.js`, `**/*.spec.jsx`]
.concat(xarcOptions.babel.enableTypeScript && [`**/*.test.ts`, `**/*.test.tsx`])
.concat(`**/.__dev_hmr`)
.filter((x) => x)
.join(",")
);
const babelCliExtensions = quote(
[".js", ".jsx"]
.concat(xarcOptions.babel.enableTypeScript && [".ts", ".tsx"])
.filter((x) => x)
.join(",")
);
const babelEnvTargetsArr = Object.keys(xarcOptions.babel.envTargets).filter(
(k) => k !== "node"
);
const buildDistDirs = babelEnvTargetsArr
.filter((name) => name !== "default")
.map((name) => `dist-${name}`);
let tasks = {
".mk-prod-dir": () =>
createGitIgnoreDir(Path.resolve(xarcCwd, xarcOptions.prodDir), "Electrode production dir"),
".mk-dist-dir": () => createGitIgnoreDir(Path.resolve(xarcCwd, "dist"), "Electrode dist dir"),
".mk-dll-dir": () => createGitIgnoreDir(Path.resolve(xarcCwd, "dll"), "Electrode dll dir"),
".production-env": () => {
setProductionEnv();
xarcOptions = getDevOptions(userOptions); // re-evaluate options
},
".development-env": () => {
setDevelopmentEnv();
xarcOptions = getDevOptions(userOptions); // re-evaluate options
},
".webpack-dev": () => {
setWebpackDev();
xarcOptions = getDevOptions(userOptions); // re-evaluate options
},
".static-files-env": () => setStaticFilesEnv(),
".remove-log-files": () => removeLogFiles(),
build: {
dep: [".remove-log-files", ".production-env"],
desc: `Build your app's ${AppMode.src.dir} directory into ${AppMode.lib.dir} for production`,
task: [".build-lib", "build-dist", ".check.top.level.babelrc", "mv-to-dist"],
},
//
// browser coverage
//
".build-browser-coverage-1": () => {
setProductionEnv();
setWebpackProfile("browsercoverage");
return exec(
`${webpackCmd()}`,
`--config`,
quote(getWebpackStartConfig("webpack.config.browsercoverage.js")),
`--color`
);
},
"build-browser-coverage": {
desc: "Build browser coverage",
task: [
".clean.dist",
".build-browser-coverage-1",
"build-dist:flatten-l10n",
"build-dist:clean-tmp",
],
},
"build-dev-static": {
desc: "Build static copy of your app's client bundle for development",
task: [".clean.dist", "build-dist-dev-static"],
},
"build-dist": [
".production-env",
".clean.build",
".mk-dist-dir",
".copy-xarc-options-to-dist",
"build-dist-dll",
"build-dist-min",
"build-dist:flatten-l10n",
"build-dist:merge-isomorphic-assets",
"copy-dll",
"build-dist:clean-tmp",
],
".copy-xarc-options-to-dist": () => shell.cp(Path.join(eTmpDir, "xarc-options.json"), "dist"),
"mv-to-dist": ["mv-to-dist:clean", "mv-to-dist:mv-dirs", "mv-to-dist:keep-targets"],
"build-dist-dev-static": {
desc: false,
task: function () {
setWebpackProfile("static");
return mkCmd(
`~$${webpackCmd()} --config`,
quote(getWebpackStartConfig("webpack.config.dev.static.js")),
`--color`
);
},
},
".ss-prod-react": () => optimizeModuleForProd("react"),
".ss-prod-react-dom": () => optimizeModuleForProd("react-dom"),
".ss-clean.prod-react": () => {
shell.rm(
"-rf",
Path.join(xarcOptions.prodModulesDir, "react"),
Path.join(xarcOptions.prodModulesDir, "react-dom")
);
},
"ss-prod-react": {
desc: `Make optimized copy of react&react-dom for server side in dir ${xarcOptions.prodModulesDir}`,
dep: [".ss-clean.prod-react", ".mk-prod-dir"],
task: xrun2.concurrent(".ss-prod-react", ".ss-prod-react-dom"),
},
"build-dist-dll": () => undefined,
"copy-dll": () => undefined,
"build-dist-min": {
dep: [".production-env", () => setWebpackProfile("production")],
desc: "build dist for production",
task: xrun2.concurrent(
babelEnvTargetsArr.map((name, index) =>
xrun2.exec(
[
`${webpackCmd()} --config`,
quote(getWebpackStartConfig("webpack.config.js")),
`--color`,
],
{
xclap: {
delayRunMs: index * 2000,
},
execOptions: {
env: {
ENV_TARGET: name,
},
},
}
)
)
),
},
"mv-to-dist:clean": {
desc: `clean static resources within ${buildDistDirs}`,
task: () => {
buildDistDirs.forEach((dir) => {
// clean static resources within `dist-X` built by user specified env targets
// and leave [.js, .map, .json] files only
const removedFiles = scanDir.sync({
dir: Path.resolve(xarcCwd, dir),
includeRoot: true,
ignoreExt: [".js", ".map", ".json"],
});
shell.rm("-rf", ...removedFiles);
});
return;
},
},
"mv-to-dist:mv-dirs": {
desc: `move ${buildDistDirs} to dist`,
task: () => {
buildDistDirs.forEach((dir) => {
scanDir
.sync({
dir,
includeRoot: true,
filterExt: [".js", ".json", ".map"],
// the regex above matches all the sw-registration.js, sw-registration.js.map,
// main.bundle.js and main.bundle.js.map and stats.json
})
.forEach((file) => {
if (file.endsWith(".js")) {
shell.cp("-r", file, "dist/js");
} else if (file.endsWith(".map")) {
shell.cp("-r", file, "dist/map");
} else {
shell.cp("-r", file, `dist/server/${dir.split("-")[1]}-${Path.basename(file)}`);
}
});
});
return;
},
},
"mv-to-dist:keep-targets": {
desc: `write each targets to respective isomorphic-assets.json`,
task: () => {
buildDistDirs.forEach((dir) => {
// add `targets` field to `dist-X/isomorphic-assets.json`
const isomorphicPath = Path.resolve(xarcCwd, dir, "isomorphic-assets.json");
if (Fs.existsSync(isomorphicPath)) {
Fs.readFile(
isomorphicPath,
{
encoding: "utf8",
},
(err, data) => {
if (err) throw err;
const assetsJson = JSON.parse(data);
const { envTargets } = xarcOptions.babel;
assetsJson.targets = envTargets[dir.split("-")[1]];
// eslint-disable-next-line no-shadow
Fs.writeFile(isomorphicPath, JSON.stringify(assetsJson, null, 2), (err) => {
if (err) throw err;
});
}
);
}
});
return;
},
},
"build-dist:clean-tmp": {
desc: false,
task: () => shell.rm("-rf", "./tmp"),
},
"build-dist:flatten-l10n": flattenMessagesL10n,
"build-dist:merge-isomorphic-assets": mergeIsomorphicAssets,
".build-lib": () => undefined,
".check.top.level.babelrc": () => {
if (xarcOptions.checkUserBabelRc() !== false) {
logger.error(`
You are using src for client & server, archetype will ignore your top level .babelrc
Please remove your top level .babelrc file if you have no other use of it.
Individual .babelrc files were generated for you in src/client and src/server
`);
}
},
".clean.lib:client": () => shell.rm("-rf", AppMode.lib.client),
".mk.lib.client.dir": () => {
createGitIgnoreDir(
Path.resolve(xarcCwd, AppMode.lib.client),
`Electrode app transpiled code from ${AppMode.src.client}`
);
},
".build.babelrc": () => {
makeBabelConfig(xarcCwd, "babelrc.js");
},
".build-lib:delete-babel-ignored-files": {
desc: false,
task: () => {
const scanned = scanDir.sync({
dir: Path.resolve(xarcCwd, AppMode.lib.dir),
includeRoot: true,
includeDir: true,
grouping: true,
filterDir: (x) => (x === `.__dev_hmr` && "dirs") || "otherDirs",
filter: (x, p) =>
x.indexOf(".spec.") > 0 || x.indexOf(".test.") > 0 || p === `.__dev_hmr`,
});
scanned.files.forEach((f) => {
try {
Fs.unlinkSync(f);
} catch (err) {
//
}
});
[].concat(scanned.dirs, scanned.otherDirs).forEach((d) => {
try {
if (d) Fs.rmdirSync(d);
} catch (err) {
// ignore
}
});
},
},
"build-lib:all": {
desc: false,
dep: [
".clean.lib:client",
".clean.lib:server",
".mk.lib.client.dir",
".mk.lib.server.dir",
".build.babelrc",
],
task: xrun2.exec(
[
`babel ${AppMode.src.dir}`,
`--out-dir=${AppMode.lib.dir}`,
`--extensions=${babelCliExtensions}`,
`--source-maps=inline --copy-files`,
`--verbose --ignore=${babelCliIgnore}`,
],
{
env: {
XARC_BABEL_TARGET: "node",
},
}
),
finally: [".build-lib:delete-babel-ignored-files"],
},
// TODO: to be removed
"build-lib:client": {
desc: false,
dep: [".clean.lib:client", ".mk.lib.client.dir"],
task: () => {
const dirs = AppMode.hasSubApps
? []
.concat(
scanDir.sync({
dir: AppMode.src.dir,
includeDir: true,
grouping: true,
filterDir: (x) => !x.startsWith("server") && "dirs",
filter: () => false,
}).dirs
)
.filter((x) => x)
: [AppMode.client];
return dirs.map((x) =>
mkCmd(
`~$babel ${Path.posix.join(AppMode.src.dir, x)}`,
`--out-dir=${Path.posix.join(AppMode.lib.dir, x)}`,
`--extensions=${babelCliExtensions}`,
`--source-maps=inline --copy-files`,
`--verbose --ignore=${babelCliIgnore}`
)
);
},
finally: [".build-lib:delete-babel-ignored-files"],
},
".clean.lib:server": () => shell.rm("-rf", AppMode.lib.server),
".mk.lib.server.dir": () => {
createGitIgnoreDir(
Path.resolve(xarcCwd, AppMode.lib.server),
`Electrode app transpiled code from ${AppMode.src.server}`
);
},
// TODO: to be removed
"build-lib:server": {
desc: false,
dep: [".clean.lib:server", ".mk.lib.server.dir"],
task: [
mkCmd(
`~$babel ${AppMode.src.server} --out-dir=${AppMode.lib.server}`,
`--extensions=${babelCliExtensions}`,
`--source-maps=inline --copy-files`,
`--ignore=${babelCliIgnore}`
),
".build-lib:delete-babel-ignored-files",
],
},
check: ["lint", "test-cov"],
"check-ci": ["lint", "test-ci"],
"check-cov": ["lint", "test-cov"],
"check-dev": ["lint", "test-dev"],
clean: [".clean.dist", ".clean.lib", ".clean.prod", ".clean.etmp", ".clean.dll"],
".clean.dist": () => shell.rm("-rf", "dist", ...buildDistDirs),
".clean.lib": () => undefined, // to be updated below for src mode
".clean.prod": () => shell.rm("-rf", xarcOptions.prodDir),
".clean.etmp": () => shell.rm("-rf", eTmpDir),
".clean.dll": () => shell.rm("-rf", "dll"),
".clean.build": [".clean.dist", ".clean.dll"],
"cov-frontend": () => checkFrontendCov(),
"cov-frontend-50": () => checkFrontendCov("50"),
"cov-frontend-70": () => checkFrontendCov("70"),
"cov-frontend-85": () => checkFrontendCov("85"),
"cov-frontend-95": () => checkFrontendCov("95"),
debug: ["build-dev-static", "server-debug"],
devbrk: ["dev --inspect-brk"],
"mock-cloud": {
desc: `Run app locally like it's deployed to cloud with CDN mock and HTTPS proxy.
- You must run clap build first and set env vars like HOST, PORT yourself.
- NODE_ENV is set to 'production' if it's not set.
- options: [all options will be passed to node when starting your app server]`,
task(context) {
userXrun.updateEnv({ NODE_ENV: "production" }, { override: false });
if (process.env.APP_SERVER_PORT === "0") {
console.log("mock-cloud need to explicitly set APP_SERVER_PORT, changing 0 to 3100");
process.env.APP_SERVER_PORT = "3100";
}
const mockTask = xrun2.concurrent([
"dev-proxy --mock-cdn --no-dev",
xrun2.serial(
() => xaa.delay(500),
() =>
watchExec(
["config/assets.json", "lib/server"],
`node ${context.args.join(" ")} lib/server`
)
),
]);
if (!Fs.existsSync("dist")) {
console.log("dist does not exist, running build task first.");
return xrun2.serial(
"build",
() => console.log("build completed, starting mock prod mode with proxy"),
mockTask
);
}
return xrun2.serial(() => console.log("dist exist, skipping build task"), mockTask);
},
},
"setup-dev": {
desc: `Setup development related options for your application. \
You only need to run this if you are doing something not through the xarc tasks.`,
dep: [".webpack-dev", ".development-env"],
task() {
console.log(`xarc dev options configured.`);
},
},
dev: {
desc: `Start your app with watch in development mode with dev-admin.
options: node.js --inspect can be used to debug the dev-admin`,
dep: [".remove-log-files", ".development-env", ".build.babelrc"],
task() {
const args = this.args.join(" ");
return [".webpack-dev", [`server-admin ${args}`, "generate-service-worker"]];
},
},
hot: {
desc: "Start app dev with hot reload enabled",
task: () => {
xarcOptions.webpack.enableHotModuleReload = true;
return "dev";
},
},
"dev-static": {
desc: "Start server in development mode with statically built files",
task: ["build-dev-static", "app-server"],
},
"npm:test": ["check"],
"npm:release": mapIsomorphicCdn,
server: ["app-server"], // keep old server name for backward compat
"app-server": {
desc: "Start the app server only. Must run 'clap build' first.",
task: () => startAppServer(),
},
"server-debug": {
desc: "Start the app serve with 'node debug'",
task: () => startAppServer(["debug"]),
},
"server-build-debug": {
desc: "Build and debug with devTools",
task: ["build", "server-devtools"],
},
"server-build-debug-brk": {
desc: "Build and debug with devTools with breakpoint starting the app",
task: ["build", "server-devtools-debug-brk"],
},
"server-devtools": {
desc: "Debug the app server with 'node --inspect'",
task: () => startAppServer(["--inspect"]),
},
"server-devtools-debug-brk": {
desc: "Debug the app server with 'node --inspect --debug-brk'",
task: () => startAppServer(["--inspect", "--debug-brk"]),
},
"server-prod": {
dep: [".production-env", ".static-files-env"],
desc:
"Start server in production mode with static files routes. Must run 'clap build' first.",
task: () => startAppServer(),
},
".init-bundle.valid.log": () =>
Fs.writeFileSync(Path.resolve(xarcCwd, eTmpDir, "bundle.valid.log"), `${Date.now()}`),
"server-admin": {
desc: "Start development with admin server",
task(context) {
setWebpackProfile("development");
AppMode.setEnv(AppMode.src.dir);
// eslint-disable-next-line no-shadow
const exec = quote(Path.join(xarcOptions.devDir, "lib/babel-run"));
const isNodeArgs = (x) => x.startsWith("--inspect");
const nodeArgs = context.args.filter(isNodeArgs).join(" ");
const otherArgs = context.args.filter((x) => !isNodeArgs(x)).join(" ");
// get user specified port for admin
const userPort = getDevAdminPortFromEnv(xarcOptions.adminPort);
const portArg = !otherArgs.includes("--port") && userPort ? `--port ${userPort}` : "";
return mkCmd(
`~(tty)$node`,
nodeArgs,
quote(Path.join(xarcOptions.devDir, "lib/dev-admin")),
otherArgs,
portArg,
`--exec ${exec} --ext js,jsx,json,yaml,log,ts,tsx`,
`--watch config ${AppMode.src.server}`,
`-- ${AppMode.src.server}`
);
},
},
"server-admin.test": {
desc: "Start development with admin server in test mode",
task(context) {
setWebpackProfile("test");
AppMode.setEnv(AppMode.src.dir);
// eslint-disable-next-line no-shadow
const exec = quote(Path.join(xarcOptions.devDir, "lib/babel-run"));
const isNodeArgs = (x) => x.startsWith("--inspect");
const nodeArgs = context.args.filter(isNodeArgs);
const otherArgs = context.args.filter((x) => !isNodeArgs(x));
return mkCmd(
`~(tty)$node`,
nodeArgs.join(" "),
quote(Path.join(xarcOptions.devDir, "lib/dev-admin")),
otherArgs.join(" "),
`--exec ${exec} --ext js,jsx,json,yaml,log,ts,tsx`,
`--watch config ${AppMode.src.server}`,
`-- ${AppMode.src.server}`
);
},
},
"dev-proxy": {
desc: `Start Electrode dev reverse proxy by itself - useful for running it with sudo.
options: --debug --mock-cdn`,
task(context) {
const debug = context.argOpts.debug ? "--inspect-brk " : "";
const proxySpawn = require.resolve("@xarc/app-dev/lib/dev-admin/redbird-spawn");
return `~(tty)$node ${debug}${proxySpawn} ${context.args.join(" ")}`;
},
},
"test-server": xrun2.concurrent(["lint-server", "lint-server-test"], "test-server-cov"),
"test-watch-all": xrun2.concurrent("server-admin.test", "test-frontend-dev-watch"),
"test-ci": ["test-frontend-ci"],
"test-cov": [
"?.karma.test-frontend-cov",
"?.jest.test-frontend-cov",
"test-server-cov",
].filter((x) => x),
"test-dev": ["test-frontend-dev", "test-server-dev"],
"test-watch": ["test-watch-all"],
"test-frontend": ["?.karma.test-frontend"],
"test-frontend-ci": ["?.karma.test-frontend-ci"],
"test-frontend-dev": ["?.karma.test-frontend-dev"],
"test-frontend-dev-watch": ["?.karma.test-frontend-dev-watch"],
"critical-css": {
desc: "Start server and run penthouse to output critical CSS",
task: () => {
if (penthouse && CleanCSS) {
inlineCriticalCSS();
} else {
const error =
"Please ensure `options.criticalCSS = true` in your `archetype/config.js` or `archetype/config/index.js`, then reinstall your dependencies";
throw new Error(`Missing Dependencies\n${error}`);
}
},
},
"generate-service-worker": {
desc:
"Generate Service Worker using the options provided in the app/config/sw-precache-config.json " +
"file for prod/dev mode",
task: () => generateServiceWorker(),
},
pwa: {
desc:
"PWA must have dist by running `clap build` first and then start the app server only.",
task: ["build", "server"],
},
"generate-browsers-listrc": {
desc:
"Generate .browserlistrc config file, it's used by Browserlist for AutoPrefixer/PostCSS",
task: () => generateBrowsersListRc(),
},
};
tasks = Object.assign(tasks, {
".clean.lib": () =>
shell.rm("-rf", AppMode.lib.client, AppMode.lib.server, AppMode.savedFile),
".build-lib:app-mode": () =>
Fs.writeFileSync(
Path.resolve(xarcCwd, AppMode.savedFile),
JSON.stringify(AppMode, null, 2)
),
".build-lib": {
desc: false,
dep: [".clean.lib", ".mk-prod-dir"],
task: ["build-lib:all", ".build-lib:app-mode"],
},
});
if (Fs.existsSync(Path.resolve(xarcCwd, AppMode.src.client, "dll.config.js"))) {
Object.assign(tasks, {
"build-dist-dll": {
dep: [".mk-dll-dir", ".production-env"],
task: () => {
setWebpackProfile("dll");
return exec(
`${webpackCmd()} --config`,
quote(getWebpackStartConfig("webpack.config.dll.js")),
`--color`
);
},
},
"copy-dll": () => shell.cp("-r", "dll/*", "dist"),
});
}
Object.assign(tasks, eslintTasks(xarcOptions, xrun2));
if (xarcOptions.options.karma) {
const noSingleRun = process.argv.indexOf("--no-single-run") >= 0 ? "--no-single-run" : "";
Object.assign(tasks, {
".karma.test-frontend": {
desc: false,
task: () => {
setWebpackProfile("test");
return mkCmd(
`~$karma start`,
quote(karmaConfig("karma.conf.js")),
`--colors`,
noSingleRun
);
},
},
".karma.test-frontend-ci": {
dep: [setKarmaCovEnv],
task: () => {
setWebpackProfile("coverage");
return mkCmd(
`~$karma start`,
quote(karmaConfig("karma.conf.coverage.js")),
`--colors`,
noSingleRun
);
},
},
".karma.test-frontend-cov": {
dep: [setKarmaCovEnv],
task: () => {
setWebpackProfile("coverage");
if (shell.test("-d", "test")) {
logger.info("\nRunning Karma unit tests:\n");
return mkCmd(
`~$karma start`,
quote(karmaConfig("karma.conf.coverage.js")),
`--colors`,
noSingleRun
);
}
return undefined;
},
},
".karma.test-frontend-dev": ["test-frontend"],
".karma.test-frontend-dev-watch": () => {
setWebpackProfile("test");
return mkCmd(
`~$karma start`,
quote(karmaConfig("karma.conf.watch.js")),
`--colors --browsers Chrome --no-single-run --auto-watch`,
noSingleRun
);
},
});
} else {
const karmaTasksDisabled = () => {
logger.info(`Karma tests disabled because @xarc/opt-karma is not installed.
Please add it to your devDependencies to enable running karma tests`);
};
Object.assign(tasks, {
".karma.test-frontend": karmaTasksDisabled,
".karma.test-frontend-ci": karmaTasksDisabled,
".karma.test-frontend-cov": karmaTasksDisabled,
".karma.test-frontend-dev": karmaTasksDisabled,
".karma.test-frontend-dev-watch": karmaTasksDisabled,
});
}
if (xarcOptions.options.jest) {
Object.assign(tasks, {
jest: {
desc: "Run jest tests (--inspect-brk to start debugger)",
task() {
return `.jest.test-frontend-cov ${this.argv.slice(1).join(" ")}`;
},
},
".jest.test-frontend-cov"() {
const testDir = jestTestDirectories.find((x) => shell.test("-d", x));
let runJest: any = testDir;
if (!runJest) {
const scanned = scanDir.sync({
dir: Path.resolve(xarcCwd, AppMode.src.dir),
grouping: true,
includeDir: true,
filterDir: (d) => (jestTestDirectories.indexOf(d) >= 0 ? "dirs" : "otherDirs"),
filterExt: [".js", ".jsx", ".ts", ".tsx"],
filter: (x) => x.indexOf(".spec.") > 0 || x.indexOf(".test.") > 0,
});
runJest = Boolean(scanned.dirs || scanned.files.length > 0);
}
if (!runJest) {
const { roots } = xarcOptions.jest;
runJest = roots && roots.length > 0;
}
if (runJest) {
const jestBinJs = require.resolve("jest/bin/jest");
logger.info("Running jest unit tests");
const brk = this.argv.indexOf("--inspect-brk") >= 0 ? "--inspect-brk" : "";
const jestOpts = this.argv.slice(1).filter((x) => x !== "--inspect-brk");
return mkCmd(
`~(tty)$node`,
brk,
jestBinJs,
jestOpts.join(" "),
`--config ${xarcOptions.config.jest}/jest.config.js`
);
} else {
return undefined;
}
},
});
} else {
Object.assign(tasks, {
jest: () => {
logger.info(`Running jest tests is not enabled because @xarc/opt-jest is not installed.
Please add it to your devDependencies to enable running jest tests.`);
},
});
}
if (xarcOptions.options.mocha) {
Object.assign(tasks, {
"test-server-cov": () => {
if (shell.test("-d", "test/server")) {
AppMode.setEnv(AppMode.src.dir);
return mkCmd(
`~$nyc --all --cwd src/server`,
`--reporter=text --reporter=lcov node_modules/mocha/bin/_mocha --opts`,
quote(mochaConfig("mocha.opts")),
`test/server`
);
}
return undefined;
},
"test-server-dev": () => {
if (shell.test("-d", "test/server")) {
AppMode.setEnv(AppMode.src.dir);
return mkCmd(`~$mocha -c --opts`, quote(mochaConfig("mocha.opts")), `test/server`);
}
return undefined;
},
});
} else {
const mochaTestDisabled = () => {
logger.info(`Running tests with mocha disabled because @xarc/opt-mocha is not installed
Please add it to your devDependencies to enable running tests with mocha`);
};
Object.assign(tasks, {
"test-server-cov": mochaTestDisabled,
"test-server-dev": mochaTestDisabled,
});
}
return tasks;
}
// if (xarcOptions.assertDevArchetypePresent) {
// // make sure that -dev app archetype is also installed.
// // if it's not then this will fail with an error message that it's not found.
// require.resolve(`${archetype.devArchetypeName}/package.json`);
// }
userXrun = userXrun || getDevTaskRunner(xarcCwd);
process.env._ELECTRODE_DEV_ = "1";
if (!process.env.hasOwnProperty("FORCE_COLOR")) {
process.env.FORCE_COLOR = "1"; // force color for chalk
}
userXrun.load("electrode", makeTasks(userXrun), -10);
generateBrowsersListRc();
return userXrun;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.