text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import AWS from 'aws-sdk'; import AWSMock from 'aws-sdk-mock'; import { mockProcessStdout } from 'jest-mock-process'; import { ListrTaskWrapper } from 'listr2'; import nock from 'nock'; import { RemoveNatGatewaysTrick, RemoveNatGatewaysState, } from '../../src/tricks/remove-nat-gateways.trick'; import { TrickContext } from '../../src/types/trick-context'; import { NatGatewayState } from '../../src/states/nat-gateway.state'; import { createMockTask } from '../util'; beforeAll(async done => { nock.abortPendingRequests(); nock.cleanAll(); nock.disableNetConnect(); // AWSMock cannot mock waiters at the moment AWS.EC2.prototype.waitFor = jest.fn().mockImplementation(() => ({ promise: jest.fn(), })); mockProcessStdout(); done(); }); afterEach(async () => { const pending = nock.pendingMocks(); if (pending.length > 0) { // eslint-disable-next-line no-console console.log(pending); throw new Error(`${pending.length} mocks are pending!`); } }); describe('remove-nat-gateways', () => { let task: ListrTaskWrapper<any, any>; beforeEach(() => { task = createMockTask(); }); it('returns correct machine name', async () => { const instance = new RemoveNatGatewaysTrick(); expect(instance.getMachineName()).toBe(RemoveNatGatewaysTrick.machineName); }); it('skips preparing tags', async () => { const instance = new RemoveNatGatewaysTrick(); await instance.prepareTags(task, {} as TrickContext, { dryRun: false, }); expect(task.skip).toBeCalled(); }); it('returns an empty Listr if no NAT gateway is found', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'EC2', 'describeNatGateways', ( params: AWS.EC2.Types.DescribeNatGatewaysRequest, callback: Function, ) => { callback(null, { NatGateways: [], } as AWS.EC2.Types.DescribeNatGatewaysResult); }, ); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [] } as TrickContext, stateObject, { dryRun: false, }, ); expect(listr.tasks.length).toBe(0); AWSMock.restore('EC2'); }); it('errors if required fields were not returned by AWS', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'EC2', 'describeNatGateways', ( params: AWS.EC2.Types.DescribeNatGatewaysRequest, callback: Function, ) => { callback(null, { NatGateways: [ { // NatGatewayId: 'foo', VpcId: 'bar', SubnetId: 'baz', NatGatewayAddresses: [{ AllocationId: 'qux' }], Tags: [{ Key: 'Team', Value: 'Tacos' }], }, { NatGatewayId: 'foo', // VpcId: 'bar', SubnetId: 'baz', NatGatewayAddresses: [{ AllocationId: 'qux' }], Tags: [{ Key: 'Team', Value: 'Tacos' }], }, { NatGatewayId: 'foo', VpcId: 'bar', // SubnetId: 'baz', NatGatewayAddresses: [{ AllocationId: 'qux' }], Tags: [{ Key: 'Team', Value: 'Tacos' }], }, { NatGatewayId: 'foo', VpcId: 'bar', SubnetId: 'baz', // NatGatewayAddresses: [{ AllocationId: 'qux' }], Tags: [{ Key: 'Team', Value: 'Tacos' }], }, ], } as AWS.EC2.Types.DescribeNatGatewaysResult); }, ); AWSMock.mock( 'EC2', 'describeRouteTables', ( params: AWS.EC2.Types.DescribeRouteTablesRequest, callback: Function, ) => { callback(null, { RouteTables: [], } as AWS.EC2.Types.DescribeRouteTablesResult); }, ); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [] } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run(); expect(listr.err).toStrictEqual([ expect.objectContaining({ errors: [ expect.objectContaining({ message: expect.stringMatching(/unexpected/gi), }), expect.objectContaining({ message: expect.stringMatching(/unexpected/gi), }), expect.objectContaining({ message: expect.stringMatching(/unexpected/gi), }), expect.objectContaining({ message: expect.stringMatching(/unexpected/gi), }), ], }), ]); AWSMock.restore('EC2'); }); it('generates state object for Nat gateways', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'EC2', 'describeNatGateways', ( params: AWS.EC2.Types.DescribeNatGatewaysRequest, callback: Function, ) => { callback(null, { NatGateways: [ { NatGatewayId: 'foo', VpcId: 'bar', SubnetId: 'baz', NatGatewayAddresses: [{ AllocationId: 'qux' }], State: 'available', Tags: [{ Key: 'Team', Value: 'Tacos' }], }, { NatGatewayId: 'foosec', VpcId: 'barex', SubnetId: 'baza', NatGatewayAddresses: [{ AllocationId: 'quxoo' }], State: 'available', Tags: [{ Key: 'Team', Value: 'Tacos' }], }, ], } as AWS.EC2.Types.DescribeNatGatewaysResult); }, ); AWSMock.mock( 'EC2', 'describeRouteTables', ( params: AWS.EC2.Types.DescribeRouteTablesRequest, callback: Function, ) => { callback(null, { RouteTables: [ { RouteTableId: 'quuz', Routes: [ { DestinationCidrBlock: '1.1.0.0/0', NatGatewayId: 'foosec' }, ], }, { RouteTableId: 'quux', Routes: [ { DestinationCidrBlock: '2.2.0.0/0', NatGatewayId: 'foo' }, ], }, { RouteTableId: 'cypo', Routes: [ { DestinationIpv6CidrBlock: '2001:db8::/32', NatGatewayId: 'foo', }, ], }, { RouteTableId: 'lopr', Routes: [ { DestinationPrefixListId: 'some-id', NatGatewayId: 'foo', }, ], }, { RouteTableId: 'mayba', Routes: [], }, ], } as AWS.EC2.Types.DescribeRouteTablesResult); }, ); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [] } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run({}); expect(stateObject.pop()).toMatchObject({ id: 'foosec', vpcId: 'barex', subnetId: 'baza', allocationIds: ['quxoo'], state: 'available', routes: [{ routeTableId: 'quuz', destinationCidr: '1.1.0.0/0' }], tags: [{ Key: 'Team', Value: 'Tacos' }], } as NatGatewayState); expect(stateObject.pop()).toMatchObject({ id: 'foo', vpcId: 'bar', subnetId: 'baz', allocationIds: ['qux'], state: 'available', routes: [ { routeTableId: 'quux', destinationCidr: '2.2.0.0/0' }, { routeTableId: 'cypo', destinationIpv6Cidr: '2001:db8::/32' }, { routeTableId: 'lopr', destinationPrefixListId: 'some-id' }, ], tags: [{ Key: 'Team', Value: 'Tacos' }], } as NatGatewayState); AWSMock.restore('EC2'); }); it('generates state object for tagged resources', async () => { AWSMock.setSDKInstance(AWS); const describeNatGatewaysSpy = jest .fn() .mockImplementationOnce( ( params: AWS.EC2.Types.DescribeNatGatewaysRequest, callback: Function, ) => { callback(null, { NatGateways: [ { NatGatewayId: 'foosec', VpcId: 'barex', SubnetId: 'baza', NatGatewayAddresses: [{ AllocationId: 'quxoo' }], State: 'available', Tags: [{ Key: 'Team', Value: 'Chimichanga' }], }, ], } as AWS.EC2.Types.DescribeNatGatewaysResult); }, ); AWSMock.mock('EC2', 'describeNatGateways', describeNatGatewaysSpy); AWSMock.mock( 'EC2', 'describeRouteTables', ( params: AWS.EC2.Types.DescribeRouteTablesRequest, callback: Function, ) => { callback(null, { RouteTables: [ { RouteTableId: 'quuz', Routes: [ { DestinationCidrBlock: '1.1.0.0/0', NatGatewayId: 'foosec' }, ], }, { RouteTableId: 'quux', Routes: [ { DestinationCidrBlock: '2.2.0.0/0', NatGatewayId: 'foo' }, ], }, { RouteTableId: 'cypo', Routes: [ { DestinationIpv6CidrBlock: '2001:db8::/32', NatGatewayId: 'foo', }, ], }, { RouteTableId: 'lopr', Routes: [ { DestinationPrefixListId: 'some-id', NatGatewayId: 'foo', }, ], }, { RouteTableId: 'mayba', Routes: [], }, ], } as AWS.EC2.Types.DescribeRouteTablesResult); }, ); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [] } as TrickContext, stateObject, { dryRun: false, tags: [{ Key: 'Team', Values: ['Chimichanga'] }], }, ); await listr.run({}); expect(describeNatGatewaysSpy).toBeCalledWith( expect.objectContaining({ Filter: [{ Name: 'tag:Team', Values: ['Chimichanga'] }], MaxResults: 10, } as AWS.EC2.Types.DescribeNatGatewaysRequest), expect.any(Function), ); expect(stateObject.length).toBe(1); expect(stateObject.pop()).toMatchObject({ id: 'foosec', vpcId: 'barex', subnetId: 'baza', allocationIds: ['quxoo'], state: 'available', routes: [{ routeTableId: 'quuz', destinationCidr: '1.1.0.0/0' }], tags: [{ Key: 'Team', Value: 'Chimichanga' }], } as NatGatewayState); AWSMock.restore('EC2'); }); it('conserves NAT gateways', async () => { AWSMock.setSDKInstance(AWS); const deleteNatGatewaySpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock('EC2', 'deleteNatGateway', deleteNatGatewaySpy); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = [ { id: 'foo', vpcId: 'bar', subnetId: 'baz', state: 'available', allocationIds: ['qux'], routes: [{ routeTableId: 'quux', destinationCidr: '0.0.0.0/0' }], tags: [{ Key: 'Name', Value: 'my-gw' }], }, ]; const conserveListr = await instance.conserve(task, stateObject, { dryRun: false, }); await conserveListr.run({}); expect(deleteNatGatewaySpy).toBeCalledWith( expect.objectContaining({ NatGatewayId: 'foo', }), expect.anything(), ); AWSMock.restore('EC2'); }); it('skips conserve if status is not "available"', async () => { AWSMock.setSDKInstance(AWS); const deleteNatGatewaySpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock('EC2', 'deleteNatGateway', deleteNatGatewaySpy); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = [ { id: 'foo', vpcId: 'bar', subnetId: 'baz', state: 'pending', allocationIds: ['qux'], routes: [{ routeTableId: 'quux', destinationCidr: '0.0.0.0/0' }], tags: [{ Key: 'Name', Value: 'my-gw' }], }, ]; const conserveListr = await instance.conserve(task, stateObject, { dryRun: false, }); await conserveListr.run({}); expect(deleteNatGatewaySpy).not.toBeCalled(); AWSMock.restore('EC2'); }); it('skips conserve if dry-run option is enabled', async () => { AWSMock.setSDKInstance(AWS); const deleteNatGatewaySpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock('EC2', 'deleteNatGateway', deleteNatGatewaySpy); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = [ { id: 'foo', vpcId: 'bar', subnetId: 'baz', allocationIds: ['qux'], state: 'available', routes: [{ routeTableId: 'quux', destinationCidr: '0.0.0.0/0' }], tags: [{ Key: 'Team', Value: 'Tacos' }], }, ]; const conserveListr = await instance.conserve(task, stateObject, { dryRun: true, }); await conserveListr.run({}); expect(deleteNatGatewaySpy).not.toBeCalled(); AWSMock.restore('EC2'); }); it('restores removed NAT gateway', async () => { AWSMock.setSDKInstance(AWS); const createNatGatewaySpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, { NatGateway: { NatGatewayId: 'newfoo', }, } as AWS.EC2.CreateNatGatewayResult); }); AWSMock.mock('EC2', 'createNatGateway', createNatGatewaySpy); const replaceRouteSpy = jest.fn().mockImplementation((params, callback) => { callback(null, {}); }); AWSMock.mock('EC2', 'replaceRoute', replaceRouteSpy); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = [ { id: 'foo', vpcId: 'bar', subnetId: 'baz', allocationIds: ['qux'], state: 'available', routes: [ { routeTableId: 'quux', destinationCidr: '1.2.0.0/0' }, { routeTableId: 'cypo', destinationIpv6Cidr: '2001:db8::/32' }, { routeTableId: 'lopr', destinationPrefixListId: 'some-id' }, ], tags: [{ Key: 'Team', Value: 'Tacos' }], }, ]; const restoreListr = await instance.restore(task, stateObject, { dryRun: false, }); await restoreListr.run({}); expect(createNatGatewaySpy).toBeCalledWith( expect.objectContaining({ AllocationId: 'qux', SubnetId: 'baz', TagSpecifications: [ { ResourceType: 'natgateway', Tags: [{ Key: 'Team', Value: 'Tacos' }], }, ], }), expect.anything(), ); expect(replaceRouteSpy).toBeCalledWith( expect.objectContaining({ RouteTableId: 'quux', NatGatewayId: 'newfoo', DestinationCidrBlock: '1.2.0.0/0', }), expect.anything(), ); expect(replaceRouteSpy).toBeCalledWith( expect.objectContaining({ RouteTableId: 'cypo', NatGatewayId: 'newfoo', DestinationIpv6CidrBlock: '2001:db8::/32', }), expect.anything(), ); expect(replaceRouteSpy).toBeCalledWith( expect.objectContaining({ RouteTableId: 'lopr', NatGatewayId: 'newfoo', DestinationPrefixListId: 'some-id', }), expect.anything(), ); AWSMock.restore('EC2'); }); it('skips restore if status was not "available"', async () => { AWSMock.setSDKInstance(AWS); const createNatGatewaySpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock('EC2', 'createNatGateway', createNatGatewaySpy); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = [ { id: 'foo', vpcId: 'bar', subnetId: 'baz', state: 'pending', allocationIds: ['qux'], routes: [{ routeTableId: 'quux', destinationCidr: '0.0.0.0/0' }], tags: [{ Key: 'Name', Value: 'my-gw' }], }, ]; const restoreListr = await instance.restore(task, stateObject, { dryRun: false, }); await restoreListr.run({}); expect(createNatGatewaySpy).not.toBeCalled(); AWSMock.restore('EC2'); }); it('skips restore if dry-run option is enabled', async () => { AWSMock.setSDKInstance(AWS); const createNatGatewaySpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock('EC2', 'createNatGateway', createNatGatewaySpy); const instance = new RemoveNatGatewaysTrick(); const stateObject: RemoveNatGatewaysState = [ { id: 'foo', vpcId: 'bar', subnetId: 'baz', allocationIds: ['qux'], state: 'available', routes: [{ routeTableId: 'quux', destinationCidr: '0.0.0.0/0' }], tags: [{ Key: 'Team', Value: 'Tacos' }], }, ]; const restoreListr = await instance.restore(task, stateObject, { dryRun: true, }); await restoreListr.run({}); expect(createNatGatewaySpy).not.toBeCalled(); AWSMock.restore('EC2'); }); });
the_stack
import { cleanup, jetstreamServerConf, setup } from "./jstest_util.ts"; import { deferred, delay, Empty, nanos, NatsConnectionImpl, nuid, StringCodec, } from "../nats-base-client/internal_mod.ts"; import { assert, assertArrayIncludes, assertEquals, assertThrows, assertThrowsAsync, } from "https://deno.land/std@0.95.0/testing/asserts.ts"; import { KvEntry } from "../nats-base-client/types.ts"; import { Base64KeyCodec, Bucket, NoopKvCodecs, validateBucket, validateKey, } from "../nats-base-client/kv.ts"; import { notCompatible } from "./helpers/mod.ts"; Deno.test("kv - key validation", () => { const bad = [ " x y", "x ", "x!", "xx$", "*", ">", "x.>", "x.*", ".", ".x", ".x.", "x.", ]; for (const v of bad) { assertThrows( () => { validateKey(v); }, Error, "invalid key", `expected '${v}' to be invalid key`, ); } const good = [ "foo", "_foo", "-foo", "_kv_foo", "foo123", "123", "a/b/c", "a.b.c", ]; for (const v of good) { try { validateKey(v); } catch (err) { throw new Error( `expected '${v}' to be a valid key, but was rejected: ${err.message}`, ); } } }); Deno.test("kv - bucket name validation", () => { const bad = [" B", "!", "x/y", "x>", "x.x", "x.*", "x.>", "x*", "*", ">"]; for (const v of bad) { assertThrows( () => { validateBucket(v); }, Error, "invalid bucket name", `expected '${v}' to be invalid bucket name`, ); } const good = [ "B", "b", "123", "1_2_3", "1-2-3", ]; for (const v of good) { try { validateBucket(v); } catch (err) { throw new Error( `expected '${v}' to be a valid bucket name, but was rejected: ${err.message}`, ); } } }); Deno.test("kv - init creates stream", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); if (await notCompatible(ns, nc, "2.6.3")) { return; } const jsm = await nc.jetstreamManager(); let streams = await jsm.streams.list().next(); assertEquals(streams.length, 0); const n = nuid.next(); await Bucket.create(nc, n); streams = await jsm.streams.list().next(); assertEquals(streams.length, 1); assertEquals(streams[0].config.name, `KV_${n}`); await cleanup(ns, nc); }); async function crud(bucket: Bucket): Promise<void> { const sc = StringCodec(); const status = await bucket.status(); assertEquals(status.values, 0); assertEquals(status.history, 10); assertEquals(status.bucket, bucket.bucketName()); assertEquals(status.ttl, 0); await bucket.put("k", sc.encode("hello")); let r = await bucket.get("k"); assertEquals(sc.decode(r!.value), "hello"); await bucket.put("k", sc.encode("bye")); r = await bucket.get("k"); assertEquals(sc.decode(r!.value), "bye"); await bucket.delete("k"); r = await bucket.get("k"); assert(r); assertEquals(r.operation, "DEL"); const buf: string[] = []; const values = await bucket.history(); for await (const r of values) { buf.push(sc.decode(r.value)); } assertEquals(values.getProcessed(), 3); assertEquals(buf.length, 3); assertEquals(buf[0], "hello"); assertEquals(buf[1], "bye"); assertEquals(buf[2], ""); const pr = await bucket.purgeBucket(); assertEquals(pr.purged, 3); assert(pr.success); const ok = await bucket.destroy(); assert(ok); const streams = await bucket.jsm.streams.list().next(); assertEquals(streams.length, 0); } Deno.test("kv - crud", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const n = nuid.next(); await crud(await Bucket.create(nc, n, { history: 10 }) as Bucket); await cleanup(ns, nc); }); Deno.test("kv - codec crud", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const jsm = await nc.jetstreamManager(); const streams = await jsm.streams.list().next(); assertEquals(streams.length, 0); const n = nuid.next(); const bucket = await Bucket.create(nc, n, { history: 10, codec: { key: Base64KeyCodec(), value: NoopKvCodecs().value, }, }) as Bucket; await crud(bucket); await cleanup(ns, nc); }); Deno.test("kv - history", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const n = nuid.next(); const bucket = await Bucket.create(nc, n, { history: 2 }); let status = await bucket.status(); assertEquals(status.values, 0); assertEquals(status.history, 2); await bucket.put("A", Empty); await bucket.put("A", Empty); await bucket.put("A", Empty); await bucket.put("A", Empty); status = await bucket.status(); assertEquals(status.values, 2); await cleanup(ns, nc); }); Deno.test("kv - cleanups/empty", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const n = nuid.next(); const bucket = await Bucket.create(nc, n); assertEquals(await bucket.get("x"), null); const h = await bucket.history(); assertEquals(h.getReceived(), 0); const keys = await bucket.keys(); assertEquals(keys.length, 0); const nci = nc as NatsConnectionImpl; // mux should be created const min = nci.protocol.subscriptions.getMux() ? 1 : 0; assertEquals(nci.protocol.subscriptions.subs.size, min); await cleanup(ns, nc); }); Deno.test("kv - history cleanup", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const n = nuid.next(); const bucket = await Bucket.create(nc, n); await bucket.put("a", Empty); await bucket.put("b", Empty); await bucket.put("c", Empty); const h = await bucket.history(); const done = (async () => { for await (const _e of h) { break; } })(); await done; const nci = nc as NatsConnectionImpl; // mux should be created const min = nci.protocol.subscriptions.getMux() ? 1 : 0; assertEquals(nci.protocol.subscriptions.subs.size, min); await cleanup(ns, nc); }); Deno.test("kv - bucket watch", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const sc = StringCodec(); const n = nuid.next(); const b = await Bucket.create(nc, n, { history: 10 }); const m: Map<string, string> = new Map(); const iter = await b.watch(); const done = (async () => { for await (const r of iter) { if (r.operation === "DEL") { m.delete(r.key); } else { m.set(r.key, sc.decode(r.value)); } if (r.key === "x") { break; } } })(); await b.put("a", sc.encode("1")); await b.put("b", sc.encode("2")); await b.put("c", sc.encode("3")); await b.put("a", sc.encode("2")); await b.put("b", sc.encode("3")); await b.delete("c"); await b.put("x", Empty); await done; assertEquals(iter.getProcessed(), 7); assertEquals(m.get("a"), "2"); assertEquals(m.get("b"), "3"); assert(!m.has("c")); assertEquals(m.get("x"), ""); const nci = nc as NatsConnectionImpl; // mux should be created const min = nci.protocol.subscriptions.getMux() ? 1 : 0; assertEquals(nci.protocol.subscriptions.subs.size, min); await cleanup(ns, nc); }); async function keyWatch(bucket: Bucket): Promise<void> { const sc = StringCodec(); const m: Map<string, string> = new Map(); const iter = await bucket.watch({ key: "a.>" }); const done = (async () => { for await (const r of iter) { if (r.operation === "DEL") { m.delete(r.key); } else { m.set(r.key, sc.decode(r.value)); } if (r.key === "a.x") { break; } } })(); await bucket.put("a.b", sc.encode("1")); await bucket.put("b.b", sc.encode("2")); await bucket.put("c.b", sc.encode("3")); await bucket.put("a.b", sc.encode("2")); await bucket.put("b.b", sc.encode("3")); await bucket.delete("c.b"); await bucket.put("a.x", Empty); await done; assertEquals(iter.getProcessed(), 3); assertEquals(m.get("a.b"), "2"); assertEquals(m.get("a.x"), ""); } Deno.test("kv - key watch", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const bucket = await Bucket.create(nc, nuid.next()) as Bucket; await keyWatch(bucket); const nci = nc as NatsConnectionImpl; const min = nci.protocol.subscriptions.getMux() ? 1 : 0; assertEquals(nci.protocol.subscriptions.subs.size, min); await cleanup(ns, nc); }); Deno.test("kv - codec key watch", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const bucket = await Bucket.create(nc, nuid.next(), { history: 10, codec: { key: Base64KeyCodec(), value: NoopKvCodecs().value, }, }) as Bucket; await keyWatch(bucket); const nci = nc as NatsConnectionImpl; const min = nci.protocol.subscriptions.getMux() ? 1 : 0; assertEquals(nci.protocol.subscriptions.subs.size, min); await cleanup(ns, nc); }); async function keys(b: Bucket): Promise<void> { const sc = StringCodec(); await b.put("a", sc.encode("1")); await b.put("b", sc.encode("2")); await b.put("c.c.c", sc.encode("3")); await b.put("a", sc.encode("2")); await b.put("b", sc.encode("3")); await b.delete("c.c.c"); await b.put("x", Empty); const keys = await b.keys(); assertEquals(keys.length, 3); assertArrayIncludes(keys, ["a", "b", "x"]); } Deno.test("kv - keys", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const b = await Bucket.create(nc, nuid.next()); await keys(b as Bucket); const nci = nc as NatsConnectionImpl; const min = nci.protocol.subscriptions.getMux() ? 1 : 0; assertEquals(nci.protocol.subscriptions.subs.size, min); await cleanup(ns, nc); }); Deno.test("kv - codec keys", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const b = await Bucket.create(nc, nuid.next(), { history: 10, codec: { key: Base64KeyCodec(), value: NoopKvCodecs().value, }, }); await keys(b as Bucket); const nci = nc as NatsConnectionImpl; const min = nci.protocol.subscriptions.getMux() ? 1 : 0; assertEquals(nci.protocol.subscriptions.subs.size, min); await cleanup(ns, nc); }); Deno.test("kv - ttl", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const sc = StringCodec(); const b = await Bucket.create(nc, nuid.next(), { ttl: 1000 }) as Bucket; const jsm = await nc.jetstreamManager(); const si = await jsm.streams.info(b.stream); assertEquals(si.config.max_age, nanos(1000)); assertEquals(await b.get("x"), null); await b.put("x", sc.encode("hello")); const e = await b.get("x"); assert(e); assertEquals(sc.decode(e.value), "hello"); await delay(1500); assertEquals(await b.get("x"), null); await cleanup(ns, nc); }); Deno.test("kv - no ttl", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const sc = StringCodec(); const b = await Bucket.create(nc, nuid.next()) as Bucket; await b.put("x", sc.encode("hello")); let e = await b.get("x"); assert(e); assertEquals(sc.decode(e.value), "hello"); await delay(1500); e = await b.get("x"); assert(e); assertEquals(sc.decode(e.value), "hello"); await cleanup(ns, nc); }); Deno.test("kv - complex key", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const sc = StringCodec(); const b = await Bucket.create(nc, nuid.next()) as Bucket; await b.put("x.y.z", sc.encode("hello")); const e = await b.get("x.y.z"); assertEquals(e?.value, sc.encode("hello")); const d = deferred<KvEntry>(); let iter = await b.watch({ key: "x.y.>" }); await (async () => { for await (const r of iter) { d.resolve(r); break; } })(); const vv = await d; assertEquals(vv.value, sc.encode("hello")); const dd = deferred<KvEntry>(); iter = await b.history({ key: "x.y.>" }); await (async () => { for await (const r of iter) { dd.resolve(r); break; } })(); const vvv = await dd; assertEquals(vvv.value, sc.encode("hello")); const nci = nc as NatsConnectionImpl; const min = nci.protocol.subscriptions.getMux() ? 1 : 0; assertEquals(nci.protocol.subscriptions.subs.size, min); await cleanup(ns, nc); }); Deno.test("kv - remove key", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const sc = StringCodec(); const b = await Bucket.create(nc, nuid.next()) as Bucket; await b.put("a.b", sc.encode("ab")); let v = await b.get("a.b"); assert(v); assertEquals(sc.decode(v.value), "ab"); await b.purge("a.b"); v = await b.get("a.b"); assert(v); assertEquals(v.operation, "PURGE"); const status = await b.status(); // the purged value assertEquals(status.values, 1); await cleanup(ns, nc); }); Deno.test("kv - remove subkey", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const b = await Bucket.create(nc, nuid.next()) as Bucket; await b.put("a", Empty); await b.put("a.b", Empty); await b.put("a.c", Empty); let keys = await b.keys(); assertEquals(keys.length, 3); assertArrayIncludes(keys, ["a", "a.b", "a.c"]); await b.delete("a.*"); keys = await b.keys(); assertEquals(keys.length, 1); assertArrayIncludes(keys, ["a"]); await cleanup(ns, nc); }); Deno.test("kv - create key", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const b = await Bucket.create(nc, nuid.next()) as Bucket; const sc = StringCodec(); await b.create("a", Empty); await assertThrowsAsync( async () => { await b.create("a", sc.encode("a")); }, Error, "wrong last sequence: 1", ); await cleanup(ns, nc); }); Deno.test("kv - update key", async () => { const { ns, nc } = await setup( jetstreamServerConf({}, true), ); if (await notCompatible(ns, nc, "2.6.3")) { return; } const b = await Bucket.create(nc, nuid.next()) as Bucket; const sc = StringCodec(); const seq = await b.create("a", Empty); await assertThrowsAsync( async () => { await b.update("a", sc.encode("a"), 100); }, Error, "wrong last sequence: 1", ); await b.update("a", sc.encode("b"), seq); await cleanup(ns, nc); });
the_stack
import { cloneDeep, isObject, set, get } from 'lodash'; import { format as formatFn } from 'date-fns'; import BaseFoundation, { DefaultAdapter } from '../base/foundation'; import { BaseValueType, ValidateStatus, ValueType } from './foundation'; import { formatDateValues } from './_utils/formatter'; import { getDefaultFormatTokenByType } from './_utils/getDefaultFormatToken'; import getInsetInputFormatToken from './_utils/getInsetInputFormatToken'; import getInsetInputValueFromInsetInputStr from './_utils/getInsetInputValueFromInsetInputStr'; import { strings } from './constants'; import getDefaultPickerDate from './_utils/getDefaultPickerDate'; import { compatibleParse } from './_utils/parser'; import { isValidDate } from './_utils'; const KEY_CODE_ENTER = 'Enter'; const KEY_CODE_TAB = 'Tab'; export type Type = 'date' | 'dateRange' | 'year' | 'month' | 'dateTime' | 'dateTimeRange'; export type RangeType = 'rangeStart' | 'rangeEnd'; export type PanelType = 'left' | 'right'; export interface DateInputEventHandlerProps { onClick?: (e: any) => void; onChange?: (value: string, e: any) => void; onEnterPress?: (e: any) => void; onBlur?: (e: any) => void; onFocus?: (e: any, rangeType: RangeType) => void; onClear?: (e: any) => void; onRangeInputClear?: (e: any) => void; onRangeEndTabPress?: (e: any) => void; onInsetInputChange?: (options: InsetInputChangeProps) => void; } export interface DateInputElementProps { insetLabel?: any; prefix?: any; } export interface DateInputFoundationProps extends DateInputElementProps, DateInputEventHandlerProps { [x: string]: any; value?: BaseValueType[]; disabled?: boolean; type?: Type; showClear?: boolean; format?: string; inputStyle?: React.CSSProperties; inputReadOnly?: boolean; validateStatus?: ValidateStatus; prefixCls?: string; rangeSeparator?: string; panelType?: PanelType; insetInput?: boolean; insetInputValue?: InsetInputValue; density?: typeof strings.DENSITY_SET[number]; defaultPickerValue?: ValueType; } export interface InsetInputValue { monthLeft: { dateInput: string; timeInput: string; }, monthRight: { dateInput: string; timeInput: string; } } export interface InsetInputChangeFoundationProps { value: string; insetInputValue: InsetInputValue; event: any; valuePath: string; } export interface InsetInputChangeProps { insetInputStr: string; format: string; insetInputValue: InsetInputValue; } export interface DateInputAdapter extends DefaultAdapter { updateIsFocusing: (isFocusing: boolean) => void; notifyClick: DateInputFoundationProps['onClick']; notifyChange: DateInputFoundationProps['onChange']; notifyInsetInputChange: DateInputFoundationProps['onInsetInputChange']; notifyEnter: DateInputFoundationProps['onEnterPress']; notifyBlur: DateInputFoundationProps['onBlur']; notifyClear: DateInputFoundationProps['onClear']; notifyFocus: DateInputFoundationProps['onFocus']; notifyRangeInputClear: DateInputFoundationProps['onRangeInputClear']; notifyRangeInputFocus: DateInputFoundationProps['onFocus']; notifyTabPress: DateInputFoundationProps['onRangeEndTabPress']; } export default class InputFoundation extends BaseFoundation<DateInputAdapter> { constructor(adapter: DateInputAdapter) { super({ ...adapter }); } // eslint-disable-next-line @typescript-eslint/no-empty-function init() {} // eslint-disable-next-line @typescript-eslint/no-empty-function destroy() {} handleClick(e: any) { this._adapter.notifyClick(e); } handleChange(value: string, e: any) { this._adapter.notifyChange(value, e); } handleInputComplete(e: any) { /** * onKeyPress, e.key Code gets a value of 0 instead of 13 * Here key is used to judge the button */ if (e.key === KEY_CODE_ENTER) { this._adapter.notifyEnter(e.target.value); } } handleInputClear(e: any) { this._adapter.notifyClear(e); } handleRangeInputClear(e: any) { // prevent trigger click outside this.stopPropagation(e); this._adapter.notifyRangeInputClear(e); } handleRangeInputEnterPress(e: any, rangeInputValue: string) { if (e.key === KEY_CODE_ENTER) { this._adapter.notifyEnter(rangeInputValue); } } handleRangeInputEndKeyPress(e: any) { if (e.key === KEY_CODE_TAB) { this._adapter.notifyTabPress(e); } } handleRangeInputFocus(e: any, rangeType: RangeType) { this._adapter.notifyRangeInputFocus(e, rangeType); } formatShowText(value: BaseValueType[], customFormat?: string) { const { type, dateFnsLocale, format, rangeSeparator } = this._adapter.getProps(); const formatToken = customFormat || format || getDefaultFormatTokenByType(type); let text = ''; switch (type) { case 'date': text = formatDateValues(value, formatToken, undefined, dateFnsLocale); break; case 'dateRange': text = formatDateValues(value, formatToken, { groupSize: 2, groupInnerSeparator: rangeSeparator }, dateFnsLocale); break; case 'dateTime': text = formatDateValues(value, formatToken, undefined, dateFnsLocale); break; case 'dateTimeRange': text = formatDateValues(value, formatToken, { groupSize: 2, groupInnerSeparator: rangeSeparator }, dateFnsLocale); break; case 'month': text = formatDateValues(value, formatToken, undefined, dateFnsLocale); break; default: break; } return text; } handleInsetInputChange(options: InsetInputChangeFoundationProps) { const { value, valuePath, insetInputValue } = options; const { format, type } = this._adapter.getProps(); const insetFormatToken = getInsetInputFormatToken({ type, format }); let newInsetInputValue = set(cloneDeep(insetInputValue), valuePath, value); newInsetInputValue = this._autoFillTimeToInsetInputValue({ insetInputValue: newInsetInputValue, valuePath, format: insetFormatToken }); const newInputValue = this.concatInsetInputValue({ insetInputValue: newInsetInputValue }); this._adapter.notifyInsetInputChange({ insetInputValue: newInsetInputValue, format: insetFormatToken, insetInputStr: newInputValue }); } _autoFillTimeToInsetInputValue(options: { insetInputValue: InsetInputValue; format: string; valuePath: string;}) { const { valuePath, insetInputValue, format } = options; const { type, defaultPickerValue, dateFnsLocale } = this._adapter.getProps(); const insetInputValueWithTime = cloneDeep(insetInputValue); const { nowDate, nextDate } = getDefaultPickerDate({ defaultPickerValue, format, dateFnsLocale }); if (type.includes('Time')) { let timeStr = ''; const dateFormatToken = get(format.split(' '), '0', strings.FORMAT_FULL_DATE); const timeFormatToken = get(format.split(' '), '1', strings.FORMAT_TIME_PICKER); switch (valuePath) { case 'monthLeft.dateInput': const dateLeftStr = insetInputValueWithTime.monthLeft.dateInput; if (!insetInputValueWithTime.monthLeft.timeInput && dateLeftStr.length === dateFormatToken.length) { const dateLeftParsed = compatibleParse(insetInputValueWithTime.monthLeft.dateInput, dateFormatToken); if (isValidDate(dateLeftParsed)) { timeStr = formatFn(nowDate, timeFormatToken); insetInputValueWithTime.monthLeft.timeInput = timeStr; } } break; case 'monthRight.dateInput': const dateRightStr = insetInputValueWithTime.monthRight.dateInput; if (!insetInputValueWithTime.monthRight.timeInput && dateRightStr.length === dateFormatToken.length) { const dateRightParsed = compatibleParse(dateRightStr, dateFormatToken); if (isValidDate(dateRightParsed)) { timeStr = formatFn(nextDate, timeFormatToken); insetInputValueWithTime.monthRight.timeInput = timeStr; } } break; default: break; } } return insetInputValueWithTime; } /** * 只有传入的 format 符合 formatReg 时,才会使用用户传入的 format * 否则会使用默认的 format 作为 placeholder * * The format passed in by the user will be used only if the incoming format conforms to formatReg * Otherwise the default format will be used as placeholder */ getInsetInputPlaceholder() { const { type, format } = this._adapter.getProps(); const insetInputFormat = getInsetInputFormatToken({ type, format }); let datePlaceholder, timePlaceholder; switch (type) { case 'date': case 'month': case 'dateRange': datePlaceholder = insetInputFormat; break; case 'dateTime': case 'dateTimeRange': [datePlaceholder, timePlaceholder] = insetInputFormat.split(' '); break; } return ({ datePlaceholder, timePlaceholder, }); } /** * 从当前日期值或 inputValue 中解析出 insetInputValue * * Parse out insetInputValue from current date value or inputValue */ getInsetInputValue({ value, insetInputValue } : { value: BaseValueType[]; insetInputValue: InsetInputValue }) { const { type, rangeSeparator, format } = this._adapter.getProps(); let inputValueStr = ''; if (isObject(insetInputValue)) { inputValueStr = this.concatInsetInputValue({ insetInputValue }); } else { const insetInputFormat = getInsetInputFormatToken({ format, type }); inputValueStr = this.formatShowText(value, insetInputFormat); } const newInsetInputValue = getInsetInputValueFromInsetInputStr({ inputValue: inputValueStr, type, rangeSeparator }); return newInsetInputValue; } concatInsetDateAndTime({ date, time }) { return `${date} ${time}`; } concatInsetDateRange({ rangeStart, rangeEnd }) { const { rangeSeparator } = this._adapter.getProps(); return `${rangeStart}${rangeSeparator}${rangeEnd}`; } concatInsetInputValue({ insetInputValue }: { insetInputValue: InsetInputValue }) { const { type } = this._adapter.getProps(); let inputValue = ''; switch (type) { case 'date': case 'month': inputValue = insetInputValue.monthLeft.dateInput; break; case 'dateRange': inputValue = this.concatInsetDateRange({ rangeStart: insetInputValue.monthLeft.dateInput, rangeEnd: insetInputValue.monthRight.dateInput }); break; case 'dateTime': inputValue = this.concatInsetDateAndTime({ date: insetInputValue.monthLeft.dateInput, time: insetInputValue.monthLeft.timeInput }); break; case 'dateTimeRange': const rangeStart = this.concatInsetDateAndTime({ date: insetInputValue.monthLeft.dateInput, time: insetInputValue.monthLeft.timeInput }); const rangeEnd = this.concatInsetDateAndTime({ date: insetInputValue.monthRight.dateInput, time: insetInputValue.monthRight.timeInput }); inputValue = this.concatInsetDateRange({ rangeStart, rangeEnd }); break; } return inputValue; } }
the_stack
import { Column, CompositeColumn, EAdvancedSortMethod, EDateSort, ESortMethod, IMultiLevelColumn, isSortingAscByDefault, isSupportType, } from '../model'; import { cssClass } from '../styles'; import ADialog, { dialogContext, IDialogContext } from './dialogs/ADialog'; import CategoricalColorMappingDialog from './dialogs/CategoricalColorMappingDialog'; import CategoricalFilterDialog from './dialogs/CategoricalFilterDialog'; import CategoricalMappingFilterDialog from './dialogs/CategoricalMappingFilterDialog'; import ChangeRendererDialog from './dialogs/ChangeRendererDialog'; import ColorMappingDialog from './dialogs/ColorMappingDialog'; import CompositeChildrenDialog from './dialogs/CompositeChildrenDialog'; import CutOffHierarchyDialog from './dialogs/CutOffHierarchyDialog'; import DateFilterDialog from './dialogs/DateFilterDialog'; import EditPatternDialog from './dialogs/EditPatternDialog'; import GroupDialog from './dialogs/GroupDialog'; import MappingDialog from './dialogs/MappingDialog'; import NumberFilterDialog from './dialogs/NumberFilterDialog'; import ReduceDialog from './dialogs/ReduceDialog'; import RenameDialog from './dialogs/RenameDialog'; import ScriptEditDialog from './dialogs/ScriptEditDialog'; import SearchDialog from './dialogs/SearchDialog'; import ShowTopNDialog from './dialogs/ShowTopNDialog'; import SortDialog from './dialogs/SortDialog'; import StringFilterDialog from './dialogs/StringFilterDialog'; import WeightsEditDialog from './dialogs/WeightsEditDialog'; import SelectionFilterDialog from './dialogs/SelectionFilterDialog'; import type { IRankingHeaderContext, IOnClickHandler, IUIOptions, IToolbarAction, IToolbarDialogAddon, } from './interfaces'; import appendDate from './dialogs/groupDate'; import appendNumber from './dialogs/groupNumber'; import appendString from './dialogs/groupString'; import { sortMethods } from './dialogs/utils'; interface IDialogClass { new (col: any, dialog: IDialogContext, ...args: any[]): ADialog; } function ui(title: string, onClick: IOnClickHandler, options: Partial<IUIOptions> = {}): IToolbarAction { return { title, onClick, options }; } function uiDialog( title: string, dialogClass: IDialogClass, extraArgs: (ctx: IRankingHeaderContext) => any[] = () => [], options: Partial<IUIOptions> = {} ): IToolbarAction { return { title, onClick: (col, evt, ctx, level) => { const dialog = new dialogClass(col, dialogContext(ctx, level, evt), ...extraArgs(ctx)); dialog.open(); }, options, }; } const sort: IToolbarAction = { title: 'Sort', // basic ranking onClick: (col, evt, ctx, level) => { ctx.dialogManager.removeAboveLevel(level); if (!evt.ctrlKey) { col.toggleMySorting(); return; } const ranking = col.findMyRanker()!; const current = ranking.getSortCriteria(); const order = col.isSortedByMe(); const isAscByDefault = isSortingAscByDefault(col); if (order.priority === undefined) { ranking.sortBy(col, isAscByDefault, current.length); return; } let next: string | undefined = undefined; if (isAscByDefault) { next = order.asc ? 'desc' : undefined; } else { next = !order.asc ? 'asc' : undefined; } ranking.sortBy(col, next === 'asc', next ? order.priority : -1); }, options: { mode: 'shortcut', order: 1, featureCategory: 'ranking', featureLevel: 'basic', }, }; const sortBy: IToolbarAction = { title: 'Sort By …', // advanced ranking onClick: (col, evt, ctx, level) => { const dialog = new SortDialog(col, false, dialogContext(ctx, level, evt), ctx); dialog.open(); }, options: { mode: 'menu', order: 1, featureCategory: 'ranking', featureLevel: 'advanced', }, }; const sortGroupBy: IToolbarAction = { title: 'Sort Groups By …', // advanced ranking onClick: (col, evt, ctx, level) => { const dialog = new SortDialog(col, true, dialogContext(ctx, level, evt), ctx); dialog.open(); }, options: { mode: 'menu', order: 3, featureCategory: 'ranking', featureLevel: 'advanced', }, }; const rename: IToolbarAction = { title: 'Rename …', // advanced onClick: (col, evt, ctx, level) => { const dialog = new RenameDialog(col, dialogContext(ctx, level, evt)); dialog.open(); }, options: { order: 5, featureCategory: 'ui', featureLevel: 'advanced', }, }; const vis: IToolbarAction = { title: 'Visualization …', // advanced view onClick: (col, evt, ctx, level) => { const dialog = new ChangeRendererDialog(col, dialogContext(ctx, level, evt), ctx); dialog.open(); }, options: { featureCategory: 'ui', featureLevel: 'advanced', }, }; const clone: IToolbarAction = { title: 'Clone', // advanced model onClick: (col, _evt, ctx) => { ctx.dialogManager.removeAll(); // since the column will be removed ctx.provider.takeSnapshot(col); }, options: { order: 80, featureCategory: 'model', featureLevel: 'advanced', }, }; const remove: IToolbarAction = { title: 'Remove', // advanced model onClick: (col, _evt, ctx) => { ctx.dialogManager.removeAll(); // since the column will be removed const ranking = col.findMyRanker()!; const last = ranking.children.every((d) => isSupportType(d) || d.fixed || d === col); if (!last) { col.removeMe(); return; } ctx.provider.removeRanking(ranking); ctx.provider.ensureOneRanking(); }, options: { order: 90, featureCategory: 'model', featureLevel: 'advanced', }, }; // basic ranking const group = ui( 'Group', (col, evt, ctx, level) => { ctx.dialogManager.removeAboveLevel(level); if (!evt.ctrlKey) { col.groupByMe(); return; } const ranking = col.findMyRanker()!; const current = ranking.getGroupCriteria(); const order = current.indexOf(col); ranking.groupBy(col, order >= 0 ? -1 : current.length); }, { mode: 'shortcut', order: 2, featureCategory: 'ranking', featureLevel: 'basic' } ); // advanced ranking const groupBy = ui( 'Group By …', (col, evt, ctx, level) => { const dialog = new GroupDialog(col, dialogContext(ctx, level, evt), ctx); dialog.open(); }, { mode: 'menu', order: 2, featureCategory: 'ranking', featureLevel: 'advanced' } ); function toggleCompressExpand(col: Column, evt: MouseEvent, ctx: IRankingHeaderContext, level: number) { ctx.dialogManager.removeAboveLevel(level); const mcol = col as IMultiLevelColumn; mcol.setCollapsed(!mcol.getCollapsed()); const collapsed = mcol.getCollapsed(); const i = evt.currentTarget as HTMLElement; i.title = collapsed ? 'Expand' : 'Compress'; i.classList.toggle(cssClass('action-compress'), !collapsed); i.classList.toggle(cssClass('action-expand'), collapsed); const inner = i.getElementsByTagName('span')[0]!; if (inner) { inner.textContent = i.title; } } const compress: IToolbarAction = { title: 'Compress', enabled: (col: IMultiLevelColumn) => !col.getCollapsed(), onClick: toggleCompressExpand, options: { featureCategory: 'model', featureLevel: 'advanced' }, }; const expand: IToolbarAction = { title: 'Expand', enabled: (col: IMultiLevelColumn) => col.getCollapsed(), onClick: toggleCompressExpand, options: { featureCategory: 'model', featureLevel: 'advanced' }, }; const setShowTopN: IToolbarAction = { title: 'Change Show Top N', onClick: (_col, evt, ctx, level) => { const dialog = new ShowTopNDialog(ctx.provider, dialogContext(ctx, level, evt)); dialog.open(); }, options: { featureCategory: 'ui', featureLevel: 'advanced', }, }; export const toolbarActions: { [key: string]: IToolbarAction } = { vis, group, groupBy, compress, expand, sort, sortBy, sortGroupBy, clone, remove, rename, setShowTopN, search: uiDialog('Search …', SearchDialog, (ctx) => [ctx.provider], { mode: 'menu+shortcut', order: 4, featureCategory: 'ranking', featureLevel: 'basic', }), filterNumber: uiDialog('Filter …', NumberFilterDialog, (ctx) => [ctx], { mode: 'menu+shortcut', featureCategory: 'ranking', featureLevel: 'basic', }), filterDate: uiDialog('Filter …', DateFilterDialog, (ctx) => [ctx], { mode: 'menu+shortcut', featureCategory: 'ranking', featureLevel: 'basic', }), filterString: uiDialog('Filter …', StringFilterDialog, (ctx) => [ctx], { mode: 'menu+shortcut', featureCategory: 'ranking', featureLevel: 'basic', }), filterSelection: uiDialog('Filter …', SelectionFilterDialog, (ctx) => [ctx], { mode: 'menu+shortcut', featureCategory: 'ranking', featureLevel: 'basic', }), filterCategorical: uiDialog('Filter …', CategoricalFilterDialog, (ctx) => [ctx], { mode: 'menu+shortcut', featureCategory: 'ranking', featureLevel: 'basic', }), filterOrdinal: uiDialog('Filter …', CategoricalMappingFilterDialog, () => [], { mode: 'menu+shortcut', featureCategory: 'ranking', featureLevel: 'basic', }), colorMapped: uiDialog('Color Mapping …', ColorMappingDialog, (ctx) => [ctx], { mode: 'menu', featureCategory: 'ui', featureLevel: 'advanced', }), colorMappedCategorical: uiDialog('Color Mapping …', CategoricalColorMappingDialog, () => [], { mode: 'menu', featureCategory: 'ui', featureLevel: 'advanced', }), script: uiDialog('Edit Combine Script …', ScriptEditDialog, () => [], { mode: 'menu+shortcut', featureCategory: 'model', featureLevel: 'advanced', }), reduce: uiDialog('Reduce by …', ReduceDialog, () => [], { featureCategory: 'model', featureLevel: 'advanced', }), cutoff: uiDialog('Set Cut Off …', CutOffHierarchyDialog, (ctx) => [ctx], { featureCategory: 'model', featureLevel: 'advanced', }), editMapping: uiDialog('Data Mapping …', MappingDialog, (ctx) => [ctx], { featureCategory: 'model', featureLevel: 'advanced', }), editPattern: uiDialog('Edit Pattern …', EditPatternDialog, (ctx) => [ctx], { featureCategory: 'model', featureLevel: 'advanced', }), editWeights: uiDialog('Edit Weights …', WeightsEditDialog, () => [], { mode: 'menu+shortcut', featureCategory: 'model', featureLevel: 'advanced', }), compositeContained: uiDialog('Contained Columns …', CompositeChildrenDialog, (ctx) => [ctx], { featureCategory: 'model', featureLevel: 'advanced', }), splitCombined: ui( 'Split Combined Column', (col, _evt, ctx, level) => { ctx.dialogManager.removeAboveLevel(level - 1); // close itself // split the combined column into its children (col as CompositeColumn).children.reverse().forEach((c) => col.insertAfterMe(c)); col.removeMe(); }, { featureCategory: 'model', featureLevel: 'advanced' } ), invertSelection: ui( 'Invert Selection', (col, _evt, ctx, level) => { ctx.dialogManager.removeAboveLevel(level - 1); // close itself const s = ctx.provider.getSelection(); const order = Array.from(col.findMyRanker()!.getOrder()); if (s.length === 0) { ctx.provider.setSelection(order); return; } const ss = new Set(s); const others = order.filter((d) => !ss.has(d)); ctx.provider.setSelection(others); }, { featureCategory: 'model', featureLevel: 'advanced' } ), }; function uiSortMethod(methods: string[]): IToolbarDialogAddon { methods = methods.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); return { title: 'Sort By', order: 2, append(col, node) { return sortMethods(node, col as any, methods); }, }; } export const toolbarDialogAddons: { [key: string]: IToolbarDialogAddon } = { sortNumber: uiSortMethod(Object.keys(EAdvancedSortMethod)), sortNumbers: uiSortMethod(Object.keys(EAdvancedSortMethod)), sortBoxPlot: uiSortMethod(Object.keys(ESortMethod)), sortDates: uiSortMethod(Object.keys(EDateSort)), sortGroups: uiSortMethod(['count', 'name']), groupNumber: { title: 'Split', order: 2, append: appendNumber, } as IToolbarDialogAddon, groupString: { title: 'Groups', order: 2, append: appendString, } as IToolbarDialogAddon, groupDate: { title: 'Granularity', order: 2, append: appendDate, } as IToolbarDialogAddon, };
the_stack
/// <reference types="jquery" /> declare namespace MCustomScrollbar { type Factory = (jQuery: JQueryStatic) => void; interface CustomScrollbarOptions { /** * Set the width of your content (overwrites CSS width), value in pixels (integer) or percentage (string) */ setWidth?: boolean|number|string; /** * Set the height of your content (overwirtes CSS height), value in pixels (integer) or percentage (string) */ setHeight?: boolean|number|string; /** * Set the initial css top property of content, accepts string values (css top position). * Example: setTop: "-100px". */ setTop? : number|string; /** * Set the initial css top property of content, accepts string values (css top position). * Example: setTop: "-100px". */ setLeft? : number|string; /** * Define content’s scrolling axis (the type of scrollbars added to the element: vertical and/of horizontal). * Available values: "y", "x", "yx". y -vertical, x - horizontal, yx - vertical and horizontal */ axis?: "x"|"y"|"yx"; /** * Set the position of scrollbar in relation to content. * Available values: "inside", "outside". * Setting scrollbarPosition: "inside" (default) makes scrollbar appear inside the element. * Setting scrollbarPosition: "outside" makes scrollbar appear outside the element. * Note that setting the value to "outside" requires your element (or parent elements) * to have CSS position: relative (otherwise the scrollbar will be positioned in relation to document’s root element). */ scrollbarPosition?: "inside"|"outside"; /** * Always keep scrollbar(s) visible, even when there’s nothing to scroll. * 0 – disable (default) * 1 – keep dragger rail visible * 2 – keep all scrollbar components (dragger, rail, buttons etc.) visible */ alwaysShowScrollbar?: number; /** * Make scrolling snap to a multiple of a fixed number of pixels. Useful in cases like scrolling tabular data, * image thumbnails or slides and you need to prevent scrolling from stopping half-way your elements. * Note that your elements must be of equal width or height in order for this to work properly. * To set different values for vertical and horizontal scrolling, use an array: [y,x] */ snapAmount?: number|[number,number]; /** * Set an offset (in pixels) for the snapAmount option. Useful when for example you need to offset the * snap amount of table rows by the table header. */ snapOffset?: number; /** * Enable or disable auto-expanding the scrollbar when cursor is over or dragging the scrollbar. */ autoExpandScrollbar?: boolean; /** * Scrolling inertia (easing), value in milliseconds (0 for no scrolling inertia) */ scrollInertia?: number; /** * Mouse wheel support */ mouseWheel?: { /** * Enable or disable content scrolling via mouse-wheel. */ enable?: boolean; /** * Set the mouse-wheel scrolling amount (in pixels). * The default value "auto" adjusts scrolling amount according to scrollable content length. */ scrollAmount?: "auto"|number; /** * Define the mouse-wheel scrolling axis when both vertical and horizontal scrollbars are present. * Set axis: "y" (default) for vertical or axis: "x" for horizontal scrolling. */ axis?: "x"|"y"; /** * Prevent the default behaviour which automatically scrolls the parent element when end * or beginning of scrolling is reached (same bahavior with browser’s native scrollbar). */ preventDefault?: boolean; /** * Set the number of pixels one wheel notch scrolls. The default value “auto” uses the OS/browser value. */ deltaFactor?: number; /** * Enable or disable mouse-wheel (delta) acceleration. * Setting normalizeDelta: true translates mouse-wheel delta value to -1 or 1. */ normalizeDelta?:boolean; /** * Invert mouse-wheel scrolling direction. * Set to true to scroll down or right when mouse-wheel is turned upwards. */ invert?: boolean; /** * Set the tags that disable mouse-wheel when cursor is over them. * Default value: ["select","option","keygen","datalist","textarea"] */ disableOver?: string[]; } /** * Keyboard support */ keyboard?:{ /** * Enable or disable content scrolling via keyboard. */ enable?: boolean; /** * Set the keyboard arrows scrolling amount (in pixels). * The default value "auto" adjusts scrolling amount according to scrollable content length. */ scrollAmount?: "auto"|number; /** * Define the buttons scrolling type/behavior. * scrollType: "stepless" – continuously scroll content while pressing the button (default) * scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above) */ scrollType?: "stepless"|"stepped"; } /** * Mouse wheel scrolling pixels amount, value in pixels (integer) or "auto" (script calculates and sets pixels amount according to content length) */ mouseWheelPixels?: any; /** * Auto-adjust scrollbar height/width according to content, values: true, false */ autoDraggerLength?: boolean; /** * Automatically hide the scrollbar when idle or mouse is not over the content */ autoHideScrollbar?: boolean; scrollButtons?: { /** * Enable or disable scroll buttons. */ enable?: boolean; /** * Define the buttons scrolling type/behavior. * scrollType: "stepless" – continuously scroll content while pressing the button (default) * scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above) */ scrollType?: "stepless"|"stepped"; /** * Set a tabindex value for the buttons. */ tabindex?: number; /** * Scroll buttons pixels scrolling amount, value in pixels or "auto" */ scrollAmount?: "auto"|number ; } advanced?: { /** * Update scrollbars on browser resize (for fluid content blocks and layouts based on percentages), values: true, false. Set to false only when you content has fixed dimensions */ updateOnBrowserResize?: boolean; /** * Auto-update scrollbars on content resize (useful when adding/changing content progrmatically), value: true, false. Setting this to true makes the script check for content * length changes (every few milliseconds) and automatically call plugin's update method to adjust the scrollbar accordingly */ updateOnContentResize?: boolean; /** * Update scrollbar(s) automatically each time an image inside the element is fully loaded. * Default value is auto which triggers the function only on "x" and "yx" axis (if needed). * The value should be true when your content contains images and you need the function to trigger on any axis. */ updateOnImageLoad?: "auto"|boolean; /** * Add extra selector(s) that’ll release scrollbar dragging upon mouseup, pointerup, touchend etc. * Example: extraDraggableSelectors: ".myClass, #myID" */ extraDraggableSelectors?: string; /** * Add extra selector(s) that’ll allow scrollbar dragging upon mousemove/up, pointermove/up, touchend etc. * Example: releaseDraggableSelectors: ".myClass, #myID" */ releaseDraggableSelectors?: string; /** * Set the auto-update timeout in milliseconds. * Default timeout: 60 */ autoUpdateTimeout?: number; /** * Update scrollbar(s) automatically when the amount and size of specific selectors changes. * Useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size. * For example, setting updateOnSelectorChange: "ul li" will update scrollbars each time list-items inside the element are changed. * Setting the value to true, will update scrollbars each time any element is changed. * To disable (default) set to false. */ updateOnSelectorChange?: string|boolean; /** * Auto-expanding content's width on horizontal scrollbars, values: true, false. Set to true if you have horizontal scrollbr on content that change on-the-fly. Demo contains * blocks with images and horizontal scrollbars that use this option parameter */ autoExpandHorizontalScroll?: boolean; /** * Set the list of elements/selectors that will auto-scroll content to their position when focused. * For example, when pressing TAB key to focus input fields, if the field is out of the viewable area the content * will scroll to its top/left position (same bahavior with browser’s native scrollbar). * To completely disable this functionality, set autoScrollOnFocus: false. * Default: * "input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']" */ autoScrollOnFocus?: boolean|string; /** * Normalize mouse wheel delta (-1/1), values: true, false */ normalizeMouseWheelDelta?: boolean; } /** * Enable or disable content touch-swipe scrolling for touch-enabled devices. * To completely disable, set contentTouchScroll: false. * Integer values define the axis-specific minimum amount required for scrolling momentum (default: 25). */ contentTouchScroll?: boolean|number; /** * Enable or disable document touch-swipe scrolling for touch-enabled devices. */ documentTouchScroll?: boolean; /** * All of the following callbacks option have examples in the callback demo - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/callbacks_example.html */ callbacks?: { /** * A function to call when plugin markup is created. */ onCreate?: () => void; /** * A function to call when scrollbars have initialized */ onInit?: () => void; /** * User defined callback function, triggered on scroll start event. You can call your own function(s) each time a scroll event begins */ onScrollStart?: () => void; /** * User defined callback function, triggered on scroll event. Call your own function(s) each time a scroll event completes */ onScroll?: () => void; /** * A function to call when scrolling is completed and content is scrolled all the way to the end (bottom/right) */ onTotalScroll?: () => void; /** * A function to call when scrolling is completed and content is scrolled back to the beginning (top/left) */ onTotalScrollBack?: () => void; /** * Set an offset for which the onTotalScroll callback is triggered. * Its value is in pixels. */ onTotalScrollOffset?: number; /** * Set an offset for which the onTotalScrollBack callback is triggered. * Its value is in pixels */ onTotalScrollBackOffset?: number; /** * User defined callback function, triggered while scrolling */ whileScrolling?: () => void; /** * Set the behavior of calling onTotalScroll and onTotalScrollBack offsets. * By default, callback offsets will trigger repeatedly while content is scrolling within the offsets. * Set alwaysTriggerOffsets: false when you need to trigger onTotalScroll and onTotalScrollBack callbacks once, each time scroll end or beginning is reached. */ alwaysTriggerOffsets?: boolean; /** * A function to call when content becomes long enough and vertical scrollbar is added. */ onOverflowY?: () => void; /** * A function to call when content becomes wide enough and horizontal scrollbar is added. */ onOverflowX?: () => void; /** * A function to call when content becomes short enough and vertical scrollbar is removed. */ onOverflowYNone?: () => void; /** * A function to call when content becomes narrow enough and horizontal scrollbar is removed. */ onOverflowXNone?: () => void; /** * A function to call right before scrollbar(s) are updated. */ onBeforeUpdate?: () => void; /** * A function to call when scrollbar(s) are updated. */ onUpdate?: () => void; /** * A function to call each time an image inside the element is fully loaded and scrollbar(s) are updated. */ onImageLoad?: () => void; /** * A function to call each time a type of element is added, removed or changes its size and scrollbar(s) are updated. */ onSelectorChange?: () => void; } /** * Set a scrollbar ready-to-use theme. See themes demo for all themes - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/scrollbar_themes_demo.html */ theme?: string; /** * Enable or disable applying scrollbar(s) on all elements matching the current selector, now and in the future. * Set live: true when you need to add scrollbar(s) on elements that do not yet exist in the page. * These could be elements added by other scripts or plugins after some action by the user takes place (e.g. lightbox markup may not exist untill the user clicks a link). * If you need at any time to disable or enable the live option, set live: "off" and "on" respectively. * You can also tell the script to disable live option after the first invocation by setting live: "once". */ live?: string|boolean; /** * Set the matching set of elements (instead of the current selector) to add scrollbar(s), now and in the future. */ liveSelector?: string; } interface ScrollToParameterOptions { /** * Scroll-to animation speed, value in milliseconds */ scrollInertia?: number; /** * Scroll-to animation easing, values: "linear", "easeOut", "easeInOut". */ scrollEasing?: string; /** * Scroll scrollbar dragger (instead of content) to a number of pixels, values: true, false */ moveDragger?: boolean; /** * Set a timeout for the method (the default timeout is 60 ms in order to work with automatic scrollbar update), value in milliseconds. */ timeout?: number; /** * Trigger user defined callback after scroll-to completes, value: true, false */ callbacks?: boolean; } } interface JQuery { /** * Calls specified methods on the scrollbar "update", "stop", "disable", "destroy" * * @param method Method name to call on scrollbar e.g. "update", "stop" */ mCustomScrollbar(method: string): JQuery; /** * Calls the scrollTo method on the scrollbar * * @param scrollTo Method name as a string "scrollTo" * @param parameter String or pixel integer value to specify where to scroll to e.g. "bottom", "top" or 20 * @param options Override default options */ mCustomScrollbar(scrollTo: string, parameter: any, options?: MCustomScrollbar.ScrollToParameterOptions): JQuery; /** * Creates a new mCustomScrollbar with the specified or default options * * @param options Override default options */ mCustomScrollbar(options?: MCustomScrollbar.CustomScrollbarOptions): JQuery; } declare module "malihu-custom-scrollbar-plugin" { var factory: MCustomScrollbar.Factory; export = factory; }
the_stack
// Import logging for electron and override default console logging import log from 'electron-log'; console.log = log.log; Object.assign(console, log.functions); import * as path from 'path'; import { app, dialog, BrowserWindow, ipcMain, shell, Menu } from 'electron'; import { environment } from './environments/environment'; // setup logger to catch all unhandled errors and submit as bug reports to our repo log.catchErrors({ showDialog: false, onError(error, versions, submitIssue) { dialog .showMessageBox({ title: 'An error occurred', message: error.message, detail: error.stack, type: 'error', buttons: ['Ignore', 'Report', 'Exit'] }) .then((result) => { if (result.response === 1) { submitIssue('https://github.com/ever-co/ever-gauzy-desktop-timer/issues/new', { title: `Automatic error report for Desktop Timer App ${versions.app}`, body: 'Error:\n```' + error.stack + '\n```\n' + `OS: ${versions.os}` }); return; } if (result.response === 2) { app.quit(); return; } return; }); } }); require('module').globalPaths.push(path.join(__dirname, 'node_modules')); require('sqlite3'); app.setName('gauzy-desktop-timer'); console.log('Node Modules Path', path.join(__dirname, 'node_modules')); const Store = require('electron-store'); import * as remoteMain from '@electron/remote/main'; remoteMain.initialize(); import { ipcMainHandler, ipcTimer, TrayIcon, LocalStore, DataModel, AppMenu } from '@gauzy/desktop-libs'; import { createSetupWindow, createTimeTrackerWindow, createSettingsWindow, createUpdaterWindow, createImageViewerWindow } from '@gauzy/desktop-window'; import { fork } from 'child_process'; import { autoUpdater } from 'electron-updater'; import { CancellationToken } from "builder-util-runtime"; import fetch from 'node-fetch'; import { initSentry } from './sentry'; initSentry(); // the folder where all app data will be stored (e.g. sqlite DB, settings, cache, etc) // C:\Users\USERNAME\AppData\Roaming\gauzy-desktop-timer process.env.GAUZY_USER_PATH = app.getPath('userData'); log.info(`GAUZY_USER_PATH: ${process.env.GAUZY_USER_PATH}`); const sqlite3filename = `${process.env.GAUZY_USER_PATH}/gauzy.sqlite3`; log.info(`Sqlite DB path: ${sqlite3filename}`); const knex = require('knex')({ client: 'sqlite3', connection: { filename: sqlite3filename }, pool: { min: 2, max: 15, createTimeoutMillis: 3000, acquireTimeoutMillis: 60 * 1000 * 2, idleTimeoutMillis: 30000, reapIntervalMillis: 1000, createRetryIntervalMillis: 100 }, useNullAsDefault: true }); const exeName = path.basename(process.execPath); const dataModel = new DataModel(); dataModel.createNewTable(knex); const store = new Store(); const args = process.argv.slice(1); const serve: boolean = args.some((val) => val === '--serve'); let gauzyWindow: BrowserWindow = null; let setupWindow: BrowserWindow = null; let timeTrackerWindow: BrowserWindow = null; let notificationWindow: BrowserWindow = null; let settingsWindow: BrowserWindow = null; let updaterWindow: BrowserWindow = null; let imageView: BrowserWindow = null; let tray = null; let isAlreadyRun = false; let willQuit = false; let onWaitingServer = false; let alreadyQuit = false; let serverGauzy = null; let serverDesktop = null; let dialogErr = false; let cancellationToken = null; try { cancellationToken = new CancellationToken(); } catch (error) {} console.log( 'Time Tracker UI Render Path:', path.join(__dirname, './index.html') ); const pathWindow = { timeTrackerUi: path.join(__dirname, './index.html') }; function startServer(value, restart = false) { try { const config: any = { ...value, isSetup: true }; const aw = { host: value.awHost, isAw: value.aw }; const projectConfig = store.get('project'); store.set({ configs: config, project: projectConfig ? projectConfig : { projectId: null, taskId: null, note: null, aw, organizationContactId: null } }); } catch (error) {} /* create main window */ if (value.serverConfigConnected || !value.isLocalServer) { setupWindow.hide(); timeTrackerWindow.destroy(); timeTrackerWindow = createTimeTrackerWindow( timeTrackerWindow, pathWindow.timeTrackerUi ); gauzyWindow = timeTrackerWindow; gauzyWindow.show(); } const auth = store.get('auth'); new AppMenu( timeTrackerWindow, settingsWindow, updaterWindow, knex, pathWindow ); if (!tray) { tray = new TrayIcon( setupWindow, knex, timeTrackerWindow, auth, settingsWindow, { ...environment }, pathWindow, path.join( __dirname, 'assets', 'icons', 'icon_16x16.png' ) ); } /* ping server before launch the ui */ ipcMain.on('app_is_init', () => { if (!isAlreadyRun && value && !restart) { onWaitingServer = true; setupWindow.webContents.send('server_ping', { host: getApiBaseUrl(value) }); } }); return true; } const dialogMessage = (msg) => { dialogErr = true; const options = { type: 'question', buttons: ['Open Setting', 'Exit'], defaultId: 2, title: 'Warning', message: msg }; dialog.showMessageBox(null, options).then((response) => { if (response.response === 1) app.quit(); else { if (settingsWindow) settingsWindow.show(); else { if (!settingsWindow) { settingsWindow = createSettingsWindow( settingsWindow, pathWindow.timeTrackerUi ); } settingsWindow.show(); setTimeout(() => { settingsWindow.webContents.send('app_setting', LocalStore.getApplicationConfig()); }, 500); } } }); }; const getApiBaseUrl = (configs) => { if (configs.serverUrl) return configs.serverUrl; else { return configs.port ? `http://localhost:${configs.port}` : `http://localhost:${environment.API_DEFAULT_PORT}`; } }; // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. // Added 5000 ms to fix the black background issue while using transparent window. // More details at https://github.com/electron/electron/issues/15947 app.on('ready', async () => { // require(path.join(__dirname, 'desktop-api/main.js')); /* set menu */ const configs: any = store.get('configs'); if (configs && typeof configs.autoLaunch === 'undefined') { launchAtStartup(true, false); } Menu.setApplicationMenu( Menu.buildFromTemplate([ { label: app.getName(), submenu: [ { role: 'about', label: 'About' }, { type: 'separator' }, { type: 'separator' }, { role: 'quit', label: 'Exit' } ] } ]) ); /* create window */ timeTrackerWindow = createTimeTrackerWindow( timeTrackerWindow, pathWindow.timeTrackerUi ); settingsWindow = createSettingsWindow( settingsWindow, pathWindow.timeTrackerUi ); updaterWindow = createUpdaterWindow( updaterWindow, pathWindow.timeTrackerUi ); imageView = createImageViewerWindow(imageView, pathWindow.timeTrackerUi); /* Set Menu */ if (configs && configs.isSetup) { global.variableGlobal = { API_BASE_URL: getApiBaseUrl(configs), IS_INTEGRATED_DESKTOP: configs.isLocalServer }; setupWindow = createSetupWindow( setupWindow, true, pathWindow.timeTrackerUi ); startServer(configs); } else { setupWindow = createSetupWindow( setupWindow, false, pathWindow.timeTrackerUi ); setupWindow.show(); } ipcMainHandler(store, startServer, knex, { ...environment }, timeTrackerWindow); }); app.on('window-all-closed', quit); ipcMain.on('server_is_ready', () => { LocalStore.setDefaultApplicationSetting(); const appConfig = LocalStore.getStore('configs'); appConfig.serverConfigConnected = true; store.set({ configs: appConfig }); onWaitingServer = false; if (!isAlreadyRun) { serverDesktop = fork( path.join(__dirname, './desktop-api/main.js') ); ipcTimer( store, knex, setupWindow, timeTrackerWindow, notificationWindow, settingsWindow, imageView, { ...environment }, createSettingsWindow, pathWindow, path.join(__dirname, '..', 'data', 'sound', 'snapshot-sound.wav') ); isAlreadyRun = true; } }); ipcMain.on('quit', quit); ipcMain.on('minimize', () => { gauzyWindow.minimize(); }); ipcMain.on('maximize', () => { gauzyWindow.maximize(); }); ipcMain.on('restore', () => { gauzyWindow.restore(); }); ipcMain.on('restart_app', (event, arg) => { dialogErr = false; LocalStore.updateConfigSetting(arg); if (serverGauzy) serverGauzy.kill(); if (gauzyWindow) gauzyWindow.destroy(); gauzyWindow = null; isAlreadyRun = false; setTimeout(() => { if (!gauzyWindow) { const configs = LocalStore.getStore('configs'); global.variableGlobal = { API_BASE_URL: getApiBaseUrl(configs), IS_INTEGRATED_DESKTOP: configs.isLocalServer }; startServer(configs, tray ? true : false); setupWindow.webContents.send('server_ping_restart', { host: getApiBaseUrl(configs) }); } }, 100); }); ipcMain.on('save_additional_setting', (event, arg) => { LocalStore.updateAdditionalSetting(arg); }) ipcMain.on('server_already_start', () => { if (!gauzyWindow && !isAlreadyRun) { gauzyWindow = timeTrackerWindow; gauzyWindow.show(); isAlreadyRun = true; } }); ipcMain.on('open_browser', (event, arg) => { shell.openExternal(arg.url); }); ipcMain.on('check_for_update', async (event, arg) => { const updaterConfig = { repo: 'ever-gauzy-desktop-timer', owner: 'ever-co', typeRelease: 'releases' }; let latestReleaseTag = null; try { latestReleaseTag = await fetch( `https://github.com/${updaterConfig.owner}/${updaterConfig.repo}/${updaterConfig.typeRelease}/latest`, { method: 'GET', headers: { Accept: 'application/json' } } ).then((res) => res.json()); } catch (error) {} if (latestReleaseTag) { autoUpdater.setFeedURL({ channel: 'latest', provider: 'generic', url: `https://github.com/${updaterConfig.owner}/${updaterConfig.repo}/${updaterConfig.typeRelease}/download/${latestReleaseTag.tag_name}` }); autoUpdater.checkForUpdatesAndNotify().then((downloadPromise) => { if (cancellationToken) cancellationToken = downloadPromise.cancellationToken; }); } else { settingsWindow.webContents.send('error_update'); } }); autoUpdater.on('update-available', () => { settingsWindow.webContents.send('update_available'); }); autoUpdater.on('update-downloaded', () => { settingsWindow.webContents.send('update_downloaded'); }); autoUpdater.on('update-not-available', () => { settingsWindow.webContents.send('update_not_available'); }); autoUpdater.on('download-progress', (event) => { console.log('update log', event); if (settingsWindow) { settingsWindow.webContents.send('download_on_progress', event); } }); autoUpdater.on('error', (e) => { settingsWindow.webContents.send('error_update', e); }); ipcMain.on('restart_and_update', () => { setImmediate(() => { app.removeAllListeners('window-all-closed'); autoUpdater.quitAndInstall(false); if (serverDesktop) serverDesktop.kill(); if (serverGauzy) serverGauzy.kill(); app.exit(0); }); }); ipcMain.on('check_database_connection', async (event, arg) => { let databaseOptions = {}; if (arg.db == 'postgres') { databaseOptions = { client: 'pg', connection: { host: arg.dbHost, user: arg.dbUsername, password: arg.dbPassword, database: arg.dbName, port: arg.dbPort } }; } else { databaseOptions = { client: 'sqlite', connection: { filename: sqlite3filename } }; } const dbConn = require('knex')(databaseOptions); try { await dbConn.raw('select 1+1 as result'); event.sender.send('database_status', { status: true, message: arg.db === 'postgres' ? 'Connection to PostgreSQL DB Succeeds' : 'Connection to SQLITE DB Succeeds' }); } catch (error) { event.sender.send('database_status', { status: false, message: error.message }); } }); ipcMain.on('launch_on_startup', (event, arg) => { launchAtStartup(arg.autoLaunch, arg.hidden); }); ipcMain.on('minimize_on_startup', (event, arg) => { launchAtStartup(arg.autoLaunch, arg.hidden); }); autoUpdater.on('error', () => { console.log('error'); }); app.on('activate', () => { if (gauzyWindow) { if (LocalStore.getStore('configs').gauzyWindow) { gauzyWindow.show(); } } else if ( !onWaitingServer && LocalStore.getStore('configs') && LocalStore.getStore('configs').isSetup ) { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. gauzyWindow = timeTrackerWindow; gauzyWindow.show(); } else { if (setupWindow) { setupWindow.show(); } } }); app.on('before-quit', (e) => { e.preventDefault(); const appSetting = LocalStore.getStore('appSetting'); if (appSetting && appSetting.timerStarted) { e.preventDefault(); setTimeout(() => { willQuit = true; timeTrackerWindow.webContents.send('stop_from_tray', { quitApp: true }); }, 1000); } else { if (cancellationToken) { cancellationToken.cancel(); } app.exit(0); if (serverDesktop) serverDesktop.kill(); if (serverGauzy) serverGauzy.kill(); } }); // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q function quit() { if (process.platform !== 'darwin') { app.quit(); } } function launchAtStartup(autoLaunch, hidden) { switch (process.platform) { case 'darwin': app.setLoginItemSettings({ openAtLogin: autoLaunch, openAsHidden: hidden }); break; case 'win32': app.setLoginItemSettings({ openAtLogin: autoLaunch, openAsHidden: hidden, path: app.getPath('exe'), args: hidden ? [ '--processStart', `"${exeName}"`, '--process-start-args', `"--hidden"` ] : ['--processStart', `"${exeName}"`, '--process-start-args'] }); break; case 'linux': app.setLoginItemSettings({ openAtLogin: autoLaunch, openAsHidden: hidden }); break; default: break; } }
the_stack
import { DecimalPipe } from '@angular/common'; import { Host, Injectable } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; import { of, Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { _HttpClient, CNCurrencyPipe, DatePipe, YNPipe } from '@delon/theme'; import { deepGet } from '@delon/util'; import { STSortMap } from './table-column-source'; import { STColumn, STData, STMultiSort, STPage, STReq, STRequestOptions, STRes, STRowClassName, STSingleSort, STStatistical, STStatisticalResult, STStatisticalResults, STStatisticalType, } from './table.interfaces'; export interface STDataSourceOptions { pi?: number; ps?: number; data?: string | STData[] | Observable<STData[]>; total?: number; req?: STReq; res?: STRes; page?: STPage; columns?: STColumn[]; singleSort?: STSingleSort; multiSort?: STMultiSort; rowClassName?: STRowClassName; } export interface STDataSourceResult { /** 是否需要显示分页器 */ pageShow?: boolean; /** 新 `pi`,若返回 `undefined` 表示用户受控 */ pi?: number; /** 新 `ps`,若返回 `undefined` 表示用户受控 */ ps?: number; /** 新 `total`,若返回 `undefined` 表示用户受控 */ total?: number; /** 数据 */ list?: STData[]; /** 统计数据 */ statistical?: STStatisticalResults; } @Injectable() export class STDataSource { private sortTick = 0; constructor( private http: _HttpClient, @Host() private currentyPipe: CNCurrencyPipe, @Host() private datePipe: DatePipe, @Host() private ynPipe: YNPipe, @Host() private numberPipe: DecimalPipe, private dom: DomSanitizer, ) {} process(options: STDataSourceOptions): Promise<STDataSourceResult> { return new Promise((resolvePromise, rejectPromise) => { let data$: Observable<STData[]>; let isRemote = false; const { data, res, total, page, pi, ps, columns } = options; let retTotal: number; let retPs: number; let retList: STData[]; let retPi: number; let showPage = page.show; if (typeof data === 'string') { isRemote = true; data$ = this.getByHttp(data, options).pipe( map(result => { let ret: STData[]; if (Array.isArray(result)) { ret = result; retTotal = ret.length; retPs = retTotal; showPage = false; } else { // list ret = deepGet(result, res.reName.list as string[], []); if (ret == null || !Array.isArray(ret)) { ret = []; } // total const resultTotal = res.reName.total && deepGet(result, res.reName.total as string[], null); retTotal = resultTotal == null ? total || 0 : +resultTotal; } return ret; }), catchError(err => { rejectPromise(err); return []; }), ); } else if (Array.isArray(data)) { data$ = of(data); } else { // a cold observable data$ = data; } if (!isRemote) { data$ = data$.pipe( // sort map((result: STData[]) => { let copyResult = result.slice(0); const sorterFn = this.getSorterFn(columns); if (sorterFn) { copyResult = copyResult.sort(sorterFn); } return copyResult; }), // filter map((result: STData[]) => { columns .filter(w => w.filter) .forEach(c => { const values = c.filter.menus.filter(w => w.checked); if (values.length === 0) return; const onFilter = c.filter.fn; if (typeof onFilter !== 'function') { console.warn(`[st] Muse provide the fn function in filter`); return; } result = result.filter(record => values.some(v => onFilter(v, record))); }); return result; }), // paging map((result: STData[]) => { if (page.front) { const maxPageIndex = Math.ceil(result.length / ps); retPi = Math.max(1, pi > maxPageIndex ? maxPageIndex : pi); retTotal = result.length; if (page.show === true) { return result.slice((retPi - 1) * ps, retPi * ps); } } return result; }), ); } // pre-process if (typeof res.process === 'function') { data$ = data$.pipe(map(result => res.process(result))); } // data accelerator data$ = data$.pipe( map(result => { for (let i = 0, len = result.length; i < len; i++) { result[i]._values = columns.map(c => this.get(result[i], c, i)); if (options.rowClassName) { result[i]._rowClassName = options.rowClassName(result[i], i); } } return result; }), ); data$ .forEach((result: STData[]) => (retList = result)) .then(() => { const realTotal = retTotal || total; const realPs = retPs || ps; resolvePromise({ pi: retPi, ps: retPs, total: retTotal, list: retList, statistical: this.genStatistical(columns, retList), pageShow: typeof showPage === 'undefined' ? realTotal > realPs : showPage, }); }); }); } private get(item: STData, col: STColumn, idx: number): { text: any; org?: any } { if (col.format) { const formatRes = col.format(item, col); if (formatRes && ~formatRes.indexOf('</')) { return { text: this.dom.bypassSecurityTrustHtml(formatRes), org: formatRes }; } return { text: formatRes == null ? '' : formatRes, org: formatRes }; } const value = deepGet(item, col.index as string[], col.default); let ret = value; switch (col.type) { case 'no': ret = this.getNoIndex(item, col, idx); break; case 'img': ret = value ? `<img src="${value}" class="img">` : ''; break; case 'number': ret = this.numberPipe.transform(value, col.numberDigits); break; case 'currency': ret = this.currentyPipe.transform(value); break; case 'date': ret = this.datePipe.transform(value, col.dateFormat); break; case 'yn': ret = this.ynPipe.transform(value === col.yn.truth, col.yn.yes, col.yn.no); break; } return { text: ret == null ? '' : ret, org: value }; } private getByHttp(url: string, options: STDataSourceOptions): Observable<{}> { const { req, page, pi, ps, singleSort, multiSort, columns } = options; const method = (req.method || 'GET').toUpperCase(); let params = {}; if (req.type === 'page') { params = { [req.reName.pi]: page.zeroIndexed ? pi - 1 : pi, [req.reName.ps]: ps, }; } else { params = { [req.reName.skip]: (pi - 1) * ps, [req.reName.limit]: ps, }; } params = { ...params, ...req.params, ...this.getReqSortMap(singleSort, multiSort, columns), ...this.getReqFilterMap(columns), }; let reqOptions: STRequestOptions = { params, body: req.body, headers: req.headers, }; if (method === 'POST' && req.allInBody === true) { reqOptions = { body: { ...req.body, ...params }, headers: req.headers, }; } if (typeof req.process === 'function') { reqOptions = req.process(reqOptions); } return this.http.request(method, url, reqOptions); } getNoIndex(item: STData, col: STColumn, idx: number): number { return typeof col.noIndex === 'function' ? col.noIndex(item, col, idx) : col.noIndex + idx; } // #region sort private getValidSort(columns: STColumn[]): STSortMap[] { return columns .filter(item => item._sort && item._sort.enabled && item._sort.default) .map(item => item._sort); } private getSorterFn(columns: STColumn[]) { const sortList = this.getValidSort(columns); if (sortList.length === 0) { return; } if (typeof sortList[0].compare !== 'function') { console.warn(`[st] Muse provide the compare function in sort`); return; } return (a: STData, b: STData) => { const result = sortList[0].compare(a, b); if (result !== 0) { return sortList[0].default === 'descend' ? -result : result; } return 0; }; } get nextSortTick(): number { return ++this.sortTick; } getReqSortMap( singleSort: STSingleSort, multiSort: STMultiSort, columns: STColumn[], ): { [key: string]: string } { let ret: { [key: string]: string } = {}; const sortList = this.getValidSort(columns); if (!multiSort && sortList.length === 0) return ret; if (multiSort) { const ms = { key: 'sort', separator: '-', nameSeparator: '.', ...multiSort, }; ret = { [ms.key]: sortList.sort((a, b) => a.tick - b.tick) .map(item => item.key + ms.nameSeparator + ((item.reName || {})[item.default] || item.default)) .join(ms.separator), }; } else { const mapData = sortList[0]; let sortFiled = mapData.key; let sortValue = (sortList[0].reName || {})[mapData.default] || mapData.default; if (singleSort) { sortValue = sortFiled + (singleSort.nameSeparator || '.') + sortValue; sortFiled = singleSort.key || 'sort'; } ret[sortFiled] = sortValue; } return ret; } // #endregion // #region filter private getReqFilterMap(columns: STColumn[]): { [key: string]: string } { let ret = {}; columns .filter(w => w.filter && w.filter.default === true) .forEach(col => { const values = col.filter.menus.filter(f => f.checked === true); let obj: {} = {}; if (col.filter.reName) { obj = col.filter.reName(col.filter.menus, col); } else { obj[col.filter.key] = values.map(i => i.value).join(','); } ret = { ...ret, ...obj }; }); return ret; } // #endregion // #region statistical private genStatistical(columns: STColumn[], list: STData[]): STStatisticalResults { const res = {}; columns.forEach((col, index) => { res[col.key ? col.key : index] = col.statistical == null ? {} : this.getStatistical(col, index, list); }); return res; } private getStatistical(col: STColumn, index: number, list: STData[]): STStatisticalResult { const val = col.statistical; const item: STStatistical = { digits: 2, currenty: null, ...(typeof val === 'string' ? { type: val as STStatisticalType } : (val as STStatistical)), }; let res: STStatisticalResult = { value: 0 }; let currenty = false; if (typeof item.type === 'function') { res = item.type(this.getValues(index, list), col, list); currenty = true; } else { switch (item.type) { case 'count': res.value = list.length; break; case 'distinctCount': res.value = this.getValues(index, list).filter( (value, idx, self) => self.indexOf(value) === idx, ).length; break; case 'sum': res.value = this.toFixed(this.getSum(index, list), item.digits); currenty = true; break; case 'average': res.value = this.toFixed(this.getSum(index, list) / list.length, item.digits); currenty = true; break; case 'max': res.value = Math.max(...this.getValues(index, list)); currenty = true; break; case 'min': res.value = Math.min(...this.getValues(index, list)); currenty = true; break; } } if (item.currenty === true || (item.currenty == null && currenty === true)) { res.text = this.currentyPipe.transform(res.value); } else { res.text = String(res.value); } return res; } private toFixed(val: number, digits: number): number { if (isNaN(val) || !isFinite(val)) { return 0; } return parseFloat(val.toFixed(digits)); } private getValues(index: number, list: STData[]): number[] { return list.map(i => i._values[index].org).map(i => (i === '' || i == null ? 0 : i)); } private getSum(index: number, list: STData[]): number { return this.getValues(index, list).reduce((p, i) => (p += parseFloat(String(i))), 0); } // #endregion }
the_stack
import assert = require("assert"); import https = require("https"); import sinon = require("sinon"); import nock = require("nock"); import Sender = require("../../Library/Sender"); import Config = require("../../Library/Config"); import Constants = require("../../Declarations/Constants"); import Contracts = require("../../Declarations/Contracts"); import AuthorizationHandler = require("../../Library/AuthorizationHandler"); import Util = require("../../Library/Util"); import Statsbeat = require("../../AutoCollection/Statsbeat"); import Logging = require("../../Library/Logging"); import { FileAccessControl } from "../../Library/FileAccessControl"; import FileSystemHelper = require("../../Library/FileSystemHelper"); class SenderMock extends Sender { public getResendInterval() { return this._resendInterval; } } describe("Library/Sender", () => { Util.tlsRestrictedAgent = new https.Agent(); var testEnvelope = new Contracts.Envelope(); var sandbox: sinon.SinonSandbox; let interceptor: nock.Interceptor; let nockScope: nock.Scope; before(() => { interceptor = nock(Constants.DEFAULT_BREEZE_ENDPOINT) .post("/v2.1/track", (body: string) => { return true; }); }); beforeEach(() => { sandbox = sinon.sandbox.create(); }); afterEach(() => { sandbox.restore(); if (nockScope && nockScope.restore) { nockScope.restore(); } }); after(() => { nock.cleanAll(); }); describe("#send(envelope)", () => { var sender: Sender; before(() => { sender = new Sender(new Config("2bb22222-bbbb-1ccc-8ddd-eeeeffff3333")); FileAccessControl.USE_ICACLS = false; sender.setDiskRetryMode(true); }); after(() => { FileAccessControl["USE_ICACLS"] = true; sender.setDiskRetryMode(false); }); it("should not crash JSON.stringify", () => { var a = <any>{ b: null }; a.b = a; var warnStub = sandbox.stub(Logging, "warn"); assert.doesNotThrow(() => sender.send([a])); assert.ok(warnStub.calledOnce); }); it("should try to send telemetry from disk when 200", (done) => { var breezeResponse: Contracts.BreezeResponse = { itemsAccepted: 1, itemsReceived: 1, errors: [] }; let diskEnvelope = new Contracts.Envelope(); diskEnvelope.name = "DiskEnvelope"; sender["_storeToDisk"]([diskEnvelope]); var sendSpy = sandbox.spy(sender, "send"); nockScope = interceptor.reply(200, breezeResponse); nockScope.persist(); sender["_resendInterval"] = 100; sender.send([testEnvelope], (responseText) => { // Wait for resend timer setTimeout(() => { assert.ok(sendSpy.calledTwice); assert.equal(sendSpy.secondCall.args[0][0].name, "DiskEnvelope"); done(); }, 200) }); }); it("should put telemetry in disk when retryable code is returned", (done) => { var envelope = new Contracts.Envelope(); envelope.name = "TestRetryable"; nockScope = interceptor.reply(408, null); var storeStub = sandbox.stub(sender, "_storeToDisk"); sender.send([envelope], (responseText) => { assert.ok(storeStub.calledOnce); assert.equal(storeStub.firstCall.args[0][0].name, "TestRetryable"); done(); }); }); it("should retry only failed events in partial content response", (done) => { var breezeResponse: Contracts.BreezeResponse = { itemsAccepted: 2, itemsReceived: 4, errors: [{ index: 0, statusCode: 408, message: "" }, { index: 2, statusCode: 123, message: "" }] }; var envelopes = []; for (var i = 0; i < 4; i++) { var newEnvelope = new Contracts.Envelope(); newEnvelope.name = "TestPartial" + i; envelopes.push(newEnvelope); } nockScope = interceptor.reply(206, breezeResponse); var storeStub = sandbox.stub(sender, "_storeToDisk"); sender.send(envelopes, () => { assert.ok(storeStub.calledOnce); assert.equal(storeStub.firstCall.args[0].length, 1); assert.equal(storeStub.firstCall.args[0][0].name, "TestPartial0"); done(); }); }); }); describe("#setOfflineMode(value, resendInterval)", () => { var sender: SenderMock; beforeEach(() => { sender = new SenderMock(new Config("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333")); }); after(() => { sender.setDiskRetryMode(false); }); it("default resend interval is 60 seconds", () => { sender.setDiskRetryMode(true); assert.equal(Sender.WAIT_BETWEEN_RESEND, sender.getResendInterval()); }); it("resend interval can be configured", () => { sender.setDiskRetryMode(true, 0); assert.equal(0, sender.getResendInterval()); sender.setDiskRetryMode(true, 1234); assert.equal(1234, sender.getResendInterval()); sender.setDiskRetryMode(true, 1234.56); assert.equal(1234, sender.getResendInterval()); }); it("resend interval can't be negative", () => { sender.setDiskRetryMode(true, -1234); assert.equal(Sender.WAIT_BETWEEN_RESEND, sender.getResendInterval()); }); }); describe("#endpoint redirect", () => { it("should change ingestion endpoint when redirect response code is returned (308)", (done) => { let redirectHost = "https://test"; let redirectLocation = redirectHost + "/v2.1/track"; // Fake redirect endpoint let redirectInterceptor = nock(redirectHost) .post("/v2.1/track", (body: string) => { return true; }); redirectInterceptor.reply(200, {}); nockScope = interceptor.reply(308, {}, { "Location": redirectLocation }); var testSender = new Sender(new Config("2bb22222-bbbb-1ccc-8ddd-eeeeffff3333")); var sendSpy = sandbox.spy(testSender, "send"); testSender.send([testEnvelope], (responseText) => { assert.equal(testSender["_redirectedHost"], redirectLocation); assert.ok(sendSpy.callCount === 2); // Original and redirect calls done(); }); }); it("should change ingestion endpoint when temporary redirect response code is returned (307)", (done) => { let redirectHost = "https://test"; let redirectLocation = redirectHost + "/v2.1/track"; // Fake redirect endpoint let redirectInterceptor = nock(redirectHost) .post("/v2.1/track", (body: string) => { return true; }); redirectInterceptor.reply(200, {}); nockScope = interceptor.reply(307, {}, { "Location": redirectLocation }); var testSender = new Sender(new Config("2bb22222-bbbb-1ccc-8ddd-eeeeffff3333")); var sendSpy = sandbox.spy(testSender, "send"); testSender.send([testEnvelope], (responseText) => { assert.equal(testSender["_redirectedHost"], redirectLocation); assert.ok(sendSpy.callCount === 2); // Original and redirect calls done(); }); }); it("should not change ingestion endpoint if redirect is not triggered", (done) => { nockScope = interceptor.reply(200, {}, { "Location": "testLocation" }); var testSender = new Sender(new Config("2bb22222-bbbb-1ccc-8ddd-eeeeffff3333")); testSender.send([testEnvelope], (responseText) => { assert.equal(testSender["_redirectedHost"], null); done(); }); }); it("should use redirect URL for following requests", (done) => { let redirectHost = "https://testlocation"; let redirectLocation = redirectHost + "/v2.1/track"; // Fake redirect endpoint let redirectInterceptor = nock(redirectHost) .post("/v2.1/track", (body: string) => { return true; }); redirectInterceptor.reply(200, { "redirectProperty": true }).persist(); nockScope = interceptor.reply(308, {}, { "Location": redirectLocation }); var testSender = new Sender(new Config("2bb22222-bbbb-1ccc-8ddd-eeeeffff3333")); var sendSpy = sandbox.spy(testSender, "send"); testSender.send([testEnvelope], (resposneText) => { assert.equal(testSender["_redirectedHost"], redirectLocation); assert.equal(resposneText, '{"redirectProperty":true}'); assert.ok(sendSpy.calledTwice); testSender.send([testEnvelope], (secondResponseText) => { assert.equal(secondResponseText, '{"redirectProperty":true}'); assert.ok(sendSpy.calledThrice); done(); }); }); }); it("should stop redirecting when circular redirect is triggered", (done) => { let redirectHost = "https://circularredirect"; // Fake redirect endpoint let redirectInterceptor = nock(redirectHost) .post("/v2.1/track", (body: string) => { return true; }); redirectInterceptor.reply(307, {}, { "Location": Constants.DEFAULT_BREEZE_ENDPOINT + "/v2.1/track" }).persist(); nockScope = interceptor.reply(307, {}, { "Location": redirectHost + "/v2.1/track" }); var testSender = new Sender(new Config("2bb22222-bbbb-1ccc-8ddd-eeeeffff3333")); var sendSpy = sandbox.spy(testSender, "send"); testSender.send([testEnvelope], (responseText) => { assert.equal(responseText, "Error sending telemetry because of circular redirects."); assert.equal(sendSpy.callCount, 10); done(); }); }); }); describe("#fileCleanupTask", () => { var sender: Sender; after(() => { FileAccessControl["USE_ICACLS"] = true; sender.setDiskRetryMode(false); }); it("must clean old files from temp location", (done) => { var deleteSpy = sandbox.spy(FileSystemHelper, "unlinkAsync"); sender = new Sender(new Config("3bb33333-bbbb-1ccc-8ddd-eeeeffff3333")); FileAccessControl["USE_ICACLS"] = false; (<any>sender.constructor).CLEANUP_TIMEOUT = 500; (<any>sender.constructor).FILE_RETEMPTION_PERIOD = 1; var taskSpy = sandbox.spy(sender, "_fileCleanupTask"); sender.setDiskRetryMode(true); let diskEnvelope = new Contracts.Envelope(); diskEnvelope.name = "DiskEnvelope"; sender["_storeToDisk"]([diskEnvelope]); setTimeout(() => { assert.ok(taskSpy.calledOnce); assert.ok(deleteSpy.called); done(); }, 600); }); }); describe("#AuthorizationHandler ", () => { before(() => { nock("https://dc.services.visualstudio.com") .post("/v2.1/track", (body: string) => { return true; }) .reply(200, { itemsAccepted: 1, itemsReceived: 1, errors: [] }) .persist(); }); var sandbox: sinon.SinonSandbox; beforeEach(() => { sandbox = sinon.sandbox.create(); }); afterEach(() => { sandbox.restore(); }); after(() => { nock.cleanAll(); }); it("should add token if handler present", () => { var handler = new AuthorizationHandler({ async getToken(scopes: string | string[], options?: any): Promise<any> { return { token: "testToken", }; } }); var getAuthorizationHandler = () => { return handler; }; var config = new Config("InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"); var addHeaderStub = sandbox.stub(handler, "addAuthorizationHeader"); var sender = new Sender(config, getAuthorizationHandler); sender.send([testEnvelope]); assert.ok(addHeaderStub.calledOnce); }); it("should put telemetry to disk if auth fails", () => { var handler = new AuthorizationHandler({ async getToken(scopes: string | string[], options?: any): Promise<any> { return { token: "testToken", }; } }); var getAuthorizationHandler = () => { return handler; }; var config = new Config("InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeffff3333;"); var addHeaderStub = sandbox.stub(handler, "addAuthorizationHeader", () => { throw new Error(); }); var sender = new Sender(config, getAuthorizationHandler); sender["_enableDiskRetryMode"] = true; var storeToDiskStub = sandbox.stub(sender, "_storeToDisk"); let envelope = new Contracts.Envelope(); envelope.name = "TestEnvelope"; sender.send([envelope]); assert.ok(addHeaderStub.calledOnce); assert.ok(storeToDiskStub.calledOnce); assert.equal(storeToDiskStub.firstCall.args[0][0].name, "TestEnvelope"); }); }); describe("#Statsbeat counters", () => { Statsbeat.NON_EU_CONNECTION_STRING = "InstrumentationKey=2aa22222-bbbb-1ccc-8ddd-eeeeffff3333;" var breezeResponse: Contracts.BreezeResponse = { itemsAccepted: 1, itemsReceived: 1, errors: [] }; let config = new Config("2bb22222-bbbb-1ccc-8ddd-eeeeffff3333"); let statsbeat = new Statsbeat(config); let statsbeatSender = new Sender(config, null, null, null, statsbeat); it("Succesful requests", (done) => { var statsbeatSpy = sandbox.spy(statsbeat, "countRequest"); nockScope = interceptor.reply(200, breezeResponse); statsbeatSender.send([testEnvelope], () => { assert.ok(statsbeatSpy.calledOnce); assert.equal(statsbeatSpy.args[0][0], 0); // Category assert.equal(statsbeatSpy.args[0][1], "dc.services.visualstudio.com"); // Endpoint assert.ok(!isNaN(statsbeatSpy.args[0][2])); // Duration assert.equal(statsbeatSpy.args[0][3], true); // Success done(); }); }); it("Failed requests", (done) => { var statsbeatSpy = sandbox.spy(statsbeat, "countRequest"); nockScope = interceptor.reply(400, breezeResponse); statsbeatSender.send([testEnvelope], () => { assert.ok(statsbeatSpy.calledOnce); assert.equal(statsbeatSpy.args[0][0], 0); // Category assert.equal(statsbeatSpy.args[0][1], "dc.services.visualstudio.com"); // Endpoint assert.ok(!isNaN(statsbeatSpy.args[0][2])); // Duration assert.equal(statsbeatSpy.args[0][3], false); // Failed done(); }); }); it("Retry counts", (done) => { statsbeatSender.setDiskRetryMode(true); var statsbeatSpy = sandbox.spy(statsbeat, "countRequest"); var retrySpy = sandbox.spy(statsbeat, "countRetry"); nockScope = interceptor.reply(206, breezeResponse); statsbeatSender.send([testEnvelope], () => { assert.ok(statsbeatSpy.calledOnce); assert.ok(retrySpy.calledOnce); done(); }); }); it("Throttle counts", (done) => { statsbeatSender.setDiskRetryMode(true); var statsbeatSpy = sandbox.spy(statsbeat, "countRequest"); var throttleSpy = sandbox.spy(statsbeat, "countThrottle"); nockScope = interceptor.reply(439, breezeResponse); statsbeatSender.send([testEnvelope], () => { assert.ok(statsbeatSpy.notCalled); assert.ok(throttleSpy.calledOnce); done(); }); }); it("[Statsbeat Sender] should not turn Statsbeat off succesfully reaching ingestion endpoint at least once", (done) => { var config = new Config("InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"); let shutdownCalled = false; let shutdown = () => { shutdownCalled = true; }; nockScope = interceptor.reply(200, breezeResponse); let testSender = new Sender(config, null, null, null, null, true, shutdown); assert.equal(testSender["_statsbeatHasReachedIngestionAtLeastOnce"], false); testSender.setDiskRetryMode(false); testSender.send([testEnvelope], (responseText) => { assert.equal(testSender["_statsbeatHasReachedIngestionAtLeastOnce"], true); nockScope = interceptor.reply(503, null); testSender.send([testEnvelope], (responseText) => { assert.equal(shutdownCalled, false); testSender.send([testEnvelope], (responseText) => { assert.equal(shutdownCalled, false); testSender.send([testEnvelope], (responseText) => { assert.equal(shutdownCalled, false); done(); }); }); }); }); }); it("[Statsbeat Sender] should turn Statsbeat off if there are 3 failures after initialization", (done) => { var config = new Config("InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"); let shutdownCalled = false; let shutdown = () => { shutdownCalled = true; }; let testSender = new Sender(config, null, null, null, null, true, shutdown); testSender.setDiskRetryMode(false); nockScope = interceptor.reply(503, null); testSender.send([testEnvelope], (responseText) => { assert.equal(shutdownCalled, false); assert.equal(testSender["_failedToIngestCounter"], 1); testSender.send([testEnvelope], (responseText) => { assert.equal(shutdownCalled, false); assert.equal(testSender["_failedToIngestCounter"], 2); testSender.send([testEnvelope], (responseText) => { assert.equal(testSender["_failedToIngestCounter"], 3); assert.equal(shutdownCalled, true); done(); }); }); }); }); it("[Statsbeat Sender] should turn off warn logging", (done) => { var config = new Config("InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"); let testSender = new Sender(config, null, null, null, null, true, () => { }); testSender.setDiskRetryMode(true); let warntub = sandbox.stub(Logging, "warn"); nockScope = interceptor.replyWithError("Test Error"); testSender.send([testEnvelope], (responseText) => { assert.ok(warntub.notCalled); assert.equal(testSender["_failedToIngestCounter"], 1); done(); }); }); it("[Statsbeat Sender] should turn off info logging", (done) => { var config = new Config("InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"); let testSender = new Sender(config, null, null, null, null, true, () => { }); testSender.setDiskRetryMode(false); let infoStub = sandbox.stub(Logging, "info"); nockScope = interceptor.replyWithError("Test Error"); testSender.send([testEnvelope], (responseText) => { assert.ok(infoStub.notCalled); assert.equal(testSender["_failedToIngestCounter"], 1); done(); }); }); it("Exception counts", (done) => { statsbeatSender.setDiskRetryMode(false); var statsbeatSpy = sandbox.spy(statsbeat, "countRequest"); var exceptionSpy = sandbox.spy(statsbeat, "countException"); nockScope = interceptor.replyWithError("Test Error"); statsbeatSender.send([testEnvelope], () => { assert.equal(statsbeatSpy.callCount, 0); assert.ok(exceptionSpy.calledOnce); done(); }); }); }); });
the_stack
let hash = require('hash.js') let cryptojs = require('crypto-js') import * as forge from 'node-forge' import * as OrderedJson from './ordered-json' export function sameObjects(a, b) { return OrderedJson.stringify(a) == OrderedJson.stringify(b) } export const EMPTY_PAYLOAD_SHA = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' export async function hashString(value: string): Promise<string> { var md = forge.md.sha256.create(); md.update(value); return md.digest().toHex() /*if (value === "") return EMPTY_PAYLOAD_SHA return hash.sha256().update(value).digest('hex')*/ } export function hashStringSync(value: string): string { var md = forge.md.sha256.create(); md.update(value); return md.digest().toHex() /* if (value === "") return EMPTY_PAYLOAD_SHA return hash.sha256().update(value).digest('hex') */ } export function encryptAes(data: any, secret: string) { return cryptojs.AES.encrypt(JSON.stringify(data), secret).toString() } export function decryptAes(data: string, secret: string) { const bytes = cryptojs.AES.decrypt(data, secret) return JSON.parse(bytes.toString(cryptojs.enc.Utf8)) } export async function generateRsaKeyPair() { return new Promise<{ privateKey: string; publicKey: string }>((resolve, reject) => { const rsa = forge.pki.rsa try { // should be 2048 ! rsa.generateKeyPair({ bits: 512, workers: 2 }, (err, keyPair) => { if (err) { reject(err) return } resolve({ privateKey: forge.pki.privateKeyToPem(keyPair.privateKey), publicKey: forge.pki.publicKeyToPem(keyPair.publicKey) }) }) } catch (err) { reject(err) } }) } export function encryptAesEx(data: any, key) { //data = forge.util.encode64(JSON.stringify(data)) let dataUtf8 = strToUTF8Arr(OrderedJson.stringify(data)) let dataBase64 = base64EncArr(dataUtf8) var iv = forge.random.getBytesSync(16) var cipher = forge.cipher.createCipher('AES-CBC', key) cipher.start({ iv }) cipher.update(forge.util.createBuffer(dataBase64)) cipher.finish() const result = JSON.stringify({ iv: forge.util.encode64(iv), encrypted: forge.util.encode64(cipher.output.getBytes()) }) // assert if (!sameObjects(decryptAesEx(result, key), data)) console.error(`error aes !`) return result } export function decryptAesEx(encrypted: string, key) { let obj = JSON.parse(encrypted) let data = forge.util.createBuffer(forge.util.decode64(obj.encrypted)) let iv = forge.util.createBuffer(forge.util.decode64(obj.iv)) var decipher = forge.cipher.createDecipher('AES-CBC', key) decipher.start({ iv }) decipher.update(data) decipher.finish() let dataUtf8 = base64DecToArr(decipher.output.toString(), undefined) let dataString = UTF8ArrToStr(dataUtf8) return JSON.parse(dataString) //return JSON.parse(forge.util.decode64(decipher.output.toString())) } export function encryptHybrid(data: any, publicKeyPem: string): string { let serializedData = OrderedJson.stringify(data) var key = forge.random.getBytesSync(16) let encryptedKey = encryptRsa(key, publicKeyPem) //let encrypted = encryptAesEx(serializedData, key) let encrypted = encryptAes(serializedData, key) return JSON.stringify({ key: encryptedKey, data: encrypted }) } export function decryptHybrid(encrypted: string, privateKeyPem: string): any { let { key, data } = JSON.parse(encrypted) let decryptedKey = decryptRsa(key, privateKeyPem) //let decrypted = decryptAesEx(data, decryptedKey) let decrypted = decryptAes(data, decryptedKey) return OrderedJson.parse(decrypted) } export function encryptRsa(data: any, publicKeyPem: string): string { let publicKey = forge.pki.publicKeyFromPem(publicKeyPem) //let binaryData = clearBytes let encrypted = publicKey.encrypt(OrderedJson.stringify(data), 'RSA-OAEP') return encrypted // TODO check that it's a string } export function decryptRsa(data: string, privateKey: string): any { let pk = forge.pki.privateKeyFromPem(privateKey) let decrypted = pk.decrypt(data, 'RSA-OAEP') return OrderedJson.parse(decrypted) // TODO check decrypted is a string } export function sign(data: any, privateKeyPem: string) { let md = forge.md.sha1.create() md.update(OrderedJson.stringify(data), 'utf8') let pk = forge.pki.privateKeyFromPem(privateKeyPem) let signature = forge.util.encode64(pk.sign(md)) return signature } export function verify(data: any, signature: string, publicKeyPem: string) { var md = forge.md.sha1.create() md.update(OrderedJson.stringify(data), 'utf8') let pk = forge.pki.publicKeyFromPem(publicKeyPem) let verified = pk.verify(md.digest().bytes(), forge.util.decode64(signature)) return verified } export interface SignedAndPackedData { } interface SignedAndPackedDataInternal extends SignedAndPackedData { body: any proof: { signature: string publicKey: string } } export function signAndPackData(data: object | string | number | boolean, privateKeyPem: string) { var md = forge.md.sha1.create() md.update(OrderedJson.stringify(data), 'utf8') let privateKey = forge.pki.privateKeyFromPem(privateKeyPem) let signature = forge.util.encode64(privateKey.sign(md)) let publicKey = forge.pki.setRsaPublicKey(privateKey.n, privateKey.e) let publicKeyPem = forge.pki.publicKeyToPem(publicKey) let result: SignedAndPackedDataInternal = { body: data, proof: { signature, publicKey: publicKeyPem } } return result as any } export function verifyPackedData(data: object) { if (!data || !data["body"] || !data["proof"]) return false let packedData = JSON.parse(JSON.stringify(data)) as SignedAndPackedDataInternal return verify(packedData.body, packedData.proof.signature, packedData.proof.publicKey) } export function extractPackedDataBody(data: object): any { if (!data || !data["body"] || !data["proof"]) return undefined return data["body"] } export function extractPackedDataSignature(data: object): string { if (!data || !data["body"] || !data["proof"]) return undefined return (JSON.parse(JSON.stringify(data)) as SignedAndPackedDataInternal).proof.signature } export function extractPackedDataPublicKey(data: object): string { if (!data || !data["body"] || !data["proof"]) return undefined return (JSON.parse(JSON.stringify(data)) as SignedAndPackedDataInternal).proof.publicKey } "use strict"; /*\ |*| |*| utilitairezs de manipulations de chaînes base 64 / binaires / UTF-8 |*| |*| https://developer.mozilla.org/fr/docs/Décoder_encoder_en_base64 |*| \*/ /* Décoder un tableau d'octets depuis une chaîne en base64 */ function b64ToUint6(nChr) { return nChr > 64 && nChr < 91 ? nChr - 65 : nChr > 96 && nChr < 123 ? nChr - 71 : nChr > 47 && nChr < 58 ? nChr + 4 : nChr === 43 ? 62 : nChr === 47 ? 63 : 0; } function base64DecToArr(sBase64, nBlocksSize) { var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length, nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen); for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) { nMod4 = nInIdx & 3; nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4; if (nMod4 === 3 || nInLen - nInIdx === 1) { for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++ , nOutIdx++) { taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255; } nUint24 = 0; } } return taBytes; } /* encodage d'un tableau en une chaîne en base64 */ function uint6ToB64(nUint6) { return nUint6 < 26 ? nUint6 + 65 : nUint6 < 52 ? nUint6 + 71 : nUint6 < 62 ? nUint6 - 4 : nUint6 === 62 ? 43 : nUint6 === 63 ? 47 : 65; } function base64EncArr(aBytes) { var nMod3 = 2, sB64Enc = ""; for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { nMod3 = nIdx % 3; if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; } nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); if (nMod3 === 2 || aBytes.length - nIdx === 1) { sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63)); nUint24 = 0; } } return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '=='); } /* Tableau UTF-8 en DOMString et vice versa */ function UTF8ArrToStr(aBytes) { var sView = ""; for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) { nPart = aBytes[nIdx]; sView += String.fromCharCode( nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */ /* (nPart - 252 << 32) n'est pas possible pour ECMAScript donc, on utilise un contournement... : */ (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */ (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */ (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */ (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */ (nPart - 192 << 6) + aBytes[++nIdx] - 128 : /* nPart < 127 ? */ /* one byte */ nPart ); } return sView; } function strToUTF8Arr(sDOMStr) { var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0; /* mapping... */ for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) { nChr = sDOMStr.charCodeAt(nMapIdx); nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6; } aBytes = new Uint8Array(nArrLen); /* transcription... */ for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) { nChr = sDOMStr.charCodeAt(nChrIdx); if (nChr < 128) { /* one byte */ aBytes[nIdx++] = nChr; } else if (nChr < 0x800) { /* two bytes */ aBytes[nIdx++] = 192 + (nChr >>> 6); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x10000) { /* three bytes */ aBytes[nIdx++] = 224 + (nChr >>> 12); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x200000) { /* four bytes */ aBytes[nIdx++] = 240 + (nChr >>> 18); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x4000000) { /* five bytes */ aBytes[nIdx++] = 248 + (nChr >>> 24); aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else /* if (nChr <= 0x7fffffff) */ { /* six bytes */ aBytes[nIdx++] = 252 + /* (nChr >>> 32) is not possible in ECMAScript! So...: */ (nChr / 1073741824); aBytes[nIdx++] = 128 + (nChr >>> 24 & 63); aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } } return aBytes; }
the_stack
import { ItemEventData } from '.'; import { ListViewBase, separatorColorProperty, itemTemplatesProperty, iosEstimatedRowHeightProperty } from './list-view-common'; import { CoreTypes } from '../../core-types'; import { View, KeyedTemplate } from '../core/view'; import { Length } from '../styling/style-properties'; import { Observable, EventData } from '../../data/observable'; import { Color } from '../../color'; import { layout } from '../../utils'; import { StackLayout } from '../layouts/stack-layout'; import { ProxyViewContainer } from '../proxy-view-container'; import { profile } from '../../profiling'; import { Trace } from '../../trace'; export * from './list-view-common'; const ITEMLOADING = ListViewBase.itemLoadingEvent; const LOADMOREITEMS = ListViewBase.loadMoreItemsEvent; const ITEMTAP = ListViewBase.itemTapEvent; const DEFAULT_HEIGHT = 44; const infinity = layout.makeMeasureSpec(0, layout.UNSPECIFIED); interface ViewItemIndex { _listViewItemIndex?: number; } type ItemView = View & ViewItemIndex; @NativeClass class ListViewCell extends UITableViewCell { public static initWithEmptyBackground(): ListViewCell { const cell = <ListViewCell>ListViewCell.new(); // Clear background by default - this will make cells transparent cell.backgroundColor = UIColor.clearColor; return cell; } initWithStyleReuseIdentifier(style: UITableViewCellStyle, reuseIdentifier: string): this { const cell = <this>super.initWithStyleReuseIdentifier(style, reuseIdentifier); // Clear background by default - this will make cells transparent cell.backgroundColor = UIColor.clearColor; return cell; } public willMoveToSuperview(newSuperview: UIView): void { const parent = <ListView>(this.view ? this.view.parent : null); // When inside ListView and there is no newSuperview this cell is // removed from native visual tree so we remove it from our tree too. if (parent && !newSuperview) { parent._removeContainer(this); } } public get view(): View { return this.owner ? this.owner.get() : null; } public owner: WeakRef<View>; } function notifyForItemAtIndex(listView: ListViewBase, cell: any, view: View, eventName: string, indexPath: NSIndexPath) { const args = <ItemEventData>{ eventName: eventName, object: listView, index: indexPath.row, view: view, ios: cell, android: undefined, }; listView.notify(args); return args; } @NativeClass class DataSource extends NSObject implements UITableViewDataSource { public static ObjCProtocols = [UITableViewDataSource]; private _owner: WeakRef<ListView>; public static initWithOwner(owner: WeakRef<ListView>): DataSource { const dataSource = <DataSource>DataSource.new(); dataSource._owner = owner; return dataSource; } public tableViewNumberOfRowsInSection(tableView: UITableView, section: number) { const owner = this._owner.get(); return owner && owner.items ? owner.items.length : 0; } public tableViewCellForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCell { // We call this method because ...ForIndexPath calls tableViewHeightForRowAtIndexPath immediately (before we can prepare and measure it). const owner = this._owner.get(); let cell: ListViewCell; if (owner) { const template = owner._getItemTemplate(indexPath.row); cell = <ListViewCell>(tableView.dequeueReusableCellWithIdentifier(template.key) || ListViewCell.initWithEmptyBackground()); owner._prepareCell(cell, indexPath); const cellView: View = cell.view; if (cellView && cellView.isLayoutRequired) { // Arrange cell views. We do it here instead of _layoutCell because _layoutCell is called // from 'tableViewHeightForRowAtIndexPath' method too (in iOS 7.1) and we don't want to arrange the fake cell. const width = layout.getMeasureSpecSize(owner.widthMeasureSpec); const rowHeight = owner._effectiveRowHeight; const cellHeight = rowHeight > 0 ? rowHeight : owner.getHeight(indexPath.row); cellView.iosOverflowSafeAreaEnabled = false; View.layoutChild(owner, cellView, 0, 0, width, cellHeight); } } else { cell = <ListViewCell>ListViewCell.initWithEmptyBackground(); } return cell; } } @NativeClass class UITableViewDelegateImpl extends NSObject implements UITableViewDelegate { public static ObjCProtocols = [UITableViewDelegate]; private _owner: WeakRef<ListView>; private _measureCellMap: Map<string, ListViewCell>; public static initWithOwner(owner: WeakRef<ListView>): UITableViewDelegateImpl { const delegate = <UITableViewDelegateImpl>UITableViewDelegateImpl.new(); delegate._owner = owner; delegate._measureCellMap = new Map<string, ListViewCell>(); return delegate; } public tableViewWillDisplayCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath) { const owner = this._owner.get(); if (owner && indexPath.row === owner.items.length - 1) { owner.notify(<EventData>{ eventName: LOADMOREITEMS, object: owner, }); } } public tableViewWillSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath { const cell = <ListViewCell>tableView.cellForRowAtIndexPath(indexPath); const owner = this._owner.get(); if (owner) { notifyForItemAtIndex(owner, cell, cell.view, ITEMTAP, indexPath); } return indexPath; } public tableViewDidSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath { tableView.deselectRowAtIndexPathAnimated(indexPath, true); return indexPath; } public tableViewHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number { const owner = this._owner.get(); if (!owner) { return tableView.estimatedRowHeight; } let height = owner.getHeight(indexPath.row); if (height === undefined) { // in iOS8+ after call to scrollToRowAtIndexPath:atScrollPosition:animated: this method is called before tableViewCellForRowAtIndexPath so we need fake cell to measure its content. const template = owner._getItemTemplate(indexPath.row); let cell = this._measureCellMap.get(template.key); if (!cell) { cell = <any>tableView.dequeueReusableCellWithIdentifier(template.key) || ListViewCell.initWithEmptyBackground(); this._measureCellMap.set(template.key, cell); } height = owner._prepareCell(cell, indexPath); } return layout.toDeviceIndependentPixels(height); } } @NativeClass class UITableViewRowHeightDelegateImpl extends NSObject implements UITableViewDelegate { public static ObjCProtocols = [UITableViewDelegate]; private _owner: WeakRef<ListView>; public static initWithOwner(owner: WeakRef<ListView>): UITableViewRowHeightDelegateImpl { const delegate = <UITableViewRowHeightDelegateImpl>UITableViewRowHeightDelegateImpl.new(); delegate._owner = owner; return delegate; } public tableViewWillDisplayCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath) { const owner = this._owner.get(); if (owner && indexPath.row === owner.items.length - 1) { owner.notify(<EventData>{ eventName: LOADMOREITEMS, object: owner, }); } } public tableViewWillSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath { const cell = <ListViewCell>tableView.cellForRowAtIndexPath(indexPath); const owner = this._owner.get(); if (owner) { notifyForItemAtIndex(owner, cell, cell.view, ITEMTAP, indexPath); } return indexPath; } public tableViewDidSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath { tableView.deselectRowAtIndexPathAnimated(indexPath, true); return indexPath; } public tableViewHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number { const owner = this._owner.get(); if (!owner) { return tableView.estimatedRowHeight; } return layout.toDeviceIndependentPixels(owner._effectiveRowHeight); } } export class ListView extends ListViewBase { public nativeViewProtected: UITableView; // tslint:disable-next-line private _dataSource; private _delegate; private _heights: Array<number>; private _preparingCell: boolean; private _isDataDirty: boolean; private _map: Map<ListViewCell, ItemView>; widthMeasureSpec = 0; constructor() { super(); this._map = new Map<ListViewCell, ItemView>(); this._heights = new Array<number>(); } createNativeView() { return UITableView.new(); } initNativeView() { super.initNativeView(); const nativeView = this.nativeViewProtected; nativeView.registerClassForCellReuseIdentifier(ListViewCell.class(), this._defaultTemplate.key); nativeView.estimatedRowHeight = DEFAULT_HEIGHT; nativeView.rowHeight = UITableViewAutomaticDimension; nativeView.dataSource = this._dataSource = DataSource.initWithOwner(new WeakRef(this)); this._delegate = UITableViewDelegateImpl.initWithOwner(new WeakRef(this)); this._setNativeClipToBounds(); } disposeNativeView() { this._delegate = null; this._dataSource = null; super.disposeNativeView(); } _setNativeClipToBounds() { // Always set clipsToBounds for list-view this.ios.clipsToBounds = true; } @profile public onLoaded() { super.onLoaded(); if (this._isDataDirty) { this.refresh(); } this.ios.delegate = this._delegate; } public onUnloaded() { this.ios.delegate = null; super.onUnloaded(); } // @ts-ignore get ios(): UITableView { return this.nativeViewProtected; } get _childrenCount(): number { return this._map.size; } public eachChildView(callback: (child: View) => boolean): void { this._map.forEach((view, key) => { callback(view); }); } public scrollToIndex(index: number) { this._scrollToIndex(index, false); } public scrollToIndexAnimated(index: number) { this._scrollToIndex(index); } private _scrollToIndex(index: number, animated = true) { if (!this.ios) { return; } const itemsLength = this.items ? this.items.length : 0; // mimic Android behavior that silently coerces index values within [0, itemsLength - 1] range if (itemsLength > 0) { if (index < 0) { index = 0; } else if (index >= itemsLength) { index = itemsLength - 1; } this.ios.scrollToRowAtIndexPathAtScrollPositionAnimated(NSIndexPath.indexPathForItemInSection(index, 0), UITableViewScrollPosition.Top, animated); } else if (Trace.isEnabled()) { Trace.write(`Cannot scroll listview to index ${index} when listview items not set`, Trace.categories.Binding); } } public refresh() { // clear bindingContext when it is not observable because otherwise bindings to items won't reevaluate this._map.forEach((view, nativeView, map) => { if (!(view.bindingContext instanceof Observable)) { view.bindingContext = null; } }); if (this.isLoaded) { this.ios.reloadData(); this.requestLayout(); this._isDataDirty = false; } else { this._isDataDirty = true; } } public isItemAtIndexVisible(itemIndex: number): boolean { const indexes: NSIndexPath[] = Array.from(this.ios.indexPathsForVisibleRows); return indexes.some((visIndex) => visIndex.row === itemIndex); } public getHeight(index: number): number { return this._heights[index]; } public setHeight(index: number, value: number): void { this._heights[index] = value; } public _onRowHeightPropertyChanged(oldValue: CoreTypes.LengthType, newValue: CoreTypes.LengthType) { const value = layout.toDeviceIndependentPixels(this._effectiveRowHeight); const nativeView = this.ios; if (value < 0) { nativeView.rowHeight = UITableViewAutomaticDimension; nativeView.estimatedRowHeight = DEFAULT_HEIGHT; this._delegate = UITableViewDelegateImpl.initWithOwner(new WeakRef(this)); } else { nativeView.rowHeight = value; nativeView.estimatedRowHeight = value; this._delegate = UITableViewRowHeightDelegateImpl.initWithOwner(new WeakRef(this)); } if (this.isLoaded) { nativeView.delegate = this._delegate; } super._onRowHeightPropertyChanged(oldValue, newValue); } public requestLayout(): void { // When preparing cell don't call super - no need to invalidate our measure when cell desiredSize is changed. if (!this._preparingCell) { super.requestLayout(); } } public measure(widthMeasureSpec: number, heightMeasureSpec: number): void { this.widthMeasureSpec = widthMeasureSpec; const changed = this._setCurrentMeasureSpecs(widthMeasureSpec, heightMeasureSpec); super.measure(widthMeasureSpec, heightMeasureSpec); if (changed) { this.ios.reloadData(); } } public onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void { super.onMeasure(widthMeasureSpec, heightMeasureSpec); this._map.forEach((childView, listViewCell) => { View.measureChild(this, childView, childView._currentWidthMeasureSpec, childView._currentHeightMeasureSpec); }); } public onLayout(left: number, top: number, right: number, bottom: number): void { super.onLayout(left, top, right, bottom); this._map.forEach((childView, listViewCell) => { const rowHeight = this._effectiveRowHeight; const cellHeight = rowHeight > 0 ? rowHeight : this.getHeight(childView._listViewItemIndex); if (cellHeight) { const width = layout.getMeasureSpecSize(this.widthMeasureSpec); childView.iosOverflowSafeAreaEnabled = false; View.layoutChild(this, childView, 0, 0, width, cellHeight); } }); } private _layoutCell(cellView: View, indexPath: NSIndexPath): number { if (cellView) { const rowHeight = this._effectiveRowHeight; const heightMeasureSpec: number = rowHeight >= 0 ? layout.makeMeasureSpec(rowHeight, layout.EXACTLY) : infinity; const measuredSize = View.measureChild(this, cellView, this.widthMeasureSpec, heightMeasureSpec); const height = measuredSize.measuredHeight; this.setHeight(indexPath.row, height); return height; } return this.ios.estimatedRowHeight; } public _prepareCell(cell: ListViewCell, indexPath: NSIndexPath): number { let cellHeight: number; try { this._preparingCell = true; let view: ItemView = cell.view; if (!view) { view = this._getItemTemplate(indexPath.row).createView(); } const args = notifyForItemAtIndex(this, cell, view, ITEMLOADING, indexPath); view = args.view || this._getDefaultItemContent(indexPath.row); // Proxy containers should not get treated as layouts. // Wrap them in a real layout as well. if (view instanceof ProxyViewContainer) { const sp = new StackLayout(); sp.addChild(view); view = sp; } // If cell is reused it have old content - remove it first. if (!cell.view) { cell.owner = new WeakRef(view); } else if (cell.view !== view) { this._removeContainer(cell); (<UIView>cell.view.nativeViewProtected).removeFromSuperview(); cell.owner = new WeakRef(view); } this._prepareItem(view, indexPath.row); view._listViewItemIndex = indexPath.row; this._map.set(cell, view); // We expect that views returned from itemLoading are new (e.g. not reused). if (view && !view.parent) { this._addView(view); cell.contentView.addSubview(view.nativeViewProtected); } cellHeight = this._layoutCell(view, indexPath); } finally { this._preparingCell = false; } return cellHeight; } public _removeContainer(cell: ListViewCell): void { const view: ItemView = cell.view; // This is to clear the StackLayout that is used to wrap ProxyViewContainer instances. if (!(view.parent instanceof ListView)) { this._removeView(view.parent); } // No need to request layout when we are removing cells. const preparing = this._preparingCell; this._preparingCell = true; view.parent._removeView(view); view._listViewItemIndex = undefined; this._preparingCell = preparing; this._map.delete(cell); } [separatorColorProperty.getDefault](): UIColor { return this.ios.separatorColor; } [separatorColorProperty.setNative](value: Color | UIColor) { this.ios.separatorColor = value instanceof Color ? value.ios : value; } [itemTemplatesProperty.getDefault](): KeyedTemplate[] { return null; } [itemTemplatesProperty.setNative](value: KeyedTemplate[]) { this._itemTemplatesInternal = new Array<KeyedTemplate>(this._defaultTemplate); if (value) { for (let i = 0, length = value.length; i < length; i++) { this.ios.registerClassForCellReuseIdentifier(ListViewCell.class(), value[i].key); } this._itemTemplatesInternal = this._itemTemplatesInternal.concat(value); } this.refresh(); } [iosEstimatedRowHeightProperty.getDefault](): CoreTypes.LengthType { return DEFAULT_HEIGHT; } [iosEstimatedRowHeightProperty.setNative](value: CoreTypes.LengthType) { const nativeView = this.ios; const estimatedHeight = Length.toDevicePixels(value, 0); nativeView.estimatedRowHeight = estimatedHeight < 0 ? DEFAULT_HEIGHT : estimatedHeight; } }
the_stack
import React from 'react' import normalizeWheel from 'normalize-wheel' import { Area, MediaSize, Point, Size, VideoSrc } from './types' import { getCropSize, restrictPosition, getDistanceBetweenPoints, getRotationBetweenPoints, computeCroppedArea, getCenter, getInitialCropFromCroppedAreaPixels, classNames, } from './helpers' import cssStyles from './styles.css' export type CropperProps = { image?: string video?: string | VideoSrc[] transform?: string crop: Point zoom: number rotation: number aspect: number minZoom: number maxZoom: number cropShape: 'rect' | 'round' cropSize?: Size objectFit?: 'contain' | 'horizontal-cover' | 'vertical-cover' showGrid?: boolean zoomSpeed: number zoomWithScroll?: boolean onCropChange: (location: Point) => void onZoomChange?: (zoom: number) => void onRotationChange?: (rotation: number) => void onCropComplete?: (croppedArea: Area, croppedAreaPixels: Area) => void onCropAreaChange?: (croppedArea: Area, croppedAreaPixels: Area) => void onCropSizeChange?: (cropSize: Size) => void onInteractionStart?: () => void onInteractionEnd?: () => void onMediaLoaded?: (mediaSize: MediaSize) => void style: { containerStyle?: React.CSSProperties mediaStyle?: React.CSSProperties cropAreaStyle?: React.CSSProperties } classes: { containerClassName?: string mediaClassName?: string cropAreaClassName?: string } restrictPosition: boolean initialCroppedAreaPixels?: Area mediaProps: React.ImgHTMLAttributes<HTMLElement> | React.VideoHTMLAttributes<HTMLElement> disableAutomaticStylesInjection?: boolean } type State = { cropSize: Size | null hasWheelJustStarted: boolean } const MIN_ZOOM = 1 const MAX_ZOOM = 3 class Cropper extends React.Component<CropperProps, State> { static defaultProps = { zoom: 1, rotation: 0, aspect: 4 / 3, maxZoom: MAX_ZOOM, minZoom: MIN_ZOOM, cropShape: 'rect', objectFit: 'contain', showGrid: true, style: {}, classes: {}, mediaProps: {}, zoomSpeed: 1, restrictPosition: true, zoomWithScroll: true, } imageRef: HTMLImageElement | null = null videoRef: HTMLVideoElement | null = null containerRef: HTMLDivElement | null = null styleRef: HTMLStyleElement | null = null containerRect: DOMRect | null = null mediaSize: MediaSize = { width: 0, height: 0, naturalWidth: 0, naturalHeight: 0 } dragStartPosition: Point = { x: 0, y: 0 } dragStartCrop: Point = { x: 0, y: 0 } lastPinchDistance = 0 lastPinchRotation = 0 rafDragTimeout: number | null = null rafPinchTimeout: number | null = null wheelTimer: number | null = null state: State = { cropSize: null, hasWheelJustStarted: false, } componentDidMount() { window.addEventListener('resize', this.computeSizes) if (this.containerRef) { this.props.zoomWithScroll && this.containerRef.addEventListener('wheel', this.onWheel, { passive: false }) this.containerRef.addEventListener('gesturestart', this.preventZoomSafari) this.containerRef.addEventListener('gesturechange', this.preventZoomSafari) } if (!this.props.disableAutomaticStylesInjection) { this.styleRef = document.createElement('style') this.styleRef.setAttribute('type', 'text/css') this.styleRef.innerHTML = cssStyles document.head.appendChild(this.styleRef) } // when rendered via SSR, the image can already be loaded and its onLoad callback will never be called if (this.imageRef && this.imageRef.complete) { this.onMediaLoad() } } componentWillUnmount() { window.removeEventListener('resize', this.computeSizes) if (this.containerRef) { this.containerRef.removeEventListener('gesturestart', this.preventZoomSafari) this.containerRef.removeEventListener('gesturechange', this.preventZoomSafari) } if (this.styleRef) { this.styleRef.parentNode?.removeChild(this.styleRef) } this.cleanEvents() this.props.zoomWithScroll && this.clearScrollEvent() } componentDidUpdate(prevProps: CropperProps) { if (prevProps.rotation !== this.props.rotation) { this.computeSizes() this.recomputeCropPosition() } else if (prevProps.aspect !== this.props.aspect) { this.computeSizes() } else if (prevProps.zoom !== this.props.zoom) { this.recomputeCropPosition() } else if ( prevProps.cropSize?.height !== this.props.cropSize?.height || prevProps.cropSize?.width !== this.props.cropSize?.width ) { this.computeSizes() } else if ( prevProps.crop?.x !== this.props.crop?.x || prevProps.crop?.y !== this.props.crop?.y ) { this.emitCropAreaChange() } if (prevProps.zoomWithScroll !== this.props.zoomWithScroll && this.containerRef) { this.props.zoomWithScroll ? this.containerRef.addEventListener('wheel', this.onWheel, { passive: false }) : this.clearScrollEvent() } if (prevProps.video !== this.props.video) { this.videoRef?.load() } } // this is to prevent Safari on iOS >= 10 to zoom the page preventZoomSafari = (e: Event) => e.preventDefault() cleanEvents = () => { document.removeEventListener('mousemove', this.onMouseMove) document.removeEventListener('mouseup', this.onDragStopped) document.removeEventListener('touchmove', this.onTouchMove) document.removeEventListener('touchend', this.onDragStopped) } clearScrollEvent = () => { if (this.containerRef) this.containerRef.removeEventListener('wheel', this.onWheel) if (this.wheelTimer) { clearTimeout(this.wheelTimer) } } onMediaLoad = () => { this.computeSizes() this.emitCropData() this.setInitialCrop() if (this.props.onMediaLoaded) { this.props.onMediaLoaded(this.mediaSize) } } setInitialCrop = () => { const { initialCroppedAreaPixels, cropSize } = this.props if (!initialCroppedAreaPixels) { return } const { crop, zoom } = getInitialCropFromCroppedAreaPixels( initialCroppedAreaPixels, this.mediaSize, cropSize ) this.props.onCropChange(crop) this.props.onZoomChange && this.props.onZoomChange(zoom) } getAspect() { const { cropSize, aspect } = this.props if (cropSize) { return cropSize.width / cropSize.height } return aspect } computeSizes = () => { const mediaRef = this.imageRef || this.videoRef if (mediaRef && this.containerRef) { this.containerRect = this.containerRef.getBoundingClientRect() this.mediaSize = { width: mediaRef.offsetWidth, height: mediaRef.offsetHeight, naturalWidth: this.imageRef?.naturalWidth || this.videoRef?.videoWidth || 0, naturalHeight: this.imageRef?.naturalHeight || this.videoRef?.videoHeight || 0, } const cropSize = this.props.cropSize ? this.props.cropSize : getCropSize( mediaRef.offsetWidth, mediaRef.offsetHeight, this.containerRect.width, this.containerRect.height, this.props.aspect, this.props.rotation ) if ( this.state.cropSize?.height !== cropSize.height || this.state.cropSize?.width !== cropSize.width ) { this.props.onCropSizeChange && this.props.onCropSizeChange(cropSize) } this.setState({ cropSize }, this.recomputeCropPosition) } } static getMousePoint = (e: MouseEvent | React.MouseEvent) => ({ x: Number(e.clientX), y: Number(e.clientY), }) static getTouchPoint = (touch: Touch | React.Touch) => ({ x: Number(touch.clientX), y: Number(touch.clientY), }) onMouseDown = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => { e.preventDefault() document.addEventListener('mousemove', this.onMouseMove) document.addEventListener('mouseup', this.onDragStopped) this.onDragStart(Cropper.getMousePoint(e)) } onMouseMove = (e: MouseEvent) => this.onDrag(Cropper.getMousePoint(e)) onTouchStart = (e: React.TouchEvent<HTMLDivElement>) => { document.addEventListener('touchmove', this.onTouchMove, { passive: false }) // iOS 11 now defaults to passive: true document.addEventListener('touchend', this.onDragStopped) if (e.touches.length === 2) { this.onPinchStart(e) } else if (e.touches.length === 1) { this.onDragStart(Cropper.getTouchPoint(e.touches[0])) } } onTouchMove = (e: TouchEvent) => { // Prevent whole page from scrolling on iOS. e.preventDefault() if (e.touches.length === 2) { this.onPinchMove(e) } else if (e.touches.length === 1) { this.onDrag(Cropper.getTouchPoint(e.touches[0])) } } onDragStart = ({ x, y }: Point) => { this.dragStartPosition = { x, y } this.dragStartCrop = { ...this.props.crop } this.props.onInteractionStart?.() } onDrag = ({ x, y }: Point) => { if (this.rafDragTimeout) window.cancelAnimationFrame(this.rafDragTimeout) this.rafDragTimeout = window.requestAnimationFrame(() => { if (!this.state.cropSize) return if (x === undefined || y === undefined) return const offsetX = x - this.dragStartPosition.x const offsetY = y - this.dragStartPosition.y const requestedPosition = { x: this.dragStartCrop.x + offsetX, y: this.dragStartCrop.y + offsetY, } const newPosition = this.props.restrictPosition ? restrictPosition( requestedPosition, this.mediaSize, this.state.cropSize, this.props.zoom, this.props.rotation ) : requestedPosition this.props.onCropChange(newPosition) }) } onDragStopped = () => { this.cleanEvents() this.emitCropData() this.props.onInteractionEnd?.() } onPinchStart(e: React.TouchEvent<HTMLDivElement>) { const pointA = Cropper.getTouchPoint(e.touches[0]) const pointB = Cropper.getTouchPoint(e.touches[1]) this.lastPinchDistance = getDistanceBetweenPoints(pointA, pointB) this.lastPinchRotation = getRotationBetweenPoints(pointA, pointB) this.onDragStart(getCenter(pointA, pointB)) } onPinchMove(e: TouchEvent) { const pointA = Cropper.getTouchPoint(e.touches[0]) const pointB = Cropper.getTouchPoint(e.touches[1]) const center = getCenter(pointA, pointB) this.onDrag(center) if (this.rafPinchTimeout) window.cancelAnimationFrame(this.rafPinchTimeout) this.rafPinchTimeout = window.requestAnimationFrame(() => { const distance = getDistanceBetweenPoints(pointA, pointB) const newZoom = this.props.zoom * (distance / this.lastPinchDistance) this.setNewZoom(newZoom, center) this.lastPinchDistance = distance const rotation = getRotationBetweenPoints(pointA, pointB) const newRotation = this.props.rotation + (rotation - this.lastPinchRotation) this.props.onRotationChange && this.props.onRotationChange(newRotation) this.lastPinchRotation = rotation }) } onWheel = (e: WheelEvent) => { e.preventDefault() const point = Cropper.getMousePoint(e) const { pixelY } = normalizeWheel(e) const newZoom = this.props.zoom - (pixelY * this.props.zoomSpeed) / 200 this.setNewZoom(newZoom, point) if (!this.state.hasWheelJustStarted) { this.setState({ hasWheelJustStarted: true }, () => this.props.onInteractionStart?.()) } if (this.wheelTimer) { clearTimeout(this.wheelTimer) } this.wheelTimer = window.setTimeout( () => this.setState({ hasWheelJustStarted: false }, () => this.props.onInteractionEnd?.()), 250 ) } getPointOnContainer = ({ x, y }: Point) => { if (!this.containerRect) { throw new Error('The Cropper is not mounted') } return { x: this.containerRect.width / 2 - (x - this.containerRect.left), y: this.containerRect.height / 2 - (y - this.containerRect.top), } } getPointOnMedia = ({ x, y }: Point) => { const { crop, zoom } = this.props return { x: (x + crop.x) / zoom, y: (y + crop.y) / zoom, } } setNewZoom = (zoom: number, point: Point) => { if (!this.state.cropSize || !this.props.onZoomChange) return const zoomPoint = this.getPointOnContainer(point) const zoomTarget = this.getPointOnMedia(zoomPoint) const newZoom = Math.min(this.props.maxZoom, Math.max(zoom, this.props.minZoom)) const requestedPosition = { x: zoomTarget.x * newZoom - zoomPoint.x, y: zoomTarget.y * newZoom - zoomPoint.y, } const newPosition = this.props.restrictPosition ? restrictPosition( requestedPosition, this.mediaSize, this.state.cropSize, newZoom, this.props.rotation ) : requestedPosition this.props.onCropChange(newPosition) this.props.onZoomChange(newZoom) } getCropData = () => { if (!this.state.cropSize) { return null } // this is to ensure the crop is correctly restricted after a zoom back (https://github.com/ricardo-ch/react-easy-crop/issues/6) const restrictedPosition = this.props.restrictPosition ? restrictPosition( this.props.crop, this.mediaSize, this.state.cropSize, this.props.zoom, this.props.rotation ) : this.props.crop return computeCroppedArea( restrictedPosition, this.mediaSize, this.state.cropSize, this.getAspect(), this.props.zoom, this.props.rotation, this.props.restrictPosition ) } emitCropData = () => { const cropData = this.getCropData() if (!cropData) return const { croppedAreaPercentages, croppedAreaPixels } = cropData if (this.props.onCropComplete) { this.props.onCropComplete(croppedAreaPercentages, croppedAreaPixels) } if (this.props.onCropAreaChange) { this.props.onCropAreaChange(croppedAreaPercentages, croppedAreaPixels) } } emitCropAreaChange = () => { const cropData = this.getCropData() if (!cropData) return const { croppedAreaPercentages, croppedAreaPixels } = cropData if (this.props.onCropAreaChange) { this.props.onCropAreaChange(croppedAreaPercentages, croppedAreaPixels) } } recomputeCropPosition = () => { if (!this.state.cropSize) return const newPosition = this.props.restrictPosition ? restrictPosition( this.props.crop, this.mediaSize, this.state.cropSize, this.props.zoom, this.props.rotation ) : this.props.crop this.props.onCropChange(newPosition) this.emitCropData() } render() { const { image, video, mediaProps, transform, crop: { x, y }, rotation, zoom, cropShape, showGrid, style: { containerStyle, cropAreaStyle, mediaStyle }, classes: { containerClassName, cropAreaClassName, mediaClassName }, objectFit, } = this.props return ( <div onMouseDown={this.onMouseDown} onTouchStart={this.onTouchStart} ref={(el) => (this.containerRef = el)} data-testid="container" style={containerStyle} className={classNames('reactEasyCrop_Container', containerClassName)} > {image ? ( <img alt="" className={classNames( 'reactEasyCrop_Image', objectFit === 'contain' && 'reactEasyCrop_Contain', objectFit === 'horizontal-cover' && 'reactEasyCrop_Cover_Horizontal', objectFit === 'vertical-cover' && 'reactEasyCrop_Cover_Vertical', mediaClassName )} {...(mediaProps as React.ImgHTMLAttributes<HTMLElement>)} src={image} ref={(el: HTMLImageElement) => (this.imageRef = el)} style={{ ...mediaStyle, transform: transform || `translate(${x}px, ${y}px) rotate(${rotation}deg) scale(${zoom})`, }} onLoad={this.onMediaLoad} /> ) : ( video && ( <video autoPlay loop muted={true} className={classNames( 'reactEasyCrop_Video', objectFit === 'contain' && 'reactEasyCrop_Contain', objectFit === 'horizontal-cover' && 'reactEasyCrop_Cover_Horizontal', objectFit === 'vertical-cover' && 'reactEasyCrop_Cover_Vertical', mediaClassName )} {...mediaProps} ref={(el: HTMLVideoElement) => (this.videoRef = el)} onLoadedMetadata={this.onMediaLoad} style={{ ...mediaStyle, transform: transform || `translate(${x}px, ${y}px) rotate(${rotation}deg) scale(${zoom})`, }} controls={false} > {(Array.isArray(video) ? video : [{ src: video }]).map((item) => ( <source key={item.src} {...item} /> ))} </video> ) )} {this.state.cropSize && ( <div style={{ ...cropAreaStyle, width: this.state.cropSize.width, height: this.state.cropSize.height, }} data-testid="cropper" className={classNames( 'reactEasyCrop_CropArea', cropShape === 'round' && 'reactEasyCrop_CropAreaRound', showGrid && 'reactEasyCrop_CropAreaGrid', cropAreaClassName )} /> )} </div> ) } } export default Cropper
the_stack
import React = require("react"); import { TeamMember } from "azure-devops-extension-api/WebApi/WebApi"; import { TeamSettingsIteration } from "azure-devops-extension-api/work"; import { getUser } from "azure-devops-extension-sdk"; import { Button } from "azure-devops-ui/Button"; import { ButtonGroup } from "azure-devops-ui/ButtonGroup"; import { CustomDialog } from "azure-devops-ui/Dialog"; import { Dropdown } from "azure-devops-ui/Dropdown"; import { TitleSize } from "azure-devops-ui/Header"; import { IListSelection } from "azure-devops-ui/List"; import { IListBoxItem } from "azure-devops-ui/ListBox"; import { MessageCard, MessageCardSeverity } from "azure-devops-ui/MessageCard"; import { ObservableValue } from "azure-devops-ui/Core/Observable"; import { Observer } from "azure-devops-ui/Observer"; import { PanelHeader, PanelFooter, PanelContent } from "azure-devops-ui/Panel"; import { DropdownSelection } from "azure-devops-ui/Utilities/DropdownSelection"; import { Calendar } from "@fullcalendar/core"; import { ICalendarEvent } from "./Contracts"; import { MessageDialog } from "./MessageDialog"; import { toDate, formatDate } from "./TimeLib"; import { VSOCapacityEventSource, Everyone } from "./VSOCapacityEventSource"; interface IAddEditDaysOffDialogProps { /** * Calendar api to add event to the Calendar */ calendarApi: Calendar; /** * End date for event */ end: Date; /** * Event object if editing an event. */ event?: ICalendarEvent; /** * Object that stores all event data */ eventSource: VSOCapacityEventSource; /** * List of members in currently selected team. */ members: TeamMember[]; /** * Callback function on dialog dismiss */ onDismiss: () => void; /** * Start date for event */ start: Date; } /** * Dialog that lets user add new days off */ export class AddEditDaysOffDialog extends React.Component<IAddEditDaysOffDialogProps> { endDate: Date; isConfirmationDialogOpen: ObservableValue<boolean>; iteration?: TeamSettingsIteration; memberSelection: IListSelection; message: ObservableValue<string>; okButtonEnabled: ObservableValue<boolean>; selectedMemberId: string; selectedMemberName: string; startDate: Date; teamMembers: IListBoxItem[]; constructor(props: IAddEditDaysOffDialogProps) { super(props); this.okButtonEnabled = new ObservableValue<boolean>(true); this.message = new ObservableValue<string>(""); this.memberSelection = new DropdownSelection(); this.teamMembers = []; this.isConfirmationDialogOpen = new ObservableValue<boolean>(false); let selectedIndex = 0; if (this.props.event) { this.startDate = new Date(this.props.event.startDate); this.endDate = new Date(this.props.event.endDate); this.teamMembers.push({ id: this.props.event.member!.id, text: this.props.event.member!.displayName }); } else { this.startDate = props.start; this.endDate = props.end; const userName = getUser().displayName; let i = 1; this.teamMembers.push({ id: Everyone, text: Everyone }); this.teamMembers.push( ...this.props.members.map(item => { if (userName === item.identity.displayName) { selectedIndex = i; } i++; return { id: item.identity.id, text: item.identity.displayName }; }) ); } this.memberSelection.select(selectedIndex); this.selectedMemberId = this.teamMembers[selectedIndex].id; this.selectedMemberName = this.teamMembers[selectedIndex].text!; this.validateSelections(); } public render(): JSX.Element { return ( <> <CustomDialog onDismiss={this.props.onDismiss}> <PanelHeader onDismiss={this.props.onDismiss} showCloseButton={false} titleProps={{ size: TitleSize.Small, text: this.props.event ? "Edit days off" : "Add days off" }} /> <PanelContent> <div className="flex-grow flex-column event-dialog-content"> <Observer message={this.message}> {(props: { message: string }) => { return props.message !== "" ? ( <MessageCard className="flex-self-stretch" severity={MessageCardSeverity.Info}> {props.message} </MessageCard> ) : null; }} </Observer> <div className="input-row flex-row"> <span>Start Date</span> <div className="bolt-textfield column-2"> <input className="bolt-textfield-input input-date" defaultValue={formatDate(this.startDate, "YYYY-MM-DD")} onChange={this.onInputStartDate} type="date" /> </div> </div> <div className="input-row flex-row"> <span>End Date</span> <div className="bolt-textfield column-2"> <input className="bolt-textfield-input input-date" defaultValue={formatDate(this.endDate, "YYYY-MM-DD")} onChange={this.onInputEndDate} type="date" /> </div> </div> <div className="input-row flex-row"> <span>Team Member</span> <Dropdown className="column-2" items={this.teamMembers} onSelect={this.onSelectTeamMember} selection={this.memberSelection} /> </div> </div> </PanelContent> <PanelFooter> <div className="flex-grow flex-row"> {this.props.event && <Button onClick={this.onDeleteClick} subtle={true} text="Delete days off" />} <ButtonGroup className="bolt-panel-footer-buttons flex-grow"> <Button onClick={this.props.onDismiss} text="Cancel" /> <Observer enabled={this.okButtonEnabled}> {(props: { enabled: boolean }) => { return <Button disabled={!props.enabled} onClick={this.onOKClick} primary={true} text="Ok" />; }} </Observer> </ButtonGroup> </div> </PanelFooter> </CustomDialog> <Observer isDialogOpen={this.isConfirmationDialogOpen}> {(props: { isDialogOpen: boolean }) => { return props.isDialogOpen ? ( <MessageDialog message="Are you sure you want to delete the days off?" onConfirm={() => { this.props.eventSource.deleteEvent(this.props.event!, this.props.event!.iterationId!).then(() => { this.props.calendarApi.refetchEvents(); }); this.isConfirmationDialogOpen.value = false; this.props.onDismiss(); }} onDismiss={() => { this.isConfirmationDialogOpen.value = false; }} title="Delete days off" /> ) : null; }} </Observer> </> ); } private onDeleteClick = async (): Promise<void> => { this.isConfirmationDialogOpen.value = true; }; private onInputEndDate = (e: React.ChangeEvent<HTMLInputElement>): void => { let temp = e.target.value; if (temp) { this.endDate = toDate(temp); } this.validateSelections(); }; private onInputStartDate = (e: React.ChangeEvent<HTMLInputElement>): void => { let temp = e.target.value; if (temp) { this.startDate = toDate(temp); } this.validateSelections(); }; private onOKClick = (): void => { let promise; if (this.props.event) { promise = this.props.eventSource.updateEvent(this.props.event, this.props.event.iterationId!, this.startDate, this.endDate); } else { promise = this.props.eventSource.addEvent( this.iteration!.id, this.startDate, this.endDate, this.selectedMemberName, this.selectedMemberId ); } promise.then(() => { this.props.calendarApi.refetchEvents(); }); this.props.onDismiss(); }; private onSelectTeamMember = (event: React.SyntheticEvent<HTMLElement>, item: IListBoxItem<{}>) => { this.selectedMemberName = item.text!; this.selectedMemberId = item.id; }; private validateSelections = () => { let valid: boolean = this.startDate <= this.endDate; // start date and end date should be in same iteration this.iteration = this.props.eventSource.getIterationForDate(this.startDate, this.endDate); valid = valid && !!this.iteration; if (valid) { if (this.message.value !== "") { this.message.value = ""; } } else { if (this.startDate > this.endDate) { this.message.value = "Start date must be same or before the end date."; } else { this.message.value = "Selected dates are not part of any or same Iteration."; } } this.okButtonEnabled.value = valid; }; }
the_stack
import Page = require('../../../../../base/Page'); import Response = require('../../../../../http/response'); import V1 = require('../../../V1'); import { SerializableClass } from '../../../../../interfaces'; type ReservationCallStatus = 'initiated'|'ringing'|'answered'|'completed'; type ReservationConferenceEvent = 'start'|'end'|'join'|'leave'|'mute'|'hold'|'speaker'; type ReservationStatus = 'pending'|'accepted'|'rejected'|'timeout'|'canceled'|'rescinded'|'wrapping'|'completed'; type ReservationSupervisorMode = 'monitor'|'whisper'|'barge'; /** * Initialize the ReservationList * * @param version - Version of the resource * @param workspaceSid - The SID of the Workspace that this task is contained within. * @param taskSid - The SID of the reserved Task resource */ declare function ReservationList(version: V1, workspaceSid: string, taskSid: string): ReservationListInstance; /** * Options to pass to update * * @property beep - Whether to play a notification beep when the participant joins * @property beepOnCustomerEntrance - Whether to play a notification beep when the customer joins * @property callAccept - Whether to accept a reservation when executing a Call instruction * @property callFrom - The Caller ID of the outbound call when executing a Call instruction * @property callRecord - Whether to record both legs of a call when executing a Call instruction * @property callStatusCallbackUrl - The URL to call for the completed call event when executing a Call instruction * @property callTimeout - Timeout for call when executing a Call instruction * @property callTo - The Contact URI of the worker when executing a Call instruction * @property callUrl - TwiML URI executed on answering the worker's leg as a result of the Call instruction * @property conferenceRecord - Whether to record the conference the participant is joining * @property conferenceRecordingStatusCallback - The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available * @property conferenceRecordingStatusCallbackMethod - The HTTP method we should use to call `conference_recording_status_callback` * @property conferenceStatusCallback - The callback URL for conference events * @property conferenceStatusCallbackEvent - The conference status events that we will send to conference_status_callback * @property conferenceStatusCallbackMethod - HTTP method for requesting `conference_status_callback` URL * @property conferenceTrim - How to trim leading and trailing silence from your recorded conference audio files * @property dequeueFrom - The Caller ID of the call to the worker when executing a Dequeue instruction * @property dequeuePostWorkActivitySid - The SID of the Activity resource to start after executing a Dequeue instruction * @property dequeueRecord - Whether to record both legs of a call when executing a Dequeue instruction * @property dequeueStatusCallbackEvent - The Call progress events sent via webhooks as a result of a Dequeue instruction * @property dequeueStatusCallbackUrl - The Callback URL for completed call event when executing a Dequeue instruction * @property dequeueTimeout - Timeout for call when executing a Dequeue instruction * @property dequeueTo - The Contact URI of the worker when executing a Dequeue instruction * @property earlyMedia - Whether agents can hear the state of the outbound call * @property endConferenceOnCustomerExit - Whether to end the conference when the customer leaves * @property endConferenceOnExit - Whether to end the conference when the agent leaves * @property from - The Caller ID of the call to the worker when executing a Conference instruction * @property ifMatch - The If-Match HTTP request header * @property instruction - The assignment instruction for reservation * @property maxParticipants - The maximum number of agent conference participants * @property muted - Whether to mute the agent * @property postWorkActivitySid - The new worker activity SID after executing a Conference instruction * @property record - Whether to record the participant and their conferences * @property recordingChannels - Specify `mono` or `dual` recording channels * @property recordingStatusCallback - The URL that we should call using the `recording_status_callback_method` when the recording status changes * @property recordingStatusCallbackMethod - The HTTP method we should use when we call `recording_status_callback` * @property redirectAccept - Whether the reservation should be accepted when executing a Redirect instruction * @property redirectCallSid - The Call SID of the call parked in the queue when executing a Redirect instruction * @property redirectUrl - TwiML URI to redirect the call to when executing the Redirect instruction * @property region - The region where we should mix the conference audio * @property reservationStatus - The new status of the reservation * @property sipAuthPassword - The SIP password for authentication * @property sipAuthUsername - The SIP username used for authentication * @property startConferenceOnEnter - Whether the conference starts when the participant joins the conference * @property statusCallback - The URL we should call to send status information to your application * @property statusCallbackEvent - The call progress events that we will send to status_callback * @property statusCallbackMethod - The HTTP method we should use to call status_callback * @property supervisor - The Supervisor SID/URI when executing the Supervise instruction * @property supervisorMode - The Supervisor mode when executing the Supervise instruction * @property timeout - Timeout for call when executing a Conference instruction * @property to - The Contact URI of the worker when executing a Conference instruction * @property waitMethod - The HTTP method we should use to call `wait_url` * @property waitUrl - URL that hosts pre-conference hold music * @property workerActivitySid - The new worker activity SID if rejecting a reservation */ interface ReservationInstanceUpdateOptions { beep?: string; beepOnCustomerEntrance?: boolean; callAccept?: boolean; callFrom?: string; callRecord?: string; callStatusCallbackUrl?: string; callTimeout?: number; callTo?: string; callUrl?: string; conferenceRecord?: string; conferenceRecordingStatusCallback?: string; conferenceRecordingStatusCallbackMethod?: string; conferenceStatusCallback?: string; conferenceStatusCallbackEvent?: ReservationConferenceEvent | ReservationConferenceEvent[]; conferenceStatusCallbackMethod?: string; conferenceTrim?: string; dequeueFrom?: string; dequeuePostWorkActivitySid?: string; dequeueRecord?: string; dequeueStatusCallbackEvent?: string | string[]; dequeueStatusCallbackUrl?: string; dequeueTimeout?: number; dequeueTo?: string; earlyMedia?: boolean; endConferenceOnCustomerExit?: boolean; endConferenceOnExit?: boolean; from?: string; ifMatch?: string; instruction?: string; maxParticipants?: number; muted?: boolean; postWorkActivitySid?: string; record?: boolean; recordingChannels?: string; recordingStatusCallback?: string; recordingStatusCallbackMethod?: string; redirectAccept?: boolean; redirectCallSid?: string; redirectUrl?: string; region?: string; reservationStatus?: ReservationStatus; sipAuthPassword?: string; sipAuthUsername?: string; startConferenceOnEnter?: boolean; statusCallback?: string; statusCallbackEvent?: ReservationCallStatus | ReservationCallStatus[]; statusCallbackMethod?: string; supervisor?: string; supervisorMode?: ReservationSupervisorMode; timeout?: number; to?: string; waitMethod?: string; waitUrl?: string; workerActivitySid?: string; } interface ReservationListInstance { /** * @param sid - sid of instance */ (sid: string): ReservationContext; /** * Streams ReservationInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Function to process each record */ each(callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; /** * Streams ReservationInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: ReservationListInstanceEachOptions, callback?: (item: ReservationInstance, done: (err?: Error) => void) => void): void; /** * Constructs a reservation * * @param sid - The SID of the TaskReservation resource to fetch */ get(sid: string): ReservationContext; /** * Retrieve a single target page of ReservationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ getPage(callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; /** * Retrieve a single target page of ReservationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; /** * Lists ReservationInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ list(callback?: (error: Error | null, items: ReservationInstance[]) => any): Promise<ReservationInstance[]>; /** * Lists ReservationInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: ReservationListInstanceOptions, callback?: (error: Error | null, items: ReservationInstance[]) => any): Promise<ReservationInstance[]>; /** * Retrieve a single page of ReservationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ page(callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; /** * Retrieve a single page of ReservationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: ReservationListInstancePageOptions, callback?: (error: Error | null, items: ReservationPage) => any): Promise<ReservationPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to each * * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property done - Function to be called upon completion of streaming * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @property reservationStatus - Returns the list of reservations for a task with a specified ReservationStatus */ interface ReservationListInstanceEachOptions { callback?: (item: ReservationInstance, done: (err?: Error) => void) => void; done?: Function; limit?: number; pageSize?: number; reservationStatus?: ReservationStatus; } /** * Options to pass to list * * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @property reservationStatus - Returns the list of reservations for a task with a specified ReservationStatus */ interface ReservationListInstanceOptions { limit?: number; pageSize?: number; reservationStatus?: ReservationStatus; } /** * Options to pass to page * * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API * @property reservationStatus - Returns the list of reservations for a task with a specified ReservationStatus */ interface ReservationListInstancePageOptions { pageNumber?: number; pageSize?: number; pageToken?: string; reservationStatus?: ReservationStatus; } interface ReservationPayload extends ReservationResource, Page.TwilioResponsePayload { } interface ReservationResource { account_sid: string; date_created: Date; date_updated: Date; links: string; reservation_status: ReservationStatus; sid: string; task_sid: string; url: string; worker_name: string; worker_sid: string; workspace_sid: string; } interface ReservationSolution { taskSid?: string; workspaceSid?: string; } declare class ReservationContext { /** * Initialize the ReservationContext * * @param version - Version of the resource * @param workspaceSid - The SID of the Workspace with the TaskReservation resource to fetch * @param taskSid - The SID of the reserved Task resource with the TaskReservation resource to fetch * @param sid - The SID of the TaskReservation resource to fetch */ constructor(version: V1, workspaceSid: string, taskSid: string, sid: string); /** * fetch a ReservationInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: ReservationInstance) => any): Promise<ReservationInstance>; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a ReservationInstance * * @param callback - Callback to handle processed record */ update(callback?: (error: Error | null, items: ReservationInstance) => any): Promise<ReservationInstance>; /** * update a ReservationInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: ReservationInstanceUpdateOptions, callback?: (error: Error | null, items: ReservationInstance) => any): Promise<ReservationInstance>; } declare class ReservationInstance extends SerializableClass { /** * Initialize the ReservationContext * * @param version - Version of the resource * @param payload - The instance payload * @param workspaceSid - The SID of the Workspace that this task is contained within. * @param taskSid - The SID of the reserved Task resource * @param sid - The SID of the TaskReservation resource to fetch */ constructor(version: V1, payload: ReservationPayload, workspaceSid: string, taskSid: string, sid: string); private _proxy: ReservationContext; accountSid: string; dateCreated: Date; dateUpdated: Date; /** * fetch a ReservationInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: ReservationInstance) => any): Promise<ReservationInstance>; links: string; reservationStatus: ReservationStatus; sid: string; taskSid: string; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a ReservationInstance * * @param callback - Callback to handle processed record */ update(callback?: (error: Error | null, items: ReservationInstance) => any): Promise<ReservationInstance>; /** * update a ReservationInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: ReservationInstanceUpdateOptions, callback?: (error: Error | null, items: ReservationInstance) => any): Promise<ReservationInstance>; url: string; workerName: string; workerSid: string; workspaceSid: string; } declare class ReservationPage extends Page<V1, ReservationPayload, ReservationResource, ReservationInstance> { /** * Initialize the ReservationPage * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: V1, response: Response<string>, solution: ReservationSolution); /** * Build an instance of ReservationInstance * * @param payload - Payload response from the API */ getInstance(payload: ReservationPayload): ReservationInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { ReservationCallStatus, ReservationConferenceEvent, ReservationContext, ReservationInstance, ReservationInstanceUpdateOptions, ReservationList, ReservationListInstance, ReservationListInstanceEachOptions, ReservationListInstanceOptions, ReservationListInstancePageOptions, ReservationPage, ReservationPayload, ReservationResource, ReservationSolution, ReservationStatus, ReservationSupervisorMode }
the_stack
import * as _ from 'lodash'; import * as request from 'xhr-request'; import { DataSourcePlugin, IOptions } from '../DataSourcePlugin'; import { appInsightsUri } from './common'; import ApplicationInsightsConnection from '../../connections/application-insights'; import { DataSourceConnector, IDataSource } from '../../DataSourceConnector'; import * as formats from '../../../utils/data-formats'; import ConfigurationsStore from '../../../stores/ConfigurationsStore'; let connectionType = new ApplicationInsightsConnection(); interface IQueryParams { query?: ((dependencies: any) => string) | string; mappings?: (string | object)[]; table?: string; queries?: IDictionary; filters?: Array<IFilterParams>; calculated?: (results: any) => object; } interface IFilterParams { dependency: string; queryProperty: string; } export default class ApplicationInsightsQuery extends DataSourcePlugin<IQueryParams> { type = 'ApplicationInsights-Query'; defaultProperty = 'values'; connectionType = connectionType.type; /** * @param options - Options object * @param connections - List of available connections */ constructor(options: IOptions<IQueryParams>, connections: IDict<IStringDictionary>) { super(options, connections); this.validateTimespan(this._props); this.validateParams(this._props.params); } /** * update - called when dependencies are created * @param {object} dependencies * @param {function} callback */ dependenciesUpdated(dependencies: any) { let emptyDependency = false; Object.keys(this._props.dependencies).forEach((key) => { // we use the 'optional_' naming convention key, to setup an optoinal dependacy. if (!key.startsWith('optional_') && typeof dependencies[key] === 'undefined') { emptyDependency = true; } }); // If one of the dependencies is not supplied, do not run the query if (emptyDependency) { return (dispatch) => { return dispatch(); }; } // Validate connection let connection = this.getConnection(); let { appId, apiKey } = connection; if (!connection || !apiKey || !appId) { return (dispatch) => { return dispatch(); }; } let { queryTimespan } = dependencies; let params = this._props.params; let tableNames: Array<string> = []; let mappings: Array<any> = []; let queries: IDictionary = {}; let table: string = null; let filters: Array<IFilterParams> = params.filters || []; // Checking if this is a single query or a fork query let query: string; let isForked = !params.query && !!params.table; if (!isForked) { let queryKey = this._props.id; query = this.query(params.query, dependencies, isForked, queryKey, filters); mappings.push(params.mappings); } else { queries = params.queries || {}; table = params.table; query = ` ${table} | fork `; Object.keys(queries).forEach((key) => { let queryParams = queries[key]; filters = queryParams.filters || []; tableNames.push(key); mappings.push(queryParams.mappings); query += this.query(queryParams.query, dependencies, isForked, key, filters); return true; }); } let dashboardId = ConfigurationsStore.getState().dashboard.id; return (dispatch) => { request( '/applicationInsights/query', { method: 'POST', json: true, body: { query, queryTimespan, appId, dashboardId } }, (error, json) => { if (error) { return this.failure(error); } if (json.error) { return json.error.code === 'PathNotFoundError' ? this.failure(new Error( `There was a problem getting results from Application Insights. Make sure the connection string is good. ${JSON.stringify(json)}`)) : this.failure(json.error); } // Check if result is valid let tables = this.mapAllTables(json, mappings); let resultStatus: IQueryStatus[] = tables[tables.length - 1]; if (!resultStatus || !resultStatus.length) { return dispatch(json); } // Map tables to appropriate results let resultTables = tables.filter((aTable, idx) => { return idx < resultStatus.length && (resultStatus[idx].Kind === 'QueryResult' || resultStatus[idx].Kind === 'PrimaryResults'); }); let returnedResults = { values: (resultTables.length && resultTables[0]) || null }; tableNames.forEach((aTable: string, idx: number) => { returnedResults[aTable] = resultTables.length > idx ? resultTables[idx] : null; // Get state for filter selection const prevState = DataSourceConnector.getDataSource(this._props.id).store.getState(); // Extract data formats let format = queries[aTable].format; if (format) { format = typeof format === 'string' ? { type: format } : format; format = _.extend({ args: {} }, format); format.args = _.extend({ prefix: aTable + '-' }, format.args); let result = { values: returnedResults[aTable] }; let formatExtract = DataSourceConnector.handleDataFormat(format, this, result, dependencies); if (formatExtract) { Object.assign(returnedResults, formatExtract); } } // Extracting calculated values let calc = queries[aTable].calculated; if (typeof calc === 'function') { let additionalValues = calc(returnedResults[aTable], dependencies, prevState) || {}; Object.assign(returnedResults, additionalValues); } }); return dispatch(returnedResults); } ); }; } updateSelectedValues(dependencies: IDictionary, selectedValues: any) { if (Array.isArray(selectedValues)) { return Object.assign(dependencies, { 'selectedValues': selectedValues }); } else { return Object.assign(dependencies, { ... selectedValues }); } } getElementQuery(dataSource: IDataSource, dependencies: IDict<any>, partialQuery: string, queryFilters: any): string { let timespan = '30d'; const table = dataSource && dataSource['config'] && dataSource['config'].params && dataSource['config'].params.table || null; if (dependencies && dependencies['timespan'] && dependencies['timespan']['queryTimespan']) { timespan = dependencies['timespan']['queryTimespan']; timespan = this.convertApplicationInsightsTimespan(timespan); } else if (dependencies && dependencies['queryTimespan']) { // handle dialog params timespan = dependencies['queryTimespan']; timespan = this.convertApplicationInsightsTimespan(timespan); } const filter = this.formatApplicationInsightsFilterString(queryFilters, dependencies); const query = this.formatApplicationInsightsQueryString(partialQuery, timespan, filter, table); return query; } private mapAllTables(results: IQueryResults, mappings: Array<IDictionary>): any[][] { if (!results || !results.Tables || !results.Tables.length) { return []; } return results.Tables.map((table, idx) => this.mapTable(table, mappings[idx])); } /** * Map the AI results array into JSON objects * @param table Results table to be mapped into JSON object * @param mappings additional mappings to activate of the row */ private mapTable(table: IQueryResult, mappings: IDictionary): Array<any> { mappings = mappings || {}; return table.Rows.map((rowValues, rowIdx) => { let row = {}; table.Columns.forEach((col, idx) => { row[col.ColumnName] = rowValues[idx]; }); // Going over user defined mappings of the values Object.keys(mappings).forEach(col => { row[col] = typeof mappings[col] === 'function' ? mappings[col](row[col], row, rowIdx) : mappings[col]; }); return row; }); } private compileQuery(query: any, dependencies: any): string { return typeof query === 'function' ? query(dependencies) : query; } private query(query: any, dependencies: any, isForked: boolean, queryKey: string, filters: IFilterParams[]): string { let q = this.compileQuery(query, dependencies); // Don't filter a filter query, or no filters specified if (queryKey.startsWith('filter') || filters === undefined || filters.length === 0) { return this.formatQuery(q, isForked); } // Apply selected filters to connected query filters.every((filter) => { const { dependency, queryProperty } = filter; const selectedFilters = dependencies[dependency] || []; if (selectedFilters.length > 0) { const f = 'where ' + selectedFilters.map((value) => `${queryProperty}=="${value}"`).join(' or '); q = isForked ? ` ${f} |\n ${q} ` : q.replace(/^(\s?\w+\s*?){1}(.)*/gim, '$1 | ' + f + ' $2'); return true; } return false; }); return this.formatQuery(q, isForked); } private formatQuery(query: string, isForked: boolean = true) { return isForked ? ` (${query}) \n\n` : query; } private validateTimespan(props: any) { if (!props.dependencies.queryTimespan) { throw new Error('AIAnalyticsEvents requires dependencies: timespan; queryTimespan'); } } private validateParams(params: IQueryParams): void { if (params.query) { if (params.table || params.queries) { throw new Error('Application Insights query should either have { query } or { table, queries } under params.'); } if (typeof params.query !== 'string' && typeof params.query !== 'function') { throw new Error('{ query } param should either be a function or a string.'); } } if (params.table) { if (!params.queries) { return this.failure( new Error('Application Insights query should either have { query } or { table, queries } under params.') ); } if (typeof params.table !== 'string' || typeof params.queries !== 'object' || Array.isArray(params.queries)) { throw new Error('{ table, queries } should be of types { "string", { query1: {...}, query2: {...} } }.'); } } if (!params.query && !params.table) { throw new Error('{ table, queries } should be of types { "string", { query1: {...}, query2: {...} } }.'); } } // element export formatting functions private formatApplicationInsightsQueryString(query: string, timespan: string, filter: string, table?: string) { let str = query.replace(/(\|)((\s??\n\s??)(.+?))/gm, '\n| $4'); // move '|' to start of each line str = str.replace(/(\s?\|\s?)([^\|])/gim, '\n| $2'); // newline on '|' str = str.replace(/(\sand\s)/gm, '\n $1'); // newline on 'and' str = str.replace(/([^\(\'\"])(,\s*)(?=(\w+[^\)\'\"]\w+))/gim, '$1,\n '); // newline on ',' const timespanQuery = '| where timestamp > ago(' + timespan + ') \n'; // Checks for '|' at start const matches = str.match(/^(\s*\||\s*\w+\s*\|)/ig); const start = (!matches || matches.length !== 1) ? '| ' : ''; if (table) { str = table + ' \n' + timespanQuery + filter + start + str; } else { // Insert timespan and filter after table name str = str.replace(/^\s*(\w+)\s*/gi, '$1 \n' + timespanQuery + filter + start); } return str; } private formatApplicationInsightsFilterString(filters: IStringDictionary[], dependencies: IDict<any>) { let str = ''; if (!filters) { return str; } // Apply selected filters to connected query filters.forEach((filter) => { const { dependency, queryProperty } = filter; const selectedFilters: string[] = dependencies[dependency] || []; if (selectedFilters.length > 0) { const f = '| where ' + selectedFilters.map((value) => `${queryProperty}=="${value}"`).join(' or '); str = `${str}${f} \n`; } }); return str; } private convertApplicationInsightsTimespan(timespan: string) { let str = timespan; if (timespan.substr(0, 2) === 'PT') { str = str.substring(2).toLowerCase(); } else if (timespan.substr(0, 1) === 'P') { str = str.substring(1).toLowerCase(); } return str; } }
the_stack
import { Book, translations, mechanicsEngine, Language, Section, state } from ".."; /** * Item effect / usage description */ export interface ItemEffect { /** Combat.COMBATSKILL for combat skill increment. Item.ENDURANCE for endurance points increment. */ cls: string; /** Attribute increment */ increment: number; } /** * Game object information */ export class Item { // Item effect classes (see ItemEffect interface) public static readonly COMBATSKILL = "combatSkill"; public static readonly ENDURANCE = "endurance"; // Object types /** Special item type */ public static readonly SPECIAL = "special"; /** Backpack item type */ public static readonly OBJECT = "object"; /** Weapon item type */ public static readonly WEAPON = "weapon"; // Object ids public static readonly MONEY = "money"; public static readonly QUIVER = "quiver"; public static readonly ARROW = "arrow"; public static readonly MAP = "map"; public static readonly BOW = "bow"; public static readonly MEAL = "meal"; public static readonly BACKPACK = "backpack"; public static readonly HELSHEZAG = "helshezag"; /** Allowed Special Items to carry to Grand Master from previous series */ public static readonly ALLOWED_GRAND_MASTER = ["crystalstar", "sommerswerd", "silverhelm", "daggerofvashna", "silverbracers", "jewelledmace", "silverbowduadon", "helshezag", "kagonitechainmail", "korliniumscabbard"]; /** The object type (Item.SPECIAL, Item.OBJECT or Item.WEAPON) */ public type: string; /** The object id */ public id: string; /** The translated object name */ public name: string; /** True if the object is a meal */ public isMeal: boolean; /** True if the object is an Arrow */ public isArrow: boolean; /** True if the object can be dropped */ public droppable: boolean; /** * Number of items the object it occupies on the backpack. * It can be zero. It can be decimal (ex. 0.5) * It's used too for the Special Items max. limit */ public itemCount: number; /** The translated object description */ public description: string; /** * Translated extra description. * It's optional (can be null) */ public extraDescription: string = null; /** * The weapon type. Only for special and object types. It is the kind of weapon. * If it can be handled as more than one weapon type, separate the with a '|'. * Ex. 'sword|shortsword' */ public weaponType: string; /** Object image URL, untranslated. null if the object has no image. */ private imageUrl: string; /** * The book number that contains the image (1-index based). * Needed to check if the book has been downloaded on the Cordova app */ private imageBookNumber: number; /** * Combat skill increment. * If it's a weapon, only when it's the current weapon. Otherwise, when the player carry the object */ public combatSkillEffect: number = 0; /** Endurance increment when the player carry the object */ public enduranceEffect: number = 0; /** Usage effect */ public usage: ItemEffect; /** * Number of allowed uses of the item. * After this number of uses, it will be dropped. Only applies if usage is not null. */ public usageCount: number; /** Object ids that cannot be carried at same time with this object. * Empty array if there are no incompatibilities */ public incompatibleWith: string[] = []; /** * Game object information * @param book The owner book * @param $o The XML tag with the object info * @param objectId The object identifier */ constructor(book: Book, $o: JQuery<Element>, objectId: string) { /** The object type ('special', 'object' or 'weapon' ) */ this.type = $o.prop("tagName"); /** The object id */ this.id = objectId; // The translated object name this.name = Item.getTranslatedTag($o, book, "name"); // True if the object is a meal this.isMeal = $o.attr("isMeal") === "true"; // True if the object is an Arrow this.isArrow = $o.attr("isArrow") === "true"; /** True if the object can be dropped */ this.droppable = $o.attr("droppable") !== "false"; /** Number of items the object it occupies on the backpack */ const txtItemCount: string = $o.attr("itemCount"); this.itemCount = txtItemCount ? parseFloat(txtItemCount) : 1; /** Number of usage of the object */ const txtUsageCount: string = $o.attr("usageCount"); this.usageCount = txtUsageCount ? parseInt(txtUsageCount, 10) : 1; // The translated object description this.description = Item.getTranslatedTag($o, book, "description"); // If it's the map, add description from the book: if (objectId === Item.MAP) { this.assignMapDescription(book); } if (this.itemCount !== 1) { // Add description of the size used if (this.description) { this.description += " "; } this.description += translations.text("countAsObjects", [this.itemCount]); } // Extra description this.extraDescription = Item.getTranslatedTag($o, book, "extraDescription"); /** * The weapon type. Only for special and object types. It is the kind of weapon. * If it can be handled as more than one weapon type, separate the with a '|'. * Ex. 'sword|shortsword' */ this.weaponType = $o.attr("weaponType"); // Object image this.loadImageInfo($o); // Usage (only one use, and then the object is dropped) const $usage = $o.find("usage"); if ($usage.length > 0) { this.usage = { cls: $usage.attr("class"), increment: parseInt($usage.attr("increment"), 10) }; } // Effects (when the player carry the object) const $effects = $o.find("effect"); for (const effect of $effects.toArray()) { const $effect = $(effect); const increment = parseInt($effect.attr("increment"), 10); const cls: string = $effect.attr("class"); if (cls === Item.COMBATSKILL) { this.combatSkillEffect = increment; } else if (cls === Item.ENDURANCE) { this.enduranceEffect = increment; } else { mechanicsEngine.debugWarning("Object " + this.id + ", wrong class effect: " + cls); } } // Incompatibilities this.incompatibleWith = mechanicsEngine.getArrayProperty($o, "incompatibleWith"); } private static getTranslatedTag($o: JQuery<Element>, book: Book, tagName: string) { let text = $o.find(tagName + "[lang=" + book.language + "]").text(); if (!text && book.language !== Language.ENGLISH) { // Maybe object is untranslated. Try to get the english text text = $o.find(tagName + "[lang=" + Language.ENGLISH + "]").text(); } return text; } private assignMapDescription(book: Book) { // Exception with book 11: The "map" section refers to "Northern Magnamund", no the real map at sect233 if (book.bookNumber === 11) { return; } const mapSection = new Section(book, Book.MAP_SECTION, null); if (mapSection.exists()) { this.description = mapSection.getTitleText(); } } /** Returns true if the object is a weapon */ public isWeapon(): boolean { if (this.weaponType) { return true; } return this.type === "weapon"; } /** * Returns true if the object is a weapon of a given type * @param weaponType The weapon type to check * @return True if the object is a weapon of the given type */ public isWeaponType(weaponType: string): boolean { if (this.id === weaponType) { return true; } if (this.weaponType) { return this.weaponType.split("|").contains(weaponType); } return false; } /** Returns true if this is a hand-to-hand weapon (not a bow) */ public isHandToHandWeapon(): boolean { if (!this.isWeapon()) { return false; } if (this.id === "bow" || this.weaponType === "bow") { return false; } return true; } /** * Get the object image URL. * @return The object image URL. null if the object has no image or we are * running the Cordova app and the book for the image is not downloaded */ public getImageUrl(): string { if (!this.imageUrl) { return null; } // Cordova app: Check if the book where is the image is downloaded if (!state.localBooksLibrary.isBookDownloaded(this.imageBookNumber)) { return null; } return this.imageUrl; } /** * Get information about the image * @param {jQuery} $o XML node for object */ private loadImageInfo($o: any) { const $image = $o.find("image"); if ($image.length === 0) { return; } // Get the book number: const candidateBookNumbers: number[] = []; const txtBook: string = $image.attr("book"); for (const txtBookNumber of txtBook.split("|")) { candidateBookNumbers.push(parseInt(txtBookNumber, 10)); } if (candidateBookNumbers.length === 0) { return; } candidateBookNumbers.sort(); // Default to the first one this.imageBookNumber = candidateBookNumbers[0]; if (candidateBookNumbers.length > 1) { // Choose the last played (or playing) book. for (let i = candidateBookNumbers.length - 1; i >= 0; i--) { if (state.book.bookNumber >= candidateBookNumbers[i] && state.localBooksLibrary.isBookDownloaded(candidateBookNumbers[i])) { this.imageBookNumber = candidateBookNumbers[i]; break; } } } const imageBook = new Book(this.imageBookNumber, state.book.language); this.imageUrl = imageBook.getIllustrationURL($image.attr("name")); } }
the_stack
import { Component } from 'react'; import { NativeEventSubscription } from 'react-native'; import { HmsPushEvent, RNRemoteMessage, HmsPushMessaging, HmsPushInstanceId, HmsLocalNotification, HmsPushOpenDevice, RemoteMessageBuilder, HmsPushProfile, HmsPushResultCode, } from '@hmscore/react-native-hms-push'; interface State { topic: string; subjectId: string; } export default class App extends Component<{}, State> { onRemoteMessageReceivedListener: NativeEventSubscription; onTokenReceivedListener: NativeEventSubscription; onTokenErrorListener: NativeEventSubscription; onMultiSenderTokenReceivedListener: NativeEventSubscription; onMultiSenderTokenErrorListener: NativeEventSubscription; onPushMessageSentListener: NativeEventSubscription; onMessageSentErrorListener: NativeEventSubscription; onMessageSentDeliveredListener: NativeEventSubscription; onLocalNotificationActionListener: NativeEventSubscription; onNotificationOpenedAppListener: NativeEventSubscription; constructor(props: {}) { super(props); this.state = { topic: '', subjectId: '<project_id>', }; this.componentDidMount = this.componentDidMount.bind(this); } componentDidMount() { this.onRemoteMessageReceivedListener = HmsPushEvent.onRemoteMessageReceived(result => { const RNRemoteMessageObj = new RNRemoteMessage(result.msg); HmsLocalNotification.localNotification({ [HmsLocalNotification.Attr.title]: 'DataMessage Received', [HmsLocalNotification.Attr.message]: RNRemoteMessageObj.getDataOfMap(), }); console.log('onRemoteMessageReceived', result); }); this.onTokenReceivedListener = HmsPushEvent.onTokenReceived(result => { console.log('onTokenReceived', result); }); this.onTokenErrorListener = HmsPushEvent.onTokenError(result => { console.log('onTokenError', result); if (result.result_code === HmsPushResultCode.ERROR_CLIENT_API_INVALID) { console.log('Invalid Client'); } }); this.onMultiSenderTokenReceivedListener = HmsPushEvent.onMultiSenderTokenReceived(result => { console.log('onMultiSenderTokenReceived', result); }); this.onMultiSenderTokenErrorListener = HmsPushEvent.onMultiSenderTokenError(result => { console.log('onMultiSenderTokenError', result); }); this.onPushMessageSentListener = HmsPushEvent.onPushMessageSent(result => { console.log('onPushMessageSent', result); }); this.onMessageSentErrorListener = HmsPushEvent.onPushMessageSentError(result => { console.log('onMessageSentError', result); }); this.onMessageSentDeliveredListener = HmsPushEvent.onPushMessageSentDelivered(result => { console.log('onMessageSentDelivered', result); }); this.onLocalNotificationActionListener = HmsPushEvent.onLocalNotificationAction(result => { console.log('onLocalNotificationAction', result); const notification = JSON.parse(result.dataJSON); if (notification.action === 'Yes') { HmsLocalNotification.cancelNotificationsWithId([notification.id]); } console.log('onLocalNotificationAction-Clicked', notification.action); }); this.onNotificationOpenedAppListener = HmsPushEvent.onNotificationOpenedApp(result => { console.log('onNotificationOpenedApp', result); }); } componentWillUnmount() { this.onRemoteMessageReceivedListener.remove(); this.onTokenReceivedListener.remove(); this.onTokenErrorListener.remove(); this.onMultiSenderTokenReceivedListener.remove(); this.onMultiSenderTokenErrorListener.remove(); this.onPushMessageSentListener.remove(); this.onMessageSentErrorListener.remove(); this.onMessageSentDeliveredListener.remove(); this.onLocalNotificationActionListener.remove(); this.onNotificationOpenedAppListener.remove(); } onChangeTopic(inputData: string) { this.setState({ topic: inputData, }); } turnOnPush() { HmsPushMessaging.turnOnPush() .then(result => { console.log('turnOnPush', result); }) .catch(err => { console.log('[turnOnPush] Error/Exception: ' + JSON.stringify(err)); }); } turnOffPush() { HmsPushMessaging.turnOffPush() .then(result => { console.log('turnOffPush', result); }) .catch(err => { console.log('[turnOffPush] Error/Exception: ' + JSON.stringify(err)); }); } getID() { HmsPushInstanceId.getId() .then(result => { console.log('getId', result); }) .catch(err => { console.log('[getID] Error/Exception: ' + JSON.stringify(err)); }); } getAAID() { HmsPushInstanceId.getAAID() .then(result => { console.log('getAAID', result); }) .catch(err => { console.log('[getAAID] Error/Exception: ' + JSON.stringify(err)); }); } getOdid() { HmsPushOpenDevice.getOdid() .then(result => { console.log('getOdid', result); }) .catch(err => { console.log('[getOdid] Error/Exception: ' + JSON.stringify(err)); }); } getToken() { HmsPushInstanceId.getToken('') .then(result => { console.log('getToken', result); }) .catch(err => { console.log('[getToken] Error/Exception: ' + JSON.stringify(err)); }); } getTokenWithSubjectId() { HmsPushInstanceId.getTokenWithSubjectId(this.state.subjectId) .then(result => { console.log('getTokenWithSubjectId', result); }) .catch(err => { console.log('[getTokenWithSubjectId] Error/Exception: ' + JSON.stringify(err)); }); } getCreationTime() { HmsPushInstanceId.getCreationTime() .then(result => { console.log('getCreationTime', result); }) .catch(err => { console.log('[getCreationTime] Error/Exception: ' + JSON.stringify(err)); }); } deleteAAID() { HmsPushInstanceId.deleteAAID() .then(result => { console.log('deleteAAID', result); }) .catch(err => { console.log('[deleteAAID] Error/Exception: ' + JSON.stringify(err)); }); } deleteToken() { HmsPushInstanceId.deleteToken('') .then(result => { console.log('deleteToken', result); }) .catch(err => { console.log('[deleteToken] Error/Exception: ' + JSON.stringify(err)); }); } deleteTokenWithSubjectId() { HmsPushInstanceId.deleteTokenWithSubjectId(this.state.subjectId) .then(result => { console.log('deleteTokenWithSubjectId', result); }) .catch(err => { console.log('[deleteTokenWithSubjectId] Error/Exception: ' + JSON.stringify(err)); }); } subscribe() { HmsPushMessaging.subscribe(this.state.topic) .then(result => { console.log('subscribe', result); }) .catch(err => { console.log(JSON.stringify(err)); console.log('[subscribe] Error/Exception: ' + JSON.stringify(err)); }); } unsubscribe() { HmsPushMessaging.unsubscribe(this.state.topic) .then(result => { console.log('unsubscribe', result); }) .catch(err => { console.log('[unsubscribe] Error/Exception: ' + JSON.stringify(err)); }); } sendRemoteMessage() { HmsPushMessaging.sendRemoteMessage({ [RemoteMessageBuilder.TO]: '', // [RemoteMessageBuilder.MESSAGE_ID]: '', // Auto generated [RemoteMessageBuilder.MESSAGE_TYPE]: 'hms', [RemoteMessageBuilder.COLLAPSE_KEY]: '-1', [RemoteMessageBuilder.TTL]: 120, [RemoteMessageBuilder.RECEIPT_MODE]: 1, [RemoteMessageBuilder.SEND_MODE]: 1, [RemoteMessageBuilder.DATA]: { key1: 'test', message: 'huawei-test' }, }) .then(result => { console.log('sendRemoteMessage', result); }) .catch(err => { console.log('[sendRemoteMessage] Error/Exception: ' + JSON.stringify(err)); }); } isAutoInitEnabled() { HmsPushMessaging.isAutoInitEnabled() .then(result => { console.log('isAutoInitEnabled', result); }) .catch(err => { console.log('[isAutoInitEnabled] Error/Exception: ' + JSON.stringify(err)); }); } setAutoInitEnabled(value: boolean) { HmsPushMessaging.setAutoInitEnabled(value) .then(result => { console.log('setAutoInitEnabled', result); }) .catch(err => { console.log('[setAutoInitEnabled] Error/Exception: ' + JSON.stringify(err)); }); } getInitialNotification() { HmsPushMessaging.getInitialNotification() .then(result => { console.log('getInitialNotification', result); }) .catch(err => { console.log('[getInitialNotification] Error/Exception: ' + JSON.stringify(err)); }); } isSupportProfile() { HmsPushProfile.isSupportProfile() .then(result => { console.log('isSupportProfile', result); }) .catch(err => { console.log('[isSupportProfile] Error/Exception: ' + JSON.stringify(err)); }); } addProfile() { HmsPushProfile.addProfile(HmsPushProfile.Type.HUAWEI_PROFILE, 'profileId') .then(result => { console.log('addProfile', result); }) .catch(err => { console.log('[addProfile] Error/Exception: ' + JSON.stringify(err)); }); } addProfileWithSubjectId() { HmsPushProfile.addProfileWithSubjectId('<subject_Id>', HmsPushProfile.Type.HUAWEI_PROFILE, '<profileId>') .then(result => { console.log('addProfileWithSubjectId', result); }) .catch(err => { console.log('[addProfileWithSubjectId] Error/Exception: ' + JSON.stringify(err)); }); } deleteProfile() { HmsPushProfile.deleteProfile('<profile_Id>') .then(result => { console.log('deleteProfile', result); }) .catch(err => { console.log('[deleteProfile] Error/Exception: ' + JSON.stringify(err)); }); } deleteProfileWithSubjectId() { HmsPushProfile.deleteProfileWithSubjectId('<subject_Id>', '<profile_Id>') .then(result => { console.log('deleteProfileWithSubjectId', result); }) .catch(err => { console.log('[deleteProfileWithSubjectId] Error/Exception: ' + JSON.stringify(err)); }); } render() { return null; } }
the_stack
import { FormBuilder, Validators, FormGroup, FormArray } from '@angular/forms'; import { Injectable } from '@angular/core'; import { AlgorithmsEnum, EarlyStoppingAlgorithmsEnum, } from '../enumerations/algorithms.enum'; import { createParameterGroup, createNasOperationGroup } from '../shared/utils'; import { SnackBarService, SnackType } from 'kubeflow'; import { load } from 'js-yaml'; import { ObjectiveSpec, AlgorithmSpec, ParameterSpec, FeasibleSpaceMinMax, NasOperation, AlgorithmSetting, } from '../models/experiment.k8s.model'; import { CollectorKind } from '../enumerations/metrics-collector'; @Injectable() export class ExperimentFormService { constructor(private builder: FormBuilder, private snack: SnackBarService) {} /* * functions for creating the Form Controls */ createMetadataForm(namespace): FormGroup { return this.builder.group({ name: 'random-experiment', namespace, }); } createTrialThresholdForm(): FormGroup { return this.builder.group({ parallelTrialCount: 3, maxTrialCount: 12, maxFailedTrialCount: 3, resumePolicy: 'LongRunning', }); } createObjectiveForm(): FormGroup { return this.builder.group({ type: 'maximize', goal: 0.99, metricName: 'Validation-accuracy', metricStrategy: 'max', additionalMetricNames: this.builder.array(['Train-accuracy']), metricStrategies: this.builder.array([]), setStrategies: this.builder.control(false), }); } createAlgorithmObjectiveForm(): FormGroup { return this.builder.group({ type: 'hp', algorithm: AlgorithmsEnum.RANDOM, algorithmSettings: this.builder.array([]), }); } createEarlyStoppingForm(): FormGroup { return this.builder.group({ algorithmName: EarlyStoppingAlgorithmsEnum.NONE, algorithmSettings: this.builder.array([]), }); } createHyperParametersForm(): FormArray { return this.builder.array([ createParameterGroup({ name: 'lr', parameterType: 'double', feasibleSpace: { min: '0.01', max: '0.03', step: '0.01', }, }), createParameterGroup({ name: 'num-layers', parameterType: 'int', feasibleSpace: { min: '1', max: '64', step: '1', }, }), createParameterGroup({ name: 'optimizer', parameterType: 'categorical', feasibleSpace: { list: ['sgd', 'adam', 'ftrl'] }, }), ]); } createNasGraphForm(): FormGroup { return this.builder.group({ layers: 8, inputSizes: this.builder.array([32, 32, 3]), outputSizes: this.builder.array([10]), }); } createNasOperationsForm(): FormArray { return this.builder.array([ createNasOperationGroup({ operationType: 'convolution', parameters: [ { name: 'filter_size', parameterType: 'categorical', feasibleSpace: { list: ['3', '5', '7'] }, }, { name: 'num_filter', parameterType: 'categorical', feasibleSpace: { list: ['32', '48', '64'] }, }, { name: 'stride', parameterType: 'categorical', feasibleSpace: { list: ['1', '2'] }, }, ], }), createNasOperationGroup({ operationType: 'separable_convolution', parameters: [ { name: 'filter_size', parameterType: 'categorical', feasibleSpace: { list: ['3', '5', '7'] }, }, { name: 'num_filter', parameterType: 'categorical', feasibleSpace: { list: ['32', '48', '64'] }, }, { name: 'stride', parameterType: 'categorical', feasibleSpace: { list: ['1', '2'] }, }, { name: 'depth_multiplier', parameterType: 'categorical', feasibleSpace: { list: ['1', '2'] }, }, ], }), createNasOperationGroup({ operationType: 'depthwise_convolution', parameters: [ { name: 'filter_size', parameterType: 'categorical', feasibleSpace: { list: ['3', '5', '7'] }, }, { name: 'num_filter', parameterType: 'categorical', feasibleSpace: { list: ['32', '48', '64'] }, }, { name: 'depth_multiplier', parameterType: 'categorical', feasibleSpace: { list: ['1', '2'] }, }, ], }), createNasOperationGroup({ operationType: 'reduction', parameters: [ { name: 'reduction_type', parameterType: 'categorical', feasibleSpace: { list: ['max_pooling', 'avg_pooling'] }, }, { name: 'pool_size', parameterType: 'int', feasibleSpace: { min: '2', max: '3', step: '1', }, }, ], }), ]); } createMetricsForm(): FormGroup { return this.builder.group({ kind: CollectorKind.STDOUT, metricsFile: '/var/log/katib/metrics.log', tfDir: '/var/log/katib/tfevent/', prometheus: this.builder.group({ port: this.builder.control('8080', Validators.required), path: this.builder.control('/metrics', Validators.required), scheme: this.builder.control('HTTP', Validators.required), host: this.builder.control(''), httpHeaders: this.builder.array([]), }), }); } createTrialTemplateForm(): FormGroup { return this.builder.group({ type: 'yaml', podLabels: this.builder.array([]), containerName: 'training-container', successCond: 'status.conditions.#(type=="Complete")#|#(status=="True")#', failureCond: 'status.conditions.#(type=="Failed")#|#(status=="True")#', retain: 'false', cmNamespace: '', cmName: '', cmTrialPath: '', yaml: '', trialParameters: this.builder.array([]), }); } /** * helpers for parsing the form controls */ parseParam(parameter: ParameterSpec): ParameterSpec { // we should omit the step in case it was not defined const param = JSON.parse(JSON.stringify(parameter)); if ( param.parameterType === 'discrete' || param.parameterType === 'categorical' ) { return param; } if ((param.feasibleSpace as FeasibleSpaceMinMax).step === '') { delete (param.feasibleSpace as FeasibleSpaceMinMax).step; } return param; } /* * YAML helpers for moving between FormControls and actual YAML strings */ metadataFromCtrl(group: FormGroup): any { return { name: group.get('name').value, namespace: group.get('namespace').value, }; } objectiveFromCtrl(group: FormGroup): ObjectiveSpec { const objMetric = group.get('metricName').value; const objStrategy = group.get('type').value.substring(0, 3); const objective: any = { type: group.get('type').value, goal: group.get('goal').value, objectiveMetricName: objMetric, // metricStrategies: [{ name: objMetric, value: objStrategy }], additionalMetricNames: [], }; const additionalMetrics = group.get('additionalMetricNames').value || []; additionalMetrics.forEach(metric => { if (!metric) { return; } objective.additionalMetricNames.push(metric); }); if (!group.get('setStrategies').value) { return objective; } objective.metricStrategies = [{ name: objMetric, value: objStrategy }]; group.get('metricStrategies').value.forEach(metricStrategy => { objective.metricStrategies.push({ name: metricStrategy.metric, value: metricStrategy.strategy, }); }); return objective; } algorithmFromCtrl(group: FormGroup): AlgorithmSpec { const settings: AlgorithmSetting[] = []; group.get('algorithmSettings').value.forEach(setting => { if (setting.value === null) { return; } settings.push({ name: setting.name, value: `${setting.value}` }); }); return { algorithmName: group.get('algorithm').value, algorithmSettings: settings, }; } earlyStoppingFromCtrl(group: FormGroup): AlgorithmSpec { const settings: AlgorithmSetting[] = []; group.get('algorithmSettings').value.forEach(setting => { if (setting.value === null) { return; } settings.push({ name: setting.name, value: `${setting.value}` }); }); return { algorithmName: group.get('algorithmName').value, algorithmSettings: settings, }; } hyperParamsFromCtrl(paramsArray: FormArray): any { const params = paramsArray.value as ParameterSpec[]; return params.map(param => { return this.parseParam(param); }); } nasOpsFromCtrl(operations: FormArray): NasOperation[] { const ops: NasOperation[] = operations.value; return ops.map(op => { op.parameters = op.parameters.map(param => this.parseParam(param)); return op; }); } metricsCollectorFromCtrl(group: FormGroup): any { const kind = group.get('kind').value; const metrics: any = { source: { fileSystemPath: { path: '', kind: '', }, }, collector: { kind }, }; if (kind === 'StdOut' || kind === 'None') { delete metrics.source; return metrics; } if (kind === 'File') { metrics.source.fileSystemPath.path = group.get('metricsFile').value; metrics.source.fileSystemPath.kind = 'File'; return metrics; } if (kind === 'TensorFlowEvent') { metrics.source.fileSystemPath.path = group.get('tfDir').value; metrics.source.fileSystemPath.kind = 'Directory'; return metrics; } if (kind === 'PrometheusMetric') { delete metrics.source.fileSystemPath; metrics.source.httpGet = group.get('prometheus').value; if (!metrics.source.httpGet.host) { delete metrics.source.httpGet.host; } const headers = metrics.source.httpGet.httpHeaders; metrics.source.httpGet.httpHeaders = headers.map(header => { return { name: header.key, value: header.value }; }); return metrics; } /* TODO(kimwnasptd): We need to handle the Custom case */ if (kind === 'Custom') { return metrics; } return {}; } trialTemplateFromCtrl(group: FormGroup): any { const trialTemplate: any = {}; const formValue = group.value; trialTemplate.primaryContainerName = formValue.containerName; trialTemplate.successCondition = formValue.successCond; trialTemplate.failureCondition = formValue.failureCond; trialTemplate.retain = formValue.retain === 'true' ? true : false; if (formValue.podLabels && formValue.podLabels.length) { trialTemplate.primaryPodLabels = {}; formValue.podLabels.map( label => (trialTemplate.primaryPodLabels[label.key] = label.value), ); } trialTemplate.trialParameters = formValue.trialParameters; if (formValue.type === 'yaml') { try { trialTemplate.trialSpec = load(formValue.yaml); } catch (e) { this.snack.open(`${e.reason}`, SnackType.Warning, 4000); } return trialTemplate; } trialTemplate.configMap = { configMapName: formValue.cmName, configMapNamespace: formValue.cmNamespace, templatePath: formValue.cmTrialPath, }; return trialTemplate; } }
the_stack
import * as Atk from '@gi-types/atk'; import * as cairo from '@gi-types/cairo'; import * as Cogl from '@gi-types/cogl'; import * as Gio from '@gi-types/gio'; import * as GLib from '@gi-types/glib'; import * as GObject from '@gi-types/gobject'; import * as Graphene from '@gi-types/graphene'; import * as Json from '@gi-types/json'; import * as Pango from '@gi-types/pango'; export const BUTTON_MIDDLE: number; export const BUTTON_PRIMARY: number; export const BUTTON_SECONDARY: number; export const COGL: string; export const CURRENT_TIME: number; export const EVENT_PROPAGATE: boolean; export const EVENT_STOP: boolean; export const FLAVOUR: string; export const HAS_WAYLAND_COMPOSITOR_SUPPORT: number; export const INPUT_EVDEV: string; export const INPUT_NULL: string; export const INPUT_X11: string; export const KEY_0: number; export const KEY_1: number; export const KEY_2: number; export const KEY_3: number; export const KEY_3270_AltCursor: number; export const KEY_3270_Attn: number; export const KEY_3270_BackTab: number; export const KEY_3270_ChangeScreen: number; export const KEY_3270_Copy: number; export const KEY_3270_CursorBlink: number; export const KEY_3270_CursorSelect: number; export const KEY_3270_DeleteWord: number; export const KEY_3270_Duplicate: number; export const KEY_3270_Enter: number; export const KEY_3270_EraseEOF: number; export const KEY_3270_EraseInput: number; export const KEY_3270_ExSelect: number; export const KEY_3270_FieldMark: number; export const KEY_3270_Ident: number; export const KEY_3270_Jump: number; export const KEY_3270_KeyClick: number; export const KEY_3270_Left2: number; export const KEY_3270_PA1: number; export const KEY_3270_PA2: number; export const KEY_3270_PA3: number; export const KEY_3270_Play: number; export const KEY_3270_PrintScreen: number; export const KEY_3270_Quit: number; export const KEY_3270_Record: number; export const KEY_3270_Reset: number; export const KEY_3270_Right2: number; export const KEY_3270_Rule: number; export const KEY_3270_Setup: number; export const KEY_3270_Test: number; export const KEY_4: number; export const KEY_5: number; export const KEY_6: number; export const KEY_7: number; export const KEY_8: number; export const KEY_9: number; export const KEY_A: number; export const KEY_AE: number; export const KEY_Aacute: number; export const KEY_Abelowdot: number; export const KEY_Abreve: number; export const KEY_Abreveacute: number; export const KEY_Abrevebelowdot: number; export const KEY_Abrevegrave: number; export const KEY_Abrevehook: number; export const KEY_Abrevetilde: number; export const KEY_AccessX_Enable: number; export const KEY_AccessX_Feedback_Enable: number; export const KEY_Acircumflex: number; export const KEY_Acircumflexacute: number; export const KEY_Acircumflexbelowdot: number; export const KEY_Acircumflexgrave: number; export const KEY_Acircumflexhook: number; export const KEY_Acircumflextilde: number; export const KEY_AddFavorite: number; export const KEY_Adiaeresis: number; export const KEY_Agrave: number; export const KEY_Ahook: number; export const KEY_Alt_L: number; export const KEY_Alt_R: number; export const KEY_Amacron: number; export const KEY_Aogonek: number; export const KEY_ApplicationLeft: number; export const KEY_ApplicationRight: number; export const KEY_Arabic_0: number; export const KEY_Arabic_1: number; export const KEY_Arabic_2: number; export const KEY_Arabic_3: number; export const KEY_Arabic_4: number; export const KEY_Arabic_5: number; export const KEY_Arabic_6: number; export const KEY_Arabic_7: number; export const KEY_Arabic_8: number; export const KEY_Arabic_9: number; export const KEY_Arabic_ain: number; export const KEY_Arabic_alef: number; export const KEY_Arabic_alefmaksura: number; export const KEY_Arabic_beh: number; export const KEY_Arabic_comma: number; export const KEY_Arabic_dad: number; export const KEY_Arabic_dal: number; export const KEY_Arabic_damma: number; export const KEY_Arabic_dammatan: number; export const KEY_Arabic_ddal: number; export const KEY_Arabic_farsi_yeh: number; export const KEY_Arabic_fatha: number; export const KEY_Arabic_fathatan: number; export const KEY_Arabic_feh: number; export const KEY_Arabic_fullstop: number; export const KEY_Arabic_gaf: number; export const KEY_Arabic_ghain: number; export const KEY_Arabic_ha: number; export const KEY_Arabic_hah: number; export const KEY_Arabic_hamza: number; export const KEY_Arabic_hamza_above: number; export const KEY_Arabic_hamza_below: number; export const KEY_Arabic_hamzaonalef: number; export const KEY_Arabic_hamzaonwaw: number; export const KEY_Arabic_hamzaonyeh: number; export const KEY_Arabic_hamzaunderalef: number; export const KEY_Arabic_heh: number; export const KEY_Arabic_heh_doachashmee: number; export const KEY_Arabic_heh_goal: number; export const KEY_Arabic_jeem: number; export const KEY_Arabic_jeh: number; export const KEY_Arabic_kaf: number; export const KEY_Arabic_kasra: number; export const KEY_Arabic_kasratan: number; export const KEY_Arabic_keheh: number; export const KEY_Arabic_khah: number; export const KEY_Arabic_lam: number; export const KEY_Arabic_madda_above: number; export const KEY_Arabic_maddaonalef: number; export const KEY_Arabic_meem: number; export const KEY_Arabic_noon: number; export const KEY_Arabic_noon_ghunna: number; export const KEY_Arabic_peh: number; export const KEY_Arabic_percent: number; export const KEY_Arabic_qaf: number; export const KEY_Arabic_question_mark: number; export const KEY_Arabic_ra: number; export const KEY_Arabic_rreh: number; export const KEY_Arabic_sad: number; export const KEY_Arabic_seen: number; export const KEY_Arabic_semicolon: number; export const KEY_Arabic_shadda: number; export const KEY_Arabic_sheen: number; export const KEY_Arabic_sukun: number; export const KEY_Arabic_superscript_alef: number; export const KEY_Arabic_switch: number; export const KEY_Arabic_tah: number; export const KEY_Arabic_tatweel: number; export const KEY_Arabic_tcheh: number; export const KEY_Arabic_teh: number; export const KEY_Arabic_tehmarbuta: number; export const KEY_Arabic_thal: number; export const KEY_Arabic_theh: number; export const KEY_Arabic_tteh: number; export const KEY_Arabic_veh: number; export const KEY_Arabic_waw: number; export const KEY_Arabic_yeh: number; export const KEY_Arabic_yeh_baree: number; export const KEY_Arabic_zah: number; export const KEY_Arabic_zain: number; export const KEY_Aring: number; export const KEY_Armenian_AT: number; export const KEY_Armenian_AYB: number; export const KEY_Armenian_BEN: number; export const KEY_Armenian_CHA: number; export const KEY_Armenian_DA: number; export const KEY_Armenian_DZA: number; export const KEY_Armenian_E: number; export const KEY_Armenian_FE: number; export const KEY_Armenian_GHAT: number; export const KEY_Armenian_GIM: number; export const KEY_Armenian_HI: number; export const KEY_Armenian_HO: number; export const KEY_Armenian_INI: number; export const KEY_Armenian_JE: number; export const KEY_Armenian_KE: number; export const KEY_Armenian_KEN: number; export const KEY_Armenian_KHE: number; export const KEY_Armenian_LYUN: number; export const KEY_Armenian_MEN: number; export const KEY_Armenian_NU: number; export const KEY_Armenian_O: number; export const KEY_Armenian_PE: number; export const KEY_Armenian_PYUR: number; export const KEY_Armenian_RA: number; export const KEY_Armenian_RE: number; export const KEY_Armenian_SE: number; export const KEY_Armenian_SHA: number; export const KEY_Armenian_TCHE: number; export const KEY_Armenian_TO: number; export const KEY_Armenian_TSA: number; export const KEY_Armenian_TSO: number; export const KEY_Armenian_TYUN: number; export const KEY_Armenian_VEV: number; export const KEY_Armenian_VO: number; export const KEY_Armenian_VYUN: number; export const KEY_Armenian_YECH: number; export const KEY_Armenian_ZA: number; export const KEY_Armenian_ZHE: number; export const KEY_Armenian_accent: number; export const KEY_Armenian_amanak: number; export const KEY_Armenian_apostrophe: number; export const KEY_Armenian_at: number; export const KEY_Armenian_ayb: number; export const KEY_Armenian_ben: number; export const KEY_Armenian_but: number; export const KEY_Armenian_cha: number; export const KEY_Armenian_da: number; export const KEY_Armenian_dza: number; export const KEY_Armenian_e: number; export const KEY_Armenian_exclam: number; export const KEY_Armenian_fe: number; export const KEY_Armenian_full_stop: number; export const KEY_Armenian_ghat: number; export const KEY_Armenian_gim: number; export const KEY_Armenian_hi: number; export const KEY_Armenian_ho: number; export const KEY_Armenian_hyphen: number; export const KEY_Armenian_ini: number; export const KEY_Armenian_je: number; export const KEY_Armenian_ke: number; export const KEY_Armenian_ken: number; export const KEY_Armenian_khe: number; export const KEY_Armenian_ligature_ew: number; export const KEY_Armenian_lyun: number; export const KEY_Armenian_men: number; export const KEY_Armenian_nu: number; export const KEY_Armenian_o: number; export const KEY_Armenian_paruyk: number; export const KEY_Armenian_pe: number; export const KEY_Armenian_pyur: number; export const KEY_Armenian_question: number; export const KEY_Armenian_ra: number; export const KEY_Armenian_re: number; export const KEY_Armenian_se: number; export const KEY_Armenian_separation_mark: number; export const KEY_Armenian_sha: number; export const KEY_Armenian_shesht: number; export const KEY_Armenian_tche: number; export const KEY_Armenian_to: number; export const KEY_Armenian_tsa: number; export const KEY_Armenian_tso: number; export const KEY_Armenian_tyun: number; export const KEY_Armenian_verjaket: number; export const KEY_Armenian_vev: number; export const KEY_Armenian_vo: number; export const KEY_Armenian_vyun: number; export const KEY_Armenian_yech: number; export const KEY_Armenian_yentamna: number; export const KEY_Armenian_za: number; export const KEY_Armenian_zhe: number; export const KEY_Atilde: number; export const KEY_AudibleBell_Enable: number; export const KEY_AudioCycleTrack: number; export const KEY_AudioForward: number; export const KEY_AudioLowerVolume: number; export const KEY_AudioMedia: number; export const KEY_AudioMicMute: number; export const KEY_AudioMute: number; export const KEY_AudioNext: number; export const KEY_AudioPause: number; export const KEY_AudioPlay: number; export const KEY_AudioPrev: number; export const KEY_AudioRaiseVolume: number; export const KEY_AudioRandomPlay: number; export const KEY_AudioRecord: number; export const KEY_AudioRepeat: number; export const KEY_AudioRewind: number; export const KEY_AudioStop: number; export const KEY_Away: number; export const KEY_B: number; export const KEY_Babovedot: number; export const KEY_Back: number; export const KEY_BackForward: number; export const KEY_BackSpace: number; export const KEY_Battery: number; export const KEY_Begin: number; export const KEY_Blue: number; export const KEY_Bluetooth: number; export const KEY_Book: number; export const KEY_BounceKeys_Enable: number; export const KEY_Break: number; export const KEY_BrightnessAdjust: number; export const KEY_Byelorussian_SHORTU: number; export const KEY_Byelorussian_shortu: number; export const KEY_C: number; export const KEY_CD: number; export const KEY_CH: number; export const KEY_C_H: number; export const KEY_C_h: number; export const KEY_Cabovedot: number; export const KEY_Cacute: number; export const KEY_Calculator: number; export const KEY_Calendar: number; export const KEY_Cancel: number; export const KEY_Caps_Lock: number; export const KEY_Ccaron: number; export const KEY_Ccedilla: number; export const KEY_Ccircumflex: number; export const KEY_Ch: number; export const KEY_Clear: number; export const KEY_ClearGrab: number; export const KEY_Close: number; export const KEY_Codeinput: number; export const KEY_ColonSign: number; export const KEY_Community: number; export const KEY_ContrastAdjust: number; export const KEY_Control_L: number; export const KEY_Control_R: number; export const KEY_Copy: number; export const KEY_CruzeiroSign: number; export const KEY_Cut: number; export const KEY_CycleAngle: number; export const KEY_Cyrillic_A: number; export const KEY_Cyrillic_BE: number; export const KEY_Cyrillic_CHE: number; export const KEY_Cyrillic_CHE_descender: number; export const KEY_Cyrillic_CHE_vertstroke: number; export const KEY_Cyrillic_DE: number; export const KEY_Cyrillic_DZHE: number; export const KEY_Cyrillic_E: number; export const KEY_Cyrillic_EF: number; export const KEY_Cyrillic_EL: number; export const KEY_Cyrillic_EM: number; export const KEY_Cyrillic_EN: number; export const KEY_Cyrillic_EN_descender: number; export const KEY_Cyrillic_ER: number; export const KEY_Cyrillic_ES: number; export const KEY_Cyrillic_GHE: number; export const KEY_Cyrillic_GHE_bar: number; export const KEY_Cyrillic_HA: number; export const KEY_Cyrillic_HARDSIGN: number; export const KEY_Cyrillic_HA_descender: number; export const KEY_Cyrillic_I: number; export const KEY_Cyrillic_IE: number; export const KEY_Cyrillic_IO: number; export const KEY_Cyrillic_I_macron: number; export const KEY_Cyrillic_JE: number; export const KEY_Cyrillic_KA: number; export const KEY_Cyrillic_KA_descender: number; export const KEY_Cyrillic_KA_vertstroke: number; export const KEY_Cyrillic_LJE: number; export const KEY_Cyrillic_NJE: number; export const KEY_Cyrillic_O: number; export const KEY_Cyrillic_O_bar: number; export const KEY_Cyrillic_PE: number; export const KEY_Cyrillic_SCHWA: number; export const KEY_Cyrillic_SHA: number; export const KEY_Cyrillic_SHCHA: number; export const KEY_Cyrillic_SHHA: number; export const KEY_Cyrillic_SHORTI: number; export const KEY_Cyrillic_SOFTSIGN: number; export const KEY_Cyrillic_TE: number; export const KEY_Cyrillic_TSE: number; export const KEY_Cyrillic_U: number; export const KEY_Cyrillic_U_macron: number; export const KEY_Cyrillic_U_straight: number; export const KEY_Cyrillic_U_straight_bar: number; export const KEY_Cyrillic_VE: number; export const KEY_Cyrillic_YA: number; export const KEY_Cyrillic_YERU: number; export const KEY_Cyrillic_YU: number; export const KEY_Cyrillic_ZE: number; export const KEY_Cyrillic_ZHE: number; export const KEY_Cyrillic_ZHE_descender: number; export const KEY_Cyrillic_a: number; export const KEY_Cyrillic_be: number; export const KEY_Cyrillic_che: number; export const KEY_Cyrillic_che_descender: number; export const KEY_Cyrillic_che_vertstroke: number; export const KEY_Cyrillic_de: number; export const KEY_Cyrillic_dzhe: number; export const KEY_Cyrillic_e: number; export const KEY_Cyrillic_ef: number; export const KEY_Cyrillic_el: number; export const KEY_Cyrillic_em: number; export const KEY_Cyrillic_en: number; export const KEY_Cyrillic_en_descender: number; export const KEY_Cyrillic_er: number; export const KEY_Cyrillic_es: number; export const KEY_Cyrillic_ghe: number; export const KEY_Cyrillic_ghe_bar: number; export const KEY_Cyrillic_ha: number; export const KEY_Cyrillic_ha_descender: number; export const KEY_Cyrillic_hardsign: number; export const KEY_Cyrillic_i: number; export const KEY_Cyrillic_i_macron: number; export const KEY_Cyrillic_ie: number; export const KEY_Cyrillic_io: number; export const KEY_Cyrillic_je: number; export const KEY_Cyrillic_ka: number; export const KEY_Cyrillic_ka_descender: number; export const KEY_Cyrillic_ka_vertstroke: number; export const KEY_Cyrillic_lje: number; export const KEY_Cyrillic_nje: number; export const KEY_Cyrillic_o: number; export const KEY_Cyrillic_o_bar: number; export const KEY_Cyrillic_pe: number; export const KEY_Cyrillic_schwa: number; export const KEY_Cyrillic_sha: number; export const KEY_Cyrillic_shcha: number; export const KEY_Cyrillic_shha: number; export const KEY_Cyrillic_shorti: number; export const KEY_Cyrillic_softsign: number; export const KEY_Cyrillic_te: number; export const KEY_Cyrillic_tse: number; export const KEY_Cyrillic_u: number; export const KEY_Cyrillic_u_macron: number; export const KEY_Cyrillic_u_straight: number; export const KEY_Cyrillic_u_straight_bar: number; export const KEY_Cyrillic_ve: number; export const KEY_Cyrillic_ya: number; export const KEY_Cyrillic_yeru: number; export const KEY_Cyrillic_yu: number; export const KEY_Cyrillic_ze: number; export const KEY_Cyrillic_zhe: number; export const KEY_Cyrillic_zhe_descender: number; export const KEY_D: number; export const KEY_DOS: number; export const KEY_Dabovedot: number; export const KEY_Dcaron: number; export const KEY_Delete: number; export const KEY_Display: number; export const KEY_Documents: number; export const KEY_DongSign: number; export const KEY_Down: number; export const KEY_Dstroke: number; export const KEY_E: number; export const KEY_ENG: number; export const KEY_ETH: number; export const KEY_EZH: number; export const KEY_Eabovedot: number; export const KEY_Eacute: number; export const KEY_Ebelowdot: number; export const KEY_Ecaron: number; export const KEY_Ecircumflex: number; export const KEY_Ecircumflexacute: number; export const KEY_Ecircumflexbelowdot: number; export const KEY_Ecircumflexgrave: number; export const KEY_Ecircumflexhook: number; export const KEY_Ecircumflextilde: number; export const KEY_EcuSign: number; export const KEY_Ediaeresis: number; export const KEY_Egrave: number; export const KEY_Ehook: number; export const KEY_Eisu_Shift: number; export const KEY_Eisu_toggle: number; export const KEY_Eject: number; export const KEY_Emacron: number; export const KEY_End: number; export const KEY_Eogonek: number; export const KEY_Escape: number; export const KEY_Eth: number; export const KEY_Etilde: number; export const KEY_EuroSign: number; export const KEY_Excel: number; export const KEY_Execute: number; export const KEY_Explorer: number; export const KEY_F: number; export const KEY_F1: number; export const KEY_F10: number; export const KEY_F11: number; export const KEY_F12: number; export const KEY_F13: number; export const KEY_F14: number; export const KEY_F15: number; export const KEY_F16: number; export const KEY_F17: number; export const KEY_F18: number; export const KEY_F19: number; export const KEY_F2: number; export const KEY_F20: number; export const KEY_F21: number; export const KEY_F22: number; export const KEY_F23: number; export const KEY_F24: number; export const KEY_F25: number; export const KEY_F26: number; export const KEY_F27: number; export const KEY_F28: number; export const KEY_F29: number; export const KEY_F3: number; export const KEY_F30: number; export const KEY_F31: number; export const KEY_F32: number; export const KEY_F33: number; export const KEY_F34: number; export const KEY_F35: number; export const KEY_F4: number; export const KEY_F5: number; export const KEY_F6: number; export const KEY_F7: number; export const KEY_F8: number; export const KEY_F9: number; export const KEY_FFrancSign: number; export const KEY_Fabovedot: number; export const KEY_Farsi_0: number; export const KEY_Farsi_1: number; export const KEY_Farsi_2: number; export const KEY_Farsi_3: number; export const KEY_Farsi_4: number; export const KEY_Farsi_5: number; export const KEY_Farsi_6: number; export const KEY_Farsi_7: number; export const KEY_Farsi_8: number; export const KEY_Farsi_9: number; export const KEY_Farsi_yeh: number; export const KEY_Favorites: number; export const KEY_Finance: number; export const KEY_Find: number; export const KEY_First_Virtual_Screen: number; export const KEY_Forward: number; export const KEY_FrameBack: number; export const KEY_FrameForward: number; export const KEY_G: number; export const KEY_Gabovedot: number; export const KEY_Game: number; export const KEY_Gbreve: number; export const KEY_Gcaron: number; export const KEY_Gcedilla: number; export const KEY_Gcircumflex: number; export const KEY_Georgian_an: number; export const KEY_Georgian_ban: number; export const KEY_Georgian_can: number; export const KEY_Georgian_char: number; export const KEY_Georgian_chin: number; export const KEY_Georgian_cil: number; export const KEY_Georgian_don: number; export const KEY_Georgian_en: number; export const KEY_Georgian_fi: number; export const KEY_Georgian_gan: number; export const KEY_Georgian_ghan: number; export const KEY_Georgian_hae: number; export const KEY_Georgian_har: number; export const KEY_Georgian_he: number; export const KEY_Georgian_hie: number; export const KEY_Georgian_hoe: number; export const KEY_Georgian_in: number; export const KEY_Georgian_jhan: number; export const KEY_Georgian_jil: number; export const KEY_Georgian_kan: number; export const KEY_Georgian_khar: number; export const KEY_Georgian_las: number; export const KEY_Georgian_man: number; export const KEY_Georgian_nar: number; export const KEY_Georgian_on: number; export const KEY_Georgian_par: number; export const KEY_Georgian_phar: number; export const KEY_Georgian_qar: number; export const KEY_Georgian_rae: number; export const KEY_Georgian_san: number; export const KEY_Georgian_shin: number; export const KEY_Georgian_tan: number; export const KEY_Georgian_tar: number; export const KEY_Georgian_un: number; export const KEY_Georgian_vin: number; export const KEY_Georgian_we: number; export const KEY_Georgian_xan: number; export const KEY_Georgian_zen: number; export const KEY_Georgian_zhar: number; export const KEY_Go: number; export const KEY_Greek_ALPHA: number; export const KEY_Greek_ALPHAaccent: number; export const KEY_Greek_BETA: number; export const KEY_Greek_CHI: number; export const KEY_Greek_DELTA: number; export const KEY_Greek_EPSILON: number; export const KEY_Greek_EPSILONaccent: number; export const KEY_Greek_ETA: number; export const KEY_Greek_ETAaccent: number; export const KEY_Greek_GAMMA: number; export const KEY_Greek_IOTA: number; export const KEY_Greek_IOTAaccent: number; export const KEY_Greek_IOTAdiaeresis: number; export const KEY_Greek_IOTAdieresis: number; export const KEY_Greek_KAPPA: number; export const KEY_Greek_LAMBDA: number; export const KEY_Greek_LAMDA: number; export const KEY_Greek_MU: number; export const KEY_Greek_NU: number; export const KEY_Greek_OMEGA: number; export const KEY_Greek_OMEGAaccent: number; export const KEY_Greek_OMICRON: number; export const KEY_Greek_OMICRONaccent: number; export const KEY_Greek_PHI: number; export const KEY_Greek_PI: number; export const KEY_Greek_PSI: number; export const KEY_Greek_RHO: number; export const KEY_Greek_SIGMA: number; export const KEY_Greek_TAU: number; export const KEY_Greek_THETA: number; export const KEY_Greek_UPSILON: number; export const KEY_Greek_UPSILONaccent: number; export const KEY_Greek_UPSILONdieresis: number; export const KEY_Greek_XI: number; export const KEY_Greek_ZETA: number; export const KEY_Greek_accentdieresis: number; export const KEY_Greek_alpha: number; export const KEY_Greek_alphaaccent: number; export const KEY_Greek_beta: number; export const KEY_Greek_chi: number; export const KEY_Greek_delta: number; export const KEY_Greek_epsilon: number; export const KEY_Greek_epsilonaccent: number; export const KEY_Greek_eta: number; export const KEY_Greek_etaaccent: number; export const KEY_Greek_finalsmallsigma: number; export const KEY_Greek_gamma: number; export const KEY_Greek_horizbar: number; export const KEY_Greek_iota: number; export const KEY_Greek_iotaaccent: number; export const KEY_Greek_iotaaccentdieresis: number; export const KEY_Greek_iotadieresis: number; export const KEY_Greek_kappa: number; export const KEY_Greek_lambda: number; export const KEY_Greek_lamda: number; export const KEY_Greek_mu: number; export const KEY_Greek_nu: number; export const KEY_Greek_omega: number; export const KEY_Greek_omegaaccent: number; export const KEY_Greek_omicron: number; export const KEY_Greek_omicronaccent: number; export const KEY_Greek_phi: number; export const KEY_Greek_pi: number; export const KEY_Greek_psi: number; export const KEY_Greek_rho: number; export const KEY_Greek_sigma: number; export const KEY_Greek_switch: number; export const KEY_Greek_tau: number; export const KEY_Greek_theta: number; export const KEY_Greek_upsilon: number; export const KEY_Greek_upsilonaccent: number; export const KEY_Greek_upsilonaccentdieresis: number; export const KEY_Greek_upsilondieresis: number; export const KEY_Greek_xi: number; export const KEY_Greek_zeta: number; export const KEY_Green: number; export const KEY_H: number; export const KEY_Hangul: number; export const KEY_Hangul_A: number; export const KEY_Hangul_AE: number; export const KEY_Hangul_AraeA: number; export const KEY_Hangul_AraeAE: number; export const KEY_Hangul_Banja: number; export const KEY_Hangul_Cieuc: number; export const KEY_Hangul_Codeinput: number; export const KEY_Hangul_Dikeud: number; export const KEY_Hangul_E: number; export const KEY_Hangul_EO: number; export const KEY_Hangul_EU: number; export const KEY_Hangul_End: number; export const KEY_Hangul_Hanja: number; export const KEY_Hangul_Hieuh: number; export const KEY_Hangul_I: number; export const KEY_Hangul_Ieung: number; export const KEY_Hangul_J_Cieuc: number; export const KEY_Hangul_J_Dikeud: number; export const KEY_Hangul_J_Hieuh: number; export const KEY_Hangul_J_Ieung: number; export const KEY_Hangul_J_Jieuj: number; export const KEY_Hangul_J_Khieuq: number; export const KEY_Hangul_J_Kiyeog: number; export const KEY_Hangul_J_KiyeogSios: number; export const KEY_Hangul_J_KkogjiDalrinIeung: number; export const KEY_Hangul_J_Mieum: number; export const KEY_Hangul_J_Nieun: number; export const KEY_Hangul_J_NieunHieuh: number; export const KEY_Hangul_J_NieunJieuj: number; export const KEY_Hangul_J_PanSios: number; export const KEY_Hangul_J_Phieuf: number; export const KEY_Hangul_J_Pieub: number; export const KEY_Hangul_J_PieubSios: number; export const KEY_Hangul_J_Rieul: number; export const KEY_Hangul_J_RieulHieuh: number; export const KEY_Hangul_J_RieulKiyeog: number; export const KEY_Hangul_J_RieulMieum: number; export const KEY_Hangul_J_RieulPhieuf: number; export const KEY_Hangul_J_RieulPieub: number; export const KEY_Hangul_J_RieulSios: number; export const KEY_Hangul_J_RieulTieut: number; export const KEY_Hangul_J_Sios: number; export const KEY_Hangul_J_SsangKiyeog: number; export const KEY_Hangul_J_SsangSios: number; export const KEY_Hangul_J_Tieut: number; export const KEY_Hangul_J_YeorinHieuh: number; export const KEY_Hangul_Jamo: number; export const KEY_Hangul_Jeonja: number; export const KEY_Hangul_Jieuj: number; export const KEY_Hangul_Khieuq: number; export const KEY_Hangul_Kiyeog: number; export const KEY_Hangul_KiyeogSios: number; export const KEY_Hangul_KkogjiDalrinIeung: number; export const KEY_Hangul_Mieum: number; export const KEY_Hangul_MultipleCandidate: number; export const KEY_Hangul_Nieun: number; export const KEY_Hangul_NieunHieuh: number; export const KEY_Hangul_NieunJieuj: number; export const KEY_Hangul_O: number; export const KEY_Hangul_OE: number; export const KEY_Hangul_PanSios: number; export const KEY_Hangul_Phieuf: number; export const KEY_Hangul_Pieub: number; export const KEY_Hangul_PieubSios: number; export const KEY_Hangul_PostHanja: number; export const KEY_Hangul_PreHanja: number; export const KEY_Hangul_PreviousCandidate: number; export const KEY_Hangul_Rieul: number; export const KEY_Hangul_RieulHieuh: number; export const KEY_Hangul_RieulKiyeog: number; export const KEY_Hangul_RieulMieum: number; export const KEY_Hangul_RieulPhieuf: number; export const KEY_Hangul_RieulPieub: number; export const KEY_Hangul_RieulSios: number; export const KEY_Hangul_RieulTieut: number; export const KEY_Hangul_RieulYeorinHieuh: number; export const KEY_Hangul_Romaja: number; export const KEY_Hangul_SingleCandidate: number; export const KEY_Hangul_Sios: number; export const KEY_Hangul_Special: number; export const KEY_Hangul_SsangDikeud: number; export const KEY_Hangul_SsangJieuj: number; export const KEY_Hangul_SsangKiyeog: number; export const KEY_Hangul_SsangPieub: number; export const KEY_Hangul_SsangSios: number; export const KEY_Hangul_Start: number; export const KEY_Hangul_SunkyeongeumMieum: number; export const KEY_Hangul_SunkyeongeumPhieuf: number; export const KEY_Hangul_SunkyeongeumPieub: number; export const KEY_Hangul_Tieut: number; export const KEY_Hangul_U: number; export const KEY_Hangul_WA: number; export const KEY_Hangul_WAE: number; export const KEY_Hangul_WE: number; export const KEY_Hangul_WEO: number; export const KEY_Hangul_WI: number; export const KEY_Hangul_YA: number; export const KEY_Hangul_YAE: number; export const KEY_Hangul_YE: number; export const KEY_Hangul_YEO: number; export const KEY_Hangul_YI: number; export const KEY_Hangul_YO: number; export const KEY_Hangul_YU: number; export const KEY_Hangul_YeorinHieuh: number; export const KEY_Hangul_switch: number; export const KEY_Hankaku: number; export const KEY_Hcircumflex: number; export const KEY_Hebrew_switch: number; export const KEY_Help: number; export const KEY_Henkan: number; export const KEY_Henkan_Mode: number; export const KEY_Hibernate: number; export const KEY_Hiragana: number; export const KEY_Hiragana_Katakana: number; export const KEY_History: number; export const KEY_Home: number; export const KEY_HomePage: number; export const KEY_HotLinks: number; export const KEY_Hstroke: number; export const KEY_Hyper_L: number; export const KEY_Hyper_R: number; export const KEY_I: number; export const KEY_ISO_Center_Object: number; export const KEY_ISO_Continuous_Underline: number; export const KEY_ISO_Discontinuous_Underline: number; export const KEY_ISO_Emphasize: number; export const KEY_ISO_Enter: number; export const KEY_ISO_Fast_Cursor_Down: number; export const KEY_ISO_Fast_Cursor_Left: number; export const KEY_ISO_Fast_Cursor_Right: number; export const KEY_ISO_Fast_Cursor_Up: number; export const KEY_ISO_First_Group: number; export const KEY_ISO_First_Group_Lock: number; export const KEY_ISO_Group_Latch: number; export const KEY_ISO_Group_Lock: number; export const KEY_ISO_Group_Shift: number; export const KEY_ISO_Last_Group: number; export const KEY_ISO_Last_Group_Lock: number; export const KEY_ISO_Left_Tab: number; export const KEY_ISO_Level2_Latch: number; export const KEY_ISO_Level3_Latch: number; export const KEY_ISO_Level3_Lock: number; export const KEY_ISO_Level3_Shift: number; export const KEY_ISO_Level5_Latch: number; export const KEY_ISO_Level5_Lock: number; export const KEY_ISO_Level5_Shift: number; export const KEY_ISO_Lock: number; export const KEY_ISO_Move_Line_Down: number; export const KEY_ISO_Move_Line_Up: number; export const KEY_ISO_Next_Group: number; export const KEY_ISO_Next_Group_Lock: number; export const KEY_ISO_Partial_Line_Down: number; export const KEY_ISO_Partial_Line_Up: number; export const KEY_ISO_Partial_Space_Left: number; export const KEY_ISO_Partial_Space_Right: number; export const KEY_ISO_Prev_Group: number; export const KEY_ISO_Prev_Group_Lock: number; export const KEY_ISO_Release_Both_Margins: number; export const KEY_ISO_Release_Margin_Left: number; export const KEY_ISO_Release_Margin_Right: number; export const KEY_ISO_Set_Margin_Left: number; export const KEY_ISO_Set_Margin_Right: number; export const KEY_Iabovedot: number; export const KEY_Iacute: number; export const KEY_Ibelowdot: number; export const KEY_Ibreve: number; export const KEY_Icircumflex: number; export const KEY_Idiaeresis: number; export const KEY_Igrave: number; export const KEY_Ihook: number; export const KEY_Imacron: number; export const KEY_Insert: number; export const KEY_Iogonek: number; export const KEY_Itilde: number; export const KEY_J: number; export const KEY_Jcircumflex: number; export const KEY_K: number; export const KEY_KP_0: number; export const KEY_KP_1: number; export const KEY_KP_2: number; export const KEY_KP_3: number; export const KEY_KP_4: number; export const KEY_KP_5: number; export const KEY_KP_6: number; export const KEY_KP_7: number; export const KEY_KP_8: number; export const KEY_KP_9: number; export const KEY_KP_Add: number; export const KEY_KP_Begin: number; export const KEY_KP_Decimal: number; export const KEY_KP_Delete: number; export const KEY_KP_Divide: number; export const KEY_KP_Down: number; export const KEY_KP_End: number; export const KEY_KP_Enter: number; export const KEY_KP_Equal: number; export const KEY_KP_F1: number; export const KEY_KP_F2: number; export const KEY_KP_F3: number; export const KEY_KP_F4: number; export const KEY_KP_Home: number; export const KEY_KP_Insert: number; export const KEY_KP_Left: number; export const KEY_KP_Multiply: number; export const KEY_KP_Next: number; export const KEY_KP_Page_Down: number; export const KEY_KP_Page_Up: number; export const KEY_KP_Prior: number; export const KEY_KP_Right: number; export const KEY_KP_Separator: number; export const KEY_KP_Space: number; export const KEY_KP_Subtract: number; export const KEY_KP_Tab: number; export const KEY_KP_Up: number; export const KEY_Kana_Lock: number; export const KEY_Kana_Shift: number; export const KEY_Kanji: number; export const KEY_Kanji_Bangou: number; export const KEY_Katakana: number; export const KEY_KbdBrightnessDown: number; export const KEY_KbdBrightnessUp: number; export const KEY_KbdLightOnOff: number; export const KEY_Kcedilla: number; export const KEY_Korean_Won: number; export const KEY_L: number; export const KEY_L1: number; export const KEY_L10: number; export const KEY_L2: number; export const KEY_L3: number; export const KEY_L4: number; export const KEY_L5: number; export const KEY_L6: number; export const KEY_L7: number; export const KEY_L8: number; export const KEY_L9: number; export const KEY_Lacute: number; export const KEY_Last_Virtual_Screen: number; export const KEY_Launch0: number; export const KEY_Launch1: number; export const KEY_Launch2: number; export const KEY_Launch3: number; export const KEY_Launch4: number; export const KEY_Launch5: number; export const KEY_Launch6: number; export const KEY_Launch7: number; export const KEY_Launch8: number; export const KEY_Launch9: number; export const KEY_LaunchA: number; export const KEY_LaunchB: number; export const KEY_LaunchC: number; export const KEY_LaunchD: number; export const KEY_LaunchE: number; export const KEY_LaunchF: number; export const KEY_Lbelowdot: number; export const KEY_Lcaron: number; export const KEY_Lcedilla: number; export const KEY_Left: number; export const KEY_LightBulb: number; export const KEY_Linefeed: number; export const KEY_LiraSign: number; export const KEY_LogGrabInfo: number; export const KEY_LogOff: number; export const KEY_LogWindowTree: number; export const KEY_Lstroke: number; export const KEY_M: number; export const KEY_Mabovedot: number; export const KEY_Macedonia_DSE: number; export const KEY_Macedonia_GJE: number; export const KEY_Macedonia_KJE: number; export const KEY_Macedonia_dse: number; export const KEY_Macedonia_gje: number; export const KEY_Macedonia_kje: number; export const KEY_Mae_Koho: number; export const KEY_Mail: number; export const KEY_MailForward: number; export const KEY_Market: number; export const KEY_Massyo: number; export const KEY_Meeting: number; export const KEY_Memo: number; export const KEY_Menu: number; export const KEY_MenuKB: number; export const KEY_MenuPB: number; export const KEY_Messenger: number; export const KEY_Meta_L: number; export const KEY_Meta_R: number; export const KEY_MillSign: number; export const KEY_ModeLock: number; export const KEY_Mode_switch: number; export const KEY_MonBrightnessDown: number; export const KEY_MonBrightnessUp: number; export const KEY_MouseKeys_Accel_Enable: number; export const KEY_MouseKeys_Enable: number; export const KEY_Muhenkan: number; export const KEY_Multi_key: number; export const KEY_MultipleCandidate: number; export const KEY_Music: number; export const KEY_MyComputer: number; export const KEY_MySites: number; export const KEY_N: number; export const KEY_Nacute: number; export const KEY_NairaSign: number; export const KEY_Ncaron: number; export const KEY_Ncedilla: number; export const KEY_New: number; export const KEY_NewSheqelSign: number; export const KEY_News: number; export const KEY_Next: number; export const KEY_Next_VMode: number; export const KEY_Next_Virtual_Screen: number; export const KEY_Ntilde: number; export const KEY_Num_Lock: number; export const KEY_O: number; export const KEY_OE: number; export const KEY_Oacute: number; export const KEY_Obarred: number; export const KEY_Obelowdot: number; export const KEY_Ocaron: number; export const KEY_Ocircumflex: number; export const KEY_Ocircumflexacute: number; export const KEY_Ocircumflexbelowdot: number; export const KEY_Ocircumflexgrave: number; export const KEY_Ocircumflexhook: number; export const KEY_Ocircumflextilde: number; export const KEY_Odiaeresis: number; export const KEY_Odoubleacute: number; export const KEY_OfficeHome: number; export const KEY_Ograve: number; export const KEY_Ohook: number; export const KEY_Ohorn: number; export const KEY_Ohornacute: number; export const KEY_Ohornbelowdot: number; export const KEY_Ohorngrave: number; export const KEY_Ohornhook: number; export const KEY_Ohorntilde: number; export const KEY_Omacron: number; export const KEY_Ooblique: number; export const KEY_Open: number; export const KEY_OpenURL: number; export const KEY_Option: number; export const KEY_Oslash: number; export const KEY_Otilde: number; export const KEY_Overlay1_Enable: number; export const KEY_Overlay2_Enable: number; export const KEY_P: number; export const KEY_Pabovedot: number; export const KEY_Page_Down: number; export const KEY_Page_Up: number; export const KEY_Paste: number; export const KEY_Pause: number; export const KEY_PesetaSign: number; export const KEY_Phone: number; export const KEY_Pictures: number; export const KEY_Pointer_Accelerate: number; export const KEY_Pointer_Button1: number; export const KEY_Pointer_Button2: number; export const KEY_Pointer_Button3: number; export const KEY_Pointer_Button4: number; export const KEY_Pointer_Button5: number; export const KEY_Pointer_Button_Dflt: number; export const KEY_Pointer_DblClick1: number; export const KEY_Pointer_DblClick2: number; export const KEY_Pointer_DblClick3: number; export const KEY_Pointer_DblClick4: number; export const KEY_Pointer_DblClick5: number; export const KEY_Pointer_DblClick_Dflt: number; export const KEY_Pointer_DfltBtnNext: number; export const KEY_Pointer_DfltBtnPrev: number; export const KEY_Pointer_Down: number; export const KEY_Pointer_DownLeft: number; export const KEY_Pointer_DownRight: number; export const KEY_Pointer_Drag1: number; export const KEY_Pointer_Drag2: number; export const KEY_Pointer_Drag3: number; export const KEY_Pointer_Drag4: number; export const KEY_Pointer_Drag5: number; export const KEY_Pointer_Drag_Dflt: number; export const KEY_Pointer_EnableKeys: number; export const KEY_Pointer_Left: number; export const KEY_Pointer_Right: number; export const KEY_Pointer_Up: number; export const KEY_Pointer_UpLeft: number; export const KEY_Pointer_UpRight: number; export const KEY_PowerDown: number; export const KEY_PowerOff: number; export const KEY_Prev_VMode: number; export const KEY_Prev_Virtual_Screen: number; export const KEY_PreviousCandidate: number; export const KEY_Print: number; export const KEY_Prior: number; export const KEY_Q: number; export const KEY_R: number; export const KEY_R1: number; export const KEY_R10: number; export const KEY_R11: number; export const KEY_R12: number; export const KEY_R13: number; export const KEY_R14: number; export const KEY_R15: number; export const KEY_R2: number; export const KEY_R3: number; export const KEY_R4: number; export const KEY_R5: number; export const KEY_R6: number; export const KEY_R7: number; export const KEY_R8: number; export const KEY_R9: number; export const KEY_Racute: number; export const KEY_Rcaron: number; export const KEY_Rcedilla: number; export const KEY_Red: number; export const KEY_Redo: number; export const KEY_Refresh: number; export const KEY_Reload: number; export const KEY_RepeatKeys_Enable: number; export const KEY_Reply: number; export const KEY_Return: number; export const KEY_Right: number; export const KEY_RockerDown: number; export const KEY_RockerEnter: number; export const KEY_RockerUp: number; export const KEY_Romaji: number; export const KEY_RotateWindows: number; export const KEY_RotationKB: number; export const KEY_RotationPB: number; export const KEY_RupeeSign: number; export const KEY_S: number; export const KEY_SCHWA: number; export const KEY_Sabovedot: number; export const KEY_Sacute: number; export const KEY_Save: number; export const KEY_Scaron: number; export const KEY_Scedilla: number; export const KEY_Scircumflex: number; export const KEY_ScreenSaver: number; export const KEY_ScrollClick: number; export const KEY_ScrollDown: number; export const KEY_ScrollUp: number; export const KEY_Scroll_Lock: number; export const KEY_Search: number; export const KEY_Select: number; export const KEY_SelectButton: number; export const KEY_Send: number; export const KEY_Serbian_DJE: number; export const KEY_Serbian_DZE: number; export const KEY_Serbian_JE: number; export const KEY_Serbian_LJE: number; export const KEY_Serbian_NJE: number; export const KEY_Serbian_TSHE: number; export const KEY_Serbian_dje: number; export const KEY_Serbian_dze: number; export const KEY_Serbian_je: number; export const KEY_Serbian_lje: number; export const KEY_Serbian_nje: number; export const KEY_Serbian_tshe: number; export const KEY_Shift_L: number; export const KEY_Shift_Lock: number; export const KEY_Shift_R: number; export const KEY_Shop: number; export const KEY_SingleCandidate: number; export const KEY_Sinh_a: number; export const KEY_Sinh_aa: number; export const KEY_Sinh_aa2: number; export const KEY_Sinh_ae: number; export const KEY_Sinh_ae2: number; export const KEY_Sinh_aee: number; export const KEY_Sinh_aee2: number; export const KEY_Sinh_ai: number; export const KEY_Sinh_ai2: number; export const KEY_Sinh_al: number; export const KEY_Sinh_au: number; export const KEY_Sinh_au2: number; export const KEY_Sinh_ba: number; export const KEY_Sinh_bha: number; export const KEY_Sinh_ca: number; export const KEY_Sinh_cha: number; export const KEY_Sinh_dda: number; export const KEY_Sinh_ddha: number; export const KEY_Sinh_dha: number; export const KEY_Sinh_dhha: number; export const KEY_Sinh_e: number; export const KEY_Sinh_e2: number; export const KEY_Sinh_ee: number; export const KEY_Sinh_ee2: number; export const KEY_Sinh_fa: number; export const KEY_Sinh_ga: number; export const KEY_Sinh_gha: number; export const KEY_Sinh_h2: number; export const KEY_Sinh_ha: number; export const KEY_Sinh_i: number; export const KEY_Sinh_i2: number; export const KEY_Sinh_ii: number; export const KEY_Sinh_ii2: number; export const KEY_Sinh_ja: number; export const KEY_Sinh_jha: number; export const KEY_Sinh_jnya: number; export const KEY_Sinh_ka: number; export const KEY_Sinh_kha: number; export const KEY_Sinh_kunddaliya: number; export const KEY_Sinh_la: number; export const KEY_Sinh_lla: number; export const KEY_Sinh_lu: number; export const KEY_Sinh_lu2: number; export const KEY_Sinh_luu: number; export const KEY_Sinh_luu2: number; export const KEY_Sinh_ma: number; export const KEY_Sinh_mba: number; export const KEY_Sinh_na: number; export const KEY_Sinh_ndda: number; export const KEY_Sinh_ndha: number; export const KEY_Sinh_ng: number; export const KEY_Sinh_ng2: number; export const KEY_Sinh_nga: number; export const KEY_Sinh_nja: number; export const KEY_Sinh_nna: number; export const KEY_Sinh_nya: number; export const KEY_Sinh_o: number; export const KEY_Sinh_o2: number; export const KEY_Sinh_oo: number; export const KEY_Sinh_oo2: number; export const KEY_Sinh_pa: number; export const KEY_Sinh_pha: number; export const KEY_Sinh_ra: number; export const KEY_Sinh_ri: number; export const KEY_Sinh_rii: number; export const KEY_Sinh_ru2: number; export const KEY_Sinh_ruu2: number; export const KEY_Sinh_sa: number; export const KEY_Sinh_sha: number; export const KEY_Sinh_ssha: number; export const KEY_Sinh_tha: number; export const KEY_Sinh_thha: number; export const KEY_Sinh_tta: number; export const KEY_Sinh_ttha: number; export const KEY_Sinh_u: number; export const KEY_Sinh_u2: number; export const KEY_Sinh_uu: number; export const KEY_Sinh_uu2: number; export const KEY_Sinh_va: number; export const KEY_Sinh_ya: number; export const KEY_Sleep: number; export const KEY_SlowKeys_Enable: number; export const KEY_Spell: number; export const KEY_SplitScreen: number; export const KEY_Standby: number; export const KEY_Start: number; export const KEY_StickyKeys_Enable: number; export const KEY_Stop: number; export const KEY_Subtitle: number; export const KEY_Super_L: number; export const KEY_Super_R: number; export const KEY_Support: number; export const KEY_Suspend: number; export const KEY_Switch_VT_1: number; export const KEY_Switch_VT_10: number; export const KEY_Switch_VT_11: number; export const KEY_Switch_VT_12: number; export const KEY_Switch_VT_2: number; export const KEY_Switch_VT_3: number; export const KEY_Switch_VT_4: number; export const KEY_Switch_VT_5: number; export const KEY_Switch_VT_6: number; export const KEY_Switch_VT_7: number; export const KEY_Switch_VT_8: number; export const KEY_Switch_VT_9: number; export const KEY_Sys_Req: number; export const KEY_T: number; export const KEY_THORN: number; export const KEY_Tab: number; export const KEY_Tabovedot: number; export const KEY_TaskPane: number; export const KEY_Tcaron: number; export const KEY_Tcedilla: number; export const KEY_Terminal: number; export const KEY_Terminate_Server: number; export const KEY_Thai_baht: number; export const KEY_Thai_bobaimai: number; export const KEY_Thai_chochan: number; export const KEY_Thai_chochang: number; export const KEY_Thai_choching: number; export const KEY_Thai_chochoe: number; export const KEY_Thai_dochada: number; export const KEY_Thai_dodek: number; export const KEY_Thai_fofa: number; export const KEY_Thai_fofan: number; export const KEY_Thai_hohip: number; export const KEY_Thai_honokhuk: number; export const KEY_Thai_khokhai: number; export const KEY_Thai_khokhon: number; export const KEY_Thai_khokhuat: number; export const KEY_Thai_khokhwai: number; export const KEY_Thai_khorakhang: number; export const KEY_Thai_kokai: number; export const KEY_Thai_lakkhangyao: number; export const KEY_Thai_lekchet: number; export const KEY_Thai_lekha: number; export const KEY_Thai_lekhok: number; export const KEY_Thai_lekkao: number; export const KEY_Thai_leknung: number; export const KEY_Thai_lekpaet: number; export const KEY_Thai_leksam: number; export const KEY_Thai_leksi: number; export const KEY_Thai_leksong: number; export const KEY_Thai_leksun: number; export const KEY_Thai_lochula: number; export const KEY_Thai_loling: number; export const KEY_Thai_lu: number; export const KEY_Thai_maichattawa: number; export const KEY_Thai_maiek: number; export const KEY_Thai_maihanakat: number; export const KEY_Thai_maihanakat_maitho: number; export const KEY_Thai_maitaikhu: number; export const KEY_Thai_maitho: number; export const KEY_Thai_maitri: number; export const KEY_Thai_maiyamok: number; export const KEY_Thai_moma: number; export const KEY_Thai_ngongu: number; export const KEY_Thai_nikhahit: number; export const KEY_Thai_nonen: number; export const KEY_Thai_nonu: number; export const KEY_Thai_oang: number; export const KEY_Thai_paiyannoi: number; export const KEY_Thai_phinthu: number; export const KEY_Thai_phophan: number; export const KEY_Thai_phophung: number; export const KEY_Thai_phosamphao: number; export const KEY_Thai_popla: number; export const KEY_Thai_rorua: number; export const KEY_Thai_ru: number; export const KEY_Thai_saraa: number; export const KEY_Thai_saraaa: number; export const KEY_Thai_saraae: number; export const KEY_Thai_saraaimaimalai: number; export const KEY_Thai_saraaimaimuan: number; export const KEY_Thai_saraam: number; export const KEY_Thai_sarae: number; export const KEY_Thai_sarai: number; export const KEY_Thai_saraii: number; export const KEY_Thai_sarao: number; export const KEY_Thai_sarau: number; export const KEY_Thai_saraue: number; export const KEY_Thai_sarauee: number; export const KEY_Thai_sarauu: number; export const KEY_Thai_sorusi: number; export const KEY_Thai_sosala: number; export const KEY_Thai_soso: number; export const KEY_Thai_sosua: number; export const KEY_Thai_thanthakhat: number; export const KEY_Thai_thonangmontho: number; export const KEY_Thai_thophuthao: number; export const KEY_Thai_thothahan: number; export const KEY_Thai_thothan: number; export const KEY_Thai_thothong: number; export const KEY_Thai_thothung: number; export const KEY_Thai_topatak: number; export const KEY_Thai_totao: number; export const KEY_Thai_wowaen: number; export const KEY_Thai_yoyak: number; export const KEY_Thai_yoying: number; export const KEY_Thorn: number; export const KEY_Time: number; export const KEY_ToDoList: number; export const KEY_Tools: number; export const KEY_TopMenu: number; export const KEY_TouchpadOff: number; export const KEY_TouchpadOn: number; export const KEY_TouchpadToggle: number; export const KEY_Touroku: number; export const KEY_Travel: number; export const KEY_Tslash: number; export const KEY_U: number; export const KEY_UWB: number; export const KEY_Uacute: number; export const KEY_Ubelowdot: number; export const KEY_Ubreve: number; export const KEY_Ucircumflex: number; export const KEY_Udiaeresis: number; export const KEY_Udoubleacute: number; export const KEY_Ugrave: number; export const KEY_Uhook: number; export const KEY_Uhorn: number; export const KEY_Uhornacute: number; export const KEY_Uhornbelowdot: number; export const KEY_Uhorngrave: number; export const KEY_Uhornhook: number; export const KEY_Uhorntilde: number; export const KEY_Ukrainian_GHE_WITH_UPTURN: number; export const KEY_Ukrainian_I: number; export const KEY_Ukrainian_IE: number; export const KEY_Ukrainian_YI: number; export const KEY_Ukrainian_ghe_with_upturn: number; export const KEY_Ukrainian_i: number; export const KEY_Ukrainian_ie: number; export const KEY_Ukrainian_yi: number; export const KEY_Ukranian_I: number; export const KEY_Ukranian_JE: number; export const KEY_Ukranian_YI: number; export const KEY_Ukranian_i: number; export const KEY_Ukranian_je: number; export const KEY_Ukranian_yi: number; export const KEY_Umacron: number; export const KEY_Undo: number; export const KEY_Ungrab: number; export const KEY_Uogonek: number; export const KEY_Up: number; export const KEY_Uring: number; export const KEY_User1KB: number; export const KEY_User2KB: number; export const KEY_UserPB: number; export const KEY_Utilde: number; export const KEY_V: number; export const KEY_VendorHome: number; export const KEY_Video: number; export const KEY_View: number; export const KEY_VoidSymbol: number; export const KEY_W: number; export const KEY_WLAN: number; export const KEY_WWW: number; export const KEY_Wacute: number; export const KEY_WakeUp: number; export const KEY_Wcircumflex: number; export const KEY_Wdiaeresis: number; export const KEY_WebCam: number; export const KEY_Wgrave: number; export const KEY_WheelButton: number; export const KEY_WindowClear: number; export const KEY_WonSign: number; export const KEY_Word: number; export const KEY_X: number; export const KEY_Xabovedot: number; export const KEY_Xfer: number; export const KEY_Y: number; export const KEY_Yacute: number; export const KEY_Ybelowdot: number; export const KEY_Ycircumflex: number; export const KEY_Ydiaeresis: number; export const KEY_Yellow: number; export const KEY_Ygrave: number; export const KEY_Yhook: number; export const KEY_Ytilde: number; export const KEY_Z: number; export const KEY_Zabovedot: number; export const KEY_Zacute: number; export const KEY_Zcaron: number; export const KEY_Zen_Koho: number; export const KEY_Zenkaku: number; export const KEY_Zenkaku_Hankaku: number; export const KEY_ZoomIn: number; export const KEY_ZoomOut: number; export const KEY_Zstroke: number; export const KEY_a: number; export const KEY_aacute: number; export const KEY_abelowdot: number; export const KEY_abovedot: number; export const KEY_abreve: number; export const KEY_abreveacute: number; export const KEY_abrevebelowdot: number; export const KEY_abrevegrave: number; export const KEY_abrevehook: number; export const KEY_abrevetilde: number; export const KEY_acircumflex: number; export const KEY_acircumflexacute: number; export const KEY_acircumflexbelowdot: number; export const KEY_acircumflexgrave: number; export const KEY_acircumflexhook: number; export const KEY_acircumflextilde: number; export const KEY_acute: number; export const KEY_adiaeresis: number; export const KEY_ae: number; export const KEY_agrave: number; export const KEY_ahook: number; export const KEY_amacron: number; export const KEY_ampersand: number; export const KEY_aogonek: number; export const KEY_apostrophe: number; export const KEY_approxeq: number; export const KEY_approximate: number; export const KEY_aring: number; export const KEY_asciicircum: number; export const KEY_asciitilde: number; export const KEY_asterisk: number; export const KEY_at: number; export const KEY_atilde: number; export const KEY_b: number; export const KEY_babovedot: number; export const KEY_backslash: number; export const KEY_ballotcross: number; export const KEY_bar: number; export const KEY_because: number; export const KEY_blank: number; export const KEY_botintegral: number; export const KEY_botleftparens: number; export const KEY_botleftsqbracket: number; export const KEY_botleftsummation: number; export const KEY_botrightparens: number; export const KEY_botrightsqbracket: number; export const KEY_botrightsummation: number; export const KEY_bott: number; export const KEY_botvertsummationconnector: number; export const KEY_braceleft: number; export const KEY_braceright: number; export const KEY_bracketleft: number; export const KEY_bracketright: number; export const KEY_braille_blank: number; export const KEY_braille_dot_1: number; export const KEY_braille_dot_10: number; export const KEY_braille_dot_2: number; export const KEY_braille_dot_3: number; export const KEY_braille_dot_4: number; export const KEY_braille_dot_5: number; export const KEY_braille_dot_6: number; export const KEY_braille_dot_7: number; export const KEY_braille_dot_8: number; export const KEY_braille_dot_9: number; export const KEY_braille_dots_1: number; export const KEY_braille_dots_12: number; export const KEY_braille_dots_123: number; export const KEY_braille_dots_1234: number; export const KEY_braille_dots_12345: number; export const KEY_braille_dots_123456: number; export const KEY_braille_dots_1234567: number; export const KEY_braille_dots_12345678: number; export const KEY_braille_dots_1234568: number; export const KEY_braille_dots_123457: number; export const KEY_braille_dots_1234578: number; export const KEY_braille_dots_123458: number; export const KEY_braille_dots_12346: number; export const KEY_braille_dots_123467: number; export const KEY_braille_dots_1234678: number; export const KEY_braille_dots_123468: number; export const KEY_braille_dots_12347: number; export const KEY_braille_dots_123478: number; export const KEY_braille_dots_12348: number; export const KEY_braille_dots_1235: number; export const KEY_braille_dots_12356: number; export const KEY_braille_dots_123567: number; export const KEY_braille_dots_1235678: number; export const KEY_braille_dots_123568: number; export const KEY_braille_dots_12357: number; export const KEY_braille_dots_123578: number; export const KEY_braille_dots_12358: number; export const KEY_braille_dots_1236: number; export const KEY_braille_dots_12367: number; export const KEY_braille_dots_123678: number; export const KEY_braille_dots_12368: number; export const KEY_braille_dots_1237: number; export const KEY_braille_dots_12378: number; export const KEY_braille_dots_1238: number; export const KEY_braille_dots_124: number; export const KEY_braille_dots_1245: number; export const KEY_braille_dots_12456: number; export const KEY_braille_dots_124567: number; export const KEY_braille_dots_1245678: number; export const KEY_braille_dots_124568: number; export const KEY_braille_dots_12457: number; export const KEY_braille_dots_124578: number; export const KEY_braille_dots_12458: number; export const KEY_braille_dots_1246: number; export const KEY_braille_dots_12467: number; export const KEY_braille_dots_124678: number; export const KEY_braille_dots_12468: number; export const KEY_braille_dots_1247: number; export const KEY_braille_dots_12478: number; export const KEY_braille_dots_1248: number; export const KEY_braille_dots_125: number; export const KEY_braille_dots_1256: number; export const KEY_braille_dots_12567: number; export const KEY_braille_dots_125678: number; export const KEY_braille_dots_12568: number; export const KEY_braille_dots_1257: number; export const KEY_braille_dots_12578: number; export const KEY_braille_dots_1258: number; export const KEY_braille_dots_126: number; export const KEY_braille_dots_1267: number; export const KEY_braille_dots_12678: number; export const KEY_braille_dots_1268: number; export const KEY_braille_dots_127: number; export const KEY_braille_dots_1278: number; export const KEY_braille_dots_128: number; export const KEY_braille_dots_13: number; export const KEY_braille_dots_134: number; export const KEY_braille_dots_1345: number; export const KEY_braille_dots_13456: number; export const KEY_braille_dots_134567: number; export const KEY_braille_dots_1345678: number; export const KEY_braille_dots_134568: number; export const KEY_braille_dots_13457: number; export const KEY_braille_dots_134578: number; export const KEY_braille_dots_13458: number; export const KEY_braille_dots_1346: number; export const KEY_braille_dots_13467: number; export const KEY_braille_dots_134678: number; export const KEY_braille_dots_13468: number; export const KEY_braille_dots_1347: number; export const KEY_braille_dots_13478: number; export const KEY_braille_dots_1348: number; export const KEY_braille_dots_135: number; export const KEY_braille_dots_1356: number; export const KEY_braille_dots_13567: number; export const KEY_braille_dots_135678: number; export const KEY_braille_dots_13568: number; export const KEY_braille_dots_1357: number; export const KEY_braille_dots_13578: number; export const KEY_braille_dots_1358: number; export const KEY_braille_dots_136: number; export const KEY_braille_dots_1367: number; export const KEY_braille_dots_13678: number; export const KEY_braille_dots_1368: number; export const KEY_braille_dots_137: number; export const KEY_braille_dots_1378: number; export const KEY_braille_dots_138: number; export const KEY_braille_dots_14: number; export const KEY_braille_dots_145: number; export const KEY_braille_dots_1456: number; export const KEY_braille_dots_14567: number; export const KEY_braille_dots_145678: number; export const KEY_braille_dots_14568: number; export const KEY_braille_dots_1457: number; export const KEY_braille_dots_14578: number; export const KEY_braille_dots_1458: number; export const KEY_braille_dots_146: number; export const KEY_braille_dots_1467: number; export const KEY_braille_dots_14678: number; export const KEY_braille_dots_1468: number; export const KEY_braille_dots_147: number; export const KEY_braille_dots_1478: number; export const KEY_braille_dots_148: number; export const KEY_braille_dots_15: number; export const KEY_braille_dots_156: number; export const KEY_braille_dots_1567: number; export const KEY_braille_dots_15678: number; export const KEY_braille_dots_1568: number; export const KEY_braille_dots_157: number; export const KEY_braille_dots_1578: number; export const KEY_braille_dots_158: number; export const KEY_braille_dots_16: number; export const KEY_braille_dots_167: number; export const KEY_braille_dots_1678: number; export const KEY_braille_dots_168: number; export const KEY_braille_dots_17: number; export const KEY_braille_dots_178: number; export const KEY_braille_dots_18: number; export const KEY_braille_dots_2: number; export const KEY_braille_dots_23: number; export const KEY_braille_dots_234: number; export const KEY_braille_dots_2345: number; export const KEY_braille_dots_23456: number; export const KEY_braille_dots_234567: number; export const KEY_braille_dots_2345678: number; export const KEY_braille_dots_234568: number; export const KEY_braille_dots_23457: number; export const KEY_braille_dots_234578: number; export const KEY_braille_dots_23458: number; export const KEY_braille_dots_2346: number; export const KEY_braille_dots_23467: number; export const KEY_braille_dots_234678: number; export const KEY_braille_dots_23468: number; export const KEY_braille_dots_2347: number; export const KEY_braille_dots_23478: number; export const KEY_braille_dots_2348: number; export const KEY_braille_dots_235: number; export const KEY_braille_dots_2356: number; export const KEY_braille_dots_23567: number; export const KEY_braille_dots_235678: number; export const KEY_braille_dots_23568: number; export const KEY_braille_dots_2357: number; export const KEY_braille_dots_23578: number; export const KEY_braille_dots_2358: number; export const KEY_braille_dots_236: number; export const KEY_braille_dots_2367: number; export const KEY_braille_dots_23678: number; export const KEY_braille_dots_2368: number; export const KEY_braille_dots_237: number; export const KEY_braille_dots_2378: number; export const KEY_braille_dots_238: number; export const KEY_braille_dots_24: number; export const KEY_braille_dots_245: number; export const KEY_braille_dots_2456: number; export const KEY_braille_dots_24567: number; export const KEY_braille_dots_245678: number; export const KEY_braille_dots_24568: number; export const KEY_braille_dots_2457: number; export const KEY_braille_dots_24578: number; export const KEY_braille_dots_2458: number; export const KEY_braille_dots_246: number; export const KEY_braille_dots_2467: number; export const KEY_braille_dots_24678: number; export const KEY_braille_dots_2468: number; export const KEY_braille_dots_247: number; export const KEY_braille_dots_2478: number; export const KEY_braille_dots_248: number; export const KEY_braille_dots_25: number; export const KEY_braille_dots_256: number; export const KEY_braille_dots_2567: number; export const KEY_braille_dots_25678: number; export const KEY_braille_dots_2568: number; export const KEY_braille_dots_257: number; export const KEY_braille_dots_2578: number; export const KEY_braille_dots_258: number; export const KEY_braille_dots_26: number; export const KEY_braille_dots_267: number; export const KEY_braille_dots_2678: number; export const KEY_braille_dots_268: number; export const KEY_braille_dots_27: number; export const KEY_braille_dots_278: number; export const KEY_braille_dots_28: number; export const KEY_braille_dots_3: number; export const KEY_braille_dots_34: number; export const KEY_braille_dots_345: number; export const KEY_braille_dots_3456: number; export const KEY_braille_dots_34567: number; export const KEY_braille_dots_345678: number; export const KEY_braille_dots_34568: number; export const KEY_braille_dots_3457: number; export const KEY_braille_dots_34578: number; export const KEY_braille_dots_3458: number; export const KEY_braille_dots_346: number; export const KEY_braille_dots_3467: number; export const KEY_braille_dots_34678: number; export const KEY_braille_dots_3468: number; export const KEY_braille_dots_347: number; export const KEY_braille_dots_3478: number; export const KEY_braille_dots_348: number; export const KEY_braille_dots_35: number; export const KEY_braille_dots_356: number; export const KEY_braille_dots_3567: number; export const KEY_braille_dots_35678: number; export const KEY_braille_dots_3568: number; export const KEY_braille_dots_357: number; export const KEY_braille_dots_3578: number; export const KEY_braille_dots_358: number; export const KEY_braille_dots_36: number; export const KEY_braille_dots_367: number; export const KEY_braille_dots_3678: number; export const KEY_braille_dots_368: number; export const KEY_braille_dots_37: number; export const KEY_braille_dots_378: number; export const KEY_braille_dots_38: number; export const KEY_braille_dots_4: number; export const KEY_braille_dots_45: number; export const KEY_braille_dots_456: number; export const KEY_braille_dots_4567: number; export const KEY_braille_dots_45678: number; export const KEY_braille_dots_4568: number; export const KEY_braille_dots_457: number; export const KEY_braille_dots_4578: number; export const KEY_braille_dots_458: number; export const KEY_braille_dots_46: number; export const KEY_braille_dots_467: number; export const KEY_braille_dots_4678: number; export const KEY_braille_dots_468: number; export const KEY_braille_dots_47: number; export const KEY_braille_dots_478: number; export const KEY_braille_dots_48: number; export const KEY_braille_dots_5: number; export const KEY_braille_dots_56: number; export const KEY_braille_dots_567: number; export const KEY_braille_dots_5678: number; export const KEY_braille_dots_568: number; export const KEY_braille_dots_57: number; export const KEY_braille_dots_578: number; export const KEY_braille_dots_58: number; export const KEY_braille_dots_6: number; export const KEY_braille_dots_67: number; export const KEY_braille_dots_678: number; export const KEY_braille_dots_68: number; export const KEY_braille_dots_7: number; export const KEY_braille_dots_78: number; export const KEY_braille_dots_8: number; export const KEY_breve: number; export const KEY_brokenbar: number; export const KEY_c: number; export const KEY_c_h: number; export const KEY_cabovedot: number; export const KEY_cacute: number; export const KEY_careof: number; export const KEY_caret: number; export const KEY_caron: number; export const KEY_ccaron: number; export const KEY_ccedilla: number; export const KEY_ccircumflex: number; export const KEY_cedilla: number; export const KEY_cent: number; export const KEY_ch: number; export const KEY_checkerboard: number; export const KEY_checkmark: number; export const KEY_circle: number; export const KEY_club: number; export const KEY_colon: number; export const KEY_comma: number; export const KEY_containsas: number; export const KEY_copyright: number; export const KEY_cr: number; export const KEY_crossinglines: number; export const KEY_cuberoot: number; export const KEY_currency: number; export const KEY_cursor: number; export const KEY_d: number; export const KEY_dabovedot: number; export const KEY_dagger: number; export const KEY_dcaron: number; export const KEY_dead_A: number; export const KEY_dead_E: number; export const KEY_dead_I: number; export const KEY_dead_O: number; export const KEY_dead_U: number; export const KEY_dead_a: number; export const KEY_dead_abovecomma: number; export const KEY_dead_abovedot: number; export const KEY_dead_abovereversedcomma: number; export const KEY_dead_abovering: number; export const KEY_dead_aboveverticalline: number; export const KEY_dead_acute: number; export const KEY_dead_belowbreve: number; export const KEY_dead_belowcircumflex: number; export const KEY_dead_belowcomma: number; export const KEY_dead_belowdiaeresis: number; export const KEY_dead_belowdot: number; export const KEY_dead_belowmacron: number; export const KEY_dead_belowring: number; export const KEY_dead_belowtilde: number; export const KEY_dead_belowverticalline: number; export const KEY_dead_breve: number; export const KEY_dead_capital_schwa: number; export const KEY_dead_caron: number; export const KEY_dead_cedilla: number; export const KEY_dead_circumflex: number; export const KEY_dead_currency: number; export const KEY_dead_dasia: number; export const KEY_dead_diaeresis: number; export const KEY_dead_doubleacute: number; export const KEY_dead_doublegrave: number; export const KEY_dead_e: number; export const KEY_dead_grave: number; export const KEY_dead_greek: number; export const KEY_dead_hook: number; export const KEY_dead_horn: number; export const KEY_dead_i: number; export const KEY_dead_invertedbreve: number; export const KEY_dead_iota: number; export const KEY_dead_longsolidusoverlay: number; export const KEY_dead_lowline: number; export const KEY_dead_macron: number; export const KEY_dead_o: number; export const KEY_dead_ogonek: number; export const KEY_dead_perispomeni: number; export const KEY_dead_psili: number; export const KEY_dead_semivoiced_sound: number; export const KEY_dead_small_schwa: number; export const KEY_dead_stroke: number; export const KEY_dead_tilde: number; export const KEY_dead_u: number; export const KEY_dead_voiced_sound: number; export const KEY_decimalpoint: number; export const KEY_degree: number; export const KEY_diaeresis: number; export const KEY_diamond: number; export const KEY_digitspace: number; export const KEY_dintegral: number; export const KEY_division: number; export const KEY_dollar: number; export const KEY_doubbaselinedot: number; export const KEY_doubleacute: number; export const KEY_doubledagger: number; export const KEY_doublelowquotemark: number; export const KEY_downarrow: number; export const KEY_downcaret: number; export const KEY_downshoe: number; export const KEY_downstile: number; export const KEY_downtack: number; export const KEY_dstroke: number; export const KEY_e: number; export const KEY_eabovedot: number; export const KEY_eacute: number; export const KEY_ebelowdot: number; export const KEY_ecaron: number; export const KEY_ecircumflex: number; export const KEY_ecircumflexacute: number; export const KEY_ecircumflexbelowdot: number; export const KEY_ecircumflexgrave: number; export const KEY_ecircumflexhook: number; export const KEY_ecircumflextilde: number; export const KEY_ediaeresis: number; export const KEY_egrave: number; export const KEY_ehook: number; export const KEY_eightsubscript: number; export const KEY_eightsuperior: number; export const KEY_elementof: number; export const KEY_ellipsis: number; export const KEY_em3space: number; export const KEY_em4space: number; export const KEY_emacron: number; export const KEY_emdash: number; export const KEY_emfilledcircle: number; export const KEY_emfilledrect: number; export const KEY_emopencircle: number; export const KEY_emopenrectangle: number; export const KEY_emptyset: number; export const KEY_emspace: number; export const KEY_endash: number; export const KEY_enfilledcircbullet: number; export const KEY_enfilledsqbullet: number; export const KEY_eng: number; export const KEY_enopencircbullet: number; export const KEY_enopensquarebullet: number; export const KEY_enspace: number; export const KEY_eogonek: number; export const KEY_equal: number; export const KEY_eth: number; export const KEY_etilde: number; export const KEY_exclam: number; export const KEY_exclamdown: number; export const KEY_ezh: number; export const KEY_f: number; export const KEY_fabovedot: number; export const KEY_femalesymbol: number; export const KEY_ff: number; export const KEY_figdash: number; export const KEY_filledlefttribullet: number; export const KEY_filledrectbullet: number; export const KEY_filledrighttribullet: number; export const KEY_filledtribulletdown: number; export const KEY_filledtribulletup: number; export const KEY_fiveeighths: number; export const KEY_fivesixths: number; export const KEY_fivesubscript: number; export const KEY_fivesuperior: number; export const KEY_fourfifths: number; export const KEY_foursubscript: number; export const KEY_foursuperior: number; export const KEY_fourthroot: number; export const KEY_function: number; export const KEY_g: number; export const KEY_gabovedot: number; export const KEY_gbreve: number; export const KEY_gcaron: number; export const KEY_gcedilla: number; export const KEY_gcircumflex: number; export const KEY_grave: number; export const KEY_greater: number; export const KEY_greaterthanequal: number; export const KEY_guillemotleft: number; export const KEY_guillemotright: number; export const KEY_h: number; export const KEY_hairspace: number; export const KEY_hcircumflex: number; export const KEY_heart: number; export const KEY_hebrew_aleph: number; export const KEY_hebrew_ayin: number; export const KEY_hebrew_bet: number; export const KEY_hebrew_beth: number; export const KEY_hebrew_chet: number; export const KEY_hebrew_dalet: number; export const KEY_hebrew_daleth: number; export const KEY_hebrew_doublelowline: number; export const KEY_hebrew_finalkaph: number; export const KEY_hebrew_finalmem: number; export const KEY_hebrew_finalnun: number; export const KEY_hebrew_finalpe: number; export const KEY_hebrew_finalzade: number; export const KEY_hebrew_finalzadi: number; export const KEY_hebrew_gimel: number; export const KEY_hebrew_gimmel: number; export const KEY_hebrew_he: number; export const KEY_hebrew_het: number; export const KEY_hebrew_kaph: number; export const KEY_hebrew_kuf: number; export const KEY_hebrew_lamed: number; export const KEY_hebrew_mem: number; export const KEY_hebrew_nun: number; export const KEY_hebrew_pe: number; export const KEY_hebrew_qoph: number; export const KEY_hebrew_resh: number; export const KEY_hebrew_samech: number; export const KEY_hebrew_samekh: number; export const KEY_hebrew_shin: number; export const KEY_hebrew_taf: number; export const KEY_hebrew_taw: number; export const KEY_hebrew_tet: number; export const KEY_hebrew_teth: number; export const KEY_hebrew_waw: number; export const KEY_hebrew_yod: number; export const KEY_hebrew_zade: number; export const KEY_hebrew_zadi: number; export const KEY_hebrew_zain: number; export const KEY_hebrew_zayin: number; export const KEY_hexagram: number; export const KEY_horizconnector: number; export const KEY_horizlinescan1: number; export const KEY_horizlinescan3: number; export const KEY_horizlinescan5: number; export const KEY_horizlinescan7: number; export const KEY_horizlinescan9: number; export const KEY_hstroke: number; export const KEY_ht: number; export const KEY_hyphen: number; export const KEY_i: number; export const KEY_iTouch: number; export const KEY_iacute: number; export const KEY_ibelowdot: number; export const KEY_ibreve: number; export const KEY_icircumflex: number; export const KEY_identical: number; export const KEY_idiaeresis: number; export const KEY_idotless: number; export const KEY_ifonlyif: number; export const KEY_igrave: number; export const KEY_ihook: number; export const KEY_imacron: number; export const KEY_implies: number; export const KEY_includedin: number; export const KEY_includes: number; export const KEY_infinity: number; export const KEY_integral: number; export const KEY_intersection: number; export const KEY_iogonek: number; export const KEY_itilde: number; export const KEY_j: number; export const KEY_jcircumflex: number; export const KEY_jot: number; export const KEY_k: number; export const KEY_kana_A: number; export const KEY_kana_CHI: number; export const KEY_kana_E: number; export const KEY_kana_FU: number; export const KEY_kana_HA: number; export const KEY_kana_HE: number; export const KEY_kana_HI: number; export const KEY_kana_HO: number; export const KEY_kana_HU: number; export const KEY_kana_I: number; export const KEY_kana_KA: number; export const KEY_kana_KE: number; export const KEY_kana_KI: number; export const KEY_kana_KO: number; export const KEY_kana_KU: number; export const KEY_kana_MA: number; export const KEY_kana_ME: number; export const KEY_kana_MI: number; export const KEY_kana_MO: number; export const KEY_kana_MU: number; export const KEY_kana_N: number; export const KEY_kana_NA: number; export const KEY_kana_NE: number; export const KEY_kana_NI: number; export const KEY_kana_NO: number; export const KEY_kana_NU: number; export const KEY_kana_O: number; export const KEY_kana_RA: number; export const KEY_kana_RE: number; export const KEY_kana_RI: number; export const KEY_kana_RO: number; export const KEY_kana_RU: number; export const KEY_kana_SA: number; export const KEY_kana_SE: number; export const KEY_kana_SHI: number; export const KEY_kana_SO: number; export const KEY_kana_SU: number; export const KEY_kana_TA: number; export const KEY_kana_TE: number; export const KEY_kana_TI: number; export const KEY_kana_TO: number; export const KEY_kana_TSU: number; export const KEY_kana_TU: number; export const KEY_kana_U: number; export const KEY_kana_WA: number; export const KEY_kana_WO: number; export const KEY_kana_YA: number; export const KEY_kana_YO: number; export const KEY_kana_YU: number; export const KEY_kana_a: number; export const KEY_kana_closingbracket: number; export const KEY_kana_comma: number; export const KEY_kana_conjunctive: number; export const KEY_kana_e: number; export const KEY_kana_fullstop: number; export const KEY_kana_i: number; export const KEY_kana_middledot: number; export const KEY_kana_o: number; export const KEY_kana_openingbracket: number; export const KEY_kana_switch: number; export const KEY_kana_tsu: number; export const KEY_kana_tu: number; export const KEY_kana_u: number; export const KEY_kana_ya: number; export const KEY_kana_yo: number; export const KEY_kana_yu: number; export const KEY_kappa: number; export const KEY_kcedilla: number; export const KEY_kra: number; export const KEY_l: number; export const KEY_lacute: number; export const KEY_latincross: number; export const KEY_lbelowdot: number; export const KEY_lcaron: number; export const KEY_lcedilla: number; export const KEY_leftanglebracket: number; export const KEY_leftarrow: number; export const KEY_leftcaret: number; export const KEY_leftdoublequotemark: number; export const KEY_leftmiddlecurlybrace: number; export const KEY_leftopentriangle: number; export const KEY_leftpointer: number; export const KEY_leftradical: number; export const KEY_leftshoe: number; export const KEY_leftsinglequotemark: number; export const KEY_leftt: number; export const KEY_lefttack: number; export const KEY_less: number; export const KEY_lessthanequal: number; export const KEY_lf: number; export const KEY_logicaland: number; export const KEY_logicalor: number; export const KEY_lowleftcorner: number; export const KEY_lowrightcorner: number; export const KEY_lstroke: number; export const KEY_m: number; export const KEY_mabovedot: number; export const KEY_macron: number; export const KEY_malesymbol: number; export const KEY_maltesecross: number; export const KEY_marker: number; export const KEY_masculine: number; export const KEY_minus: number; export const KEY_minutes: number; export const KEY_mu: number; export const KEY_multiply: number; export const KEY_musicalflat: number; export const KEY_musicalsharp: number; export const KEY_n: number; export const KEY_nabla: number; export const KEY_nacute: number; export const KEY_ncaron: number; export const KEY_ncedilla: number; export const KEY_ninesubscript: number; export const KEY_ninesuperior: number; export const KEY_nl: number; export const KEY_nobreakspace: number; export const KEY_notapproxeq: number; export const KEY_notelementof: number; export const KEY_notequal: number; export const KEY_notidentical: number; export const KEY_notsign: number; export const KEY_ntilde: number; export const KEY_numbersign: number; export const KEY_numerosign: number; export const KEY_o: number; export const KEY_oacute: number; export const KEY_obarred: number; export const KEY_obelowdot: number; export const KEY_ocaron: number; export const KEY_ocircumflex: number; export const KEY_ocircumflexacute: number; export const KEY_ocircumflexbelowdot: number; export const KEY_ocircumflexgrave: number; export const KEY_ocircumflexhook: number; export const KEY_ocircumflextilde: number; export const KEY_odiaeresis: number; export const KEY_odoubleacute: number; export const KEY_oe: number; export const KEY_ogonek: number; export const KEY_ograve: number; export const KEY_ohook: number; export const KEY_ohorn: number; export const KEY_ohornacute: number; export const KEY_ohornbelowdot: number; export const KEY_ohorngrave: number; export const KEY_ohornhook: number; export const KEY_ohorntilde: number; export const KEY_omacron: number; export const KEY_oneeighth: number; export const KEY_onefifth: number; export const KEY_onehalf: number; export const KEY_onequarter: number; export const KEY_onesixth: number; export const KEY_onesubscript: number; export const KEY_onesuperior: number; export const KEY_onethird: number; export const KEY_ooblique: number; export const KEY_openrectbullet: number; export const KEY_openstar: number; export const KEY_opentribulletdown: number; export const KEY_opentribulletup: number; export const KEY_ordfeminine: number; export const KEY_oslash: number; export const KEY_otilde: number; export const KEY_overbar: number; export const KEY_overline: number; export const KEY_p: number; export const KEY_pabovedot: number; export const KEY_paragraph: number; export const KEY_parenleft: number; export const KEY_parenright: number; export const KEY_partdifferential: number; export const KEY_partialderivative: number; export const KEY_percent: number; export const KEY_period: number; export const KEY_periodcentered: number; export const KEY_permille: number; export const KEY_phonographcopyright: number; export const KEY_plus: number; export const KEY_plusminus: number; export const KEY_prescription: number; export const KEY_prolongedsound: number; export const KEY_punctspace: number; export const KEY_q: number; export const KEY_quad: number; export const KEY_question: number; export const KEY_questiondown: number; export const KEY_quotedbl: number; export const KEY_quoteleft: number; export const KEY_quoteright: number; export const KEY_r: number; export const KEY_racute: number; export const KEY_radical: number; export const KEY_rcaron: number; export const KEY_rcedilla: number; export const KEY_registered: number; export const KEY_rightanglebracket: number; export const KEY_rightarrow: number; export const KEY_rightcaret: number; export const KEY_rightdoublequotemark: number; export const KEY_rightmiddlecurlybrace: number; export const KEY_rightmiddlesummation: number; export const KEY_rightopentriangle: number; export const KEY_rightpointer: number; export const KEY_rightshoe: number; export const KEY_rightsinglequotemark: number; export const KEY_rightt: number; export const KEY_righttack: number; export const KEY_s: number; export const KEY_sabovedot: number; export const KEY_sacute: number; export const KEY_scaron: number; export const KEY_scedilla: number; export const KEY_schwa: number; export const KEY_scircumflex: number; export const KEY_script_switch: number; export const KEY_seconds: number; export const KEY_section: number; export const KEY_semicolon: number; export const KEY_semivoicedsound: number; export const KEY_seveneighths: number; export const KEY_sevensubscript: number; export const KEY_sevensuperior: number; export const KEY_signaturemark: number; export const KEY_signifblank: number; export const KEY_similarequal: number; export const KEY_singlelowquotemark: number; export const KEY_sixsubscript: number; export const KEY_sixsuperior: number; export const KEY_slash: number; export const KEY_soliddiamond: number; export const KEY_space: number; export const KEY_squareroot: number; export const KEY_ssharp: number; export const KEY_sterling: number; export const KEY_stricteq: number; export const KEY_t: number; export const KEY_tabovedot: number; export const KEY_tcaron: number; export const KEY_tcedilla: number; export const KEY_telephone: number; export const KEY_telephonerecorder: number; export const KEY_therefore: number; export const KEY_thinspace: number; export const KEY_thorn: number; export const KEY_threeeighths: number; export const KEY_threefifths: number; export const KEY_threequarters: number; export const KEY_threesubscript: number; export const KEY_threesuperior: number; export const KEY_tintegral: number; export const KEY_topintegral: number; export const KEY_topleftparens: number; export const KEY_topleftradical: number; export const KEY_topleftsqbracket: number; export const KEY_topleftsummation: number; export const KEY_toprightparens: number; export const KEY_toprightsqbracket: number; export const KEY_toprightsummation: number; export const KEY_topt: number; export const KEY_topvertsummationconnector: number; export const KEY_trademark: number; export const KEY_trademarkincircle: number; export const KEY_tslash: number; export const KEY_twofifths: number; export const KEY_twosubscript: number; export const KEY_twosuperior: number; export const KEY_twothirds: number; export const KEY_u: number; export const KEY_uacute: number; export const KEY_ubelowdot: number; export const KEY_ubreve: number; export const KEY_ucircumflex: number; export const KEY_udiaeresis: number; export const KEY_udoubleacute: number; export const KEY_ugrave: number; export const KEY_uhook: number; export const KEY_uhorn: number; export const KEY_uhornacute: number; export const KEY_uhornbelowdot: number; export const KEY_uhorngrave: number; export const KEY_uhornhook: number; export const KEY_uhorntilde: number; export const KEY_umacron: number; export const KEY_underbar: number; export const KEY_underscore: number; export const KEY_union: number; export const KEY_uogonek: number; export const KEY_uparrow: number; export const KEY_upcaret: number; export const KEY_upleftcorner: number; export const KEY_uprightcorner: number; export const KEY_upshoe: number; export const KEY_upstile: number; export const KEY_uptack: number; export const KEY_uring: number; export const KEY_utilde: number; export const KEY_v: number; export const KEY_variation: number; export const KEY_vertbar: number; export const KEY_vertconnector: number; export const KEY_voicedsound: number; export const KEY_vt: number; export const KEY_w: number; export const KEY_wacute: number; export const KEY_wcircumflex: number; export const KEY_wdiaeresis: number; export const KEY_wgrave: number; export const KEY_x: number; export const KEY_xabovedot: number; export const KEY_y: number; export const KEY_yacute: number; export const KEY_ybelowdot: number; export const KEY_ycircumflex: number; export const KEY_ydiaeresis: number; export const KEY_yen: number; export const KEY_ygrave: number; export const KEY_yhook: number; export const KEY_ytilde: number; export const KEY_z: number; export const KEY_zabovedot: number; export const KEY_zacute: number; export const KEY_zcaron: number; export const KEY_zerosubscript: number; export const KEY_zerosuperior: number; export const KEY_zstroke: number; export const NO_FPU: number; export const PATH_RELATIVE: number; export const PRIORITY_REDRAW: number; export const STAGE_TYPE: string; export const WINDOWING_EGL: string; export const WINDOWING_GLX: string; export const WINDOWING_X11: string; export function actor_box_alloc(): ActorBox; export function base_init(): void; export function cairo_clear(cr: cairo.Context): void; export function cairo_set_source_color(cr: cairo.Context, color: Color): void; export function color_from_hls( hue: number, luminance: number, saturation: number ): Color; export function color_from_pixel(pixel: number): Color; export function color_from_string(str: string): [boolean, Color]; export function color_get_static(color: StaticColor): Color; export function container_class_find_child_property( klass: GObject.Object, property_name: string ): GObject.ParamSpec; export function container_class_list_child_properties( klass: GObject.Object ): GObject.ParamSpec[]; export function disable_accessibility(): void; export function do_event(event: Event): void; export function event_add_filter( stage: Stage | null, func: EventFilterFunc ): number; export function event_get(): Event; export function event_peek(): Event; export function event_remove_filter(id: number): void; export function events_pending(): boolean; export function feature_available(feature: FeatureFlags): boolean; export function feature_get_all(): FeatureFlags; export function get_accessibility_enabled(): boolean; export function get_current_event(): Event; export function get_current_event_time(): number; export function get_default_backend(): Backend; export function get_default_frame_rate(): number; export function get_default_text_direction(): TextDirection; export function get_font_map(): Pango.FontMap; export function get_script_id(gobject: GObject.Object): string; export function image_error_quark(): GLib.Quark; export function init(argv?: string[] | null): [InitError, string[] | null]; export function init_error_quark(): GLib.Quark; export function init_with_args( argv?: string[] | null, parameter_string?: string | null, entries?: GLib.OptionEntry[] | null, translation_domain?: string | null ): [InitError, string[] | null]; export function keysym_to_unicode(keyval: number): number; export function matrix_alloc(): Matrix; export function matrix_free(matrix?: Matrix | null): void; export function matrix_get_type(): GObject.GType; export function matrix_init_from_array( matrix: Matrix, values: number[] ): Matrix; export function matrix_init_from_matrix(a: Matrix, b: Matrix): Matrix; export function matrix_init_identity(matrix: Matrix): Matrix; export function script_error_quark(): GLib.Quark; export function set_custom_backend_func(func?: any | null): void; export function threads_add_idle( priority: number, func: GLib.SourceFunc ): number; export function threads_add_repaint_func(func: GLib.SourceFunc): number; export function threads_add_repaint_func_full( flags: RepaintFlags, func: GLib.SourceFunc ): number; export function threads_add_timeout( priority: number, interval: number, func: GLib.SourceFunc ): number; export function threads_remove_repaint_func(handle_id: number): void; export function unicode_to_keysym(wc: number): number; export function units_from_cm(cm: number): Units; export function units_from_em(em: number): Units; export function units_from_em_for_font( font_name: string | null, em: number ): Units; export function units_from_mm(mm: number): Units; export function units_from_pixels(px: number): Units; export function units_from_pt(pt: number): Units; export function units_from_string(str: string): [boolean, Units]; export function value_dup_paint_node(value: any): PaintNode; export function value_get_color(value: any): Color; export function value_get_paint_node(value: any): PaintNode; export function value_get_shader_float(value: any): number[]; export function value_get_shader_int(value: any): number[]; export function value_get_shader_matrix(value: any): number[]; export function value_get_units(value: any): Units; export function value_set_color(value: any, color: Color): void; export function value_set_paint_node(value: any, node?: PaintNode | null): void; export function value_set_shader_float(value: any, floats: number[]): void; export function value_set_shader_int(value: any, ints: number[]): void; export function value_set_shader_matrix(value: any, matrix: number[]): void; export function value_set_units(value: any, units: Units): void; export function value_take_paint_node( value: any, node?: PaintNode | null ): void; export type ActorCreateChildFunc<A = GObject.Object> = (item: A) => Actor; export type BindingActionFunc<A = GObject.Object> = ( gobject: A, action_name: string, key_val: number, modifiers: ModifierType ) => boolean; export type Callback = (actor: Actor) => void; export type EmitInputDeviceEvent = (event: Event, device: InputDevice) => void; export type EventFilterFunc = (event: Event) => boolean; export type PathCallback = (node: PathNode) => void; export type ProgressFunc = ( a: any, b: any, progress: number, retval: any ) => boolean; export type ScriptConnectFunc<A = GObject.Object, B = GObject.Object> = ( script: Script, object: A, signal_name: string, handler_name: string, connect_object: B, flags: GObject.ConnectFlags ) => void; export type TimelineProgressFunc = ( timeline: Timeline, elapsed: number, total: number ) => number; export namespace ActorAlign { export const $gtype: GObject.GType<ActorAlign>; } export enum ActorAlign { FILL = 0, START = 1, CENTER = 2, END = 3, } export namespace AlignAxis { export const $gtype: GObject.GType<AlignAxis>; } export enum AlignAxis { X_AXIS = 0, Y_AXIS = 1, BOTH = 2, } export namespace AnimationMode { export const $gtype: GObject.GType<AnimationMode>; } export enum AnimationMode { CUSTOM_MODE = 0, LINEAR = 1, EASE_IN_QUAD = 2, EASE_OUT_QUAD = 3, EASE_IN_OUT_QUAD = 4, EASE_IN_CUBIC = 5, EASE_OUT_CUBIC = 6, EASE_IN_OUT_CUBIC = 7, EASE_IN_QUART = 8, EASE_OUT_QUART = 9, EASE_IN_OUT_QUART = 10, EASE_IN_QUINT = 11, EASE_OUT_QUINT = 12, EASE_IN_OUT_QUINT = 13, EASE_IN_SINE = 14, EASE_OUT_SINE = 15, EASE_IN_OUT_SINE = 16, EASE_IN_EXPO = 17, EASE_OUT_EXPO = 18, EASE_IN_OUT_EXPO = 19, EASE_IN_CIRC = 20, EASE_OUT_CIRC = 21, EASE_IN_OUT_CIRC = 22, EASE_IN_ELASTIC = 23, EASE_OUT_ELASTIC = 24, EASE_IN_OUT_ELASTIC = 25, EASE_IN_BACK = 26, EASE_OUT_BACK = 27, EASE_IN_OUT_BACK = 28, EASE_IN_BOUNCE = 29, EASE_OUT_BOUNCE = 30, EASE_IN_OUT_BOUNCE = 31, STEPS = 32, STEP_START = 33, STEP_END = 34, CUBIC_BEZIER = 35, EASE = 36, EASE_IN = 37, EASE_OUT = 38, EASE_IN_OUT = 39, ANIMATION_LAST = 40, } export namespace BinAlignment { export const $gtype: GObject.GType<BinAlignment>; } export enum BinAlignment { FIXED = 0, FILL = 1, START = 2, END = 3, CENTER = 4, } export namespace BindCoordinate { export const $gtype: GObject.GType<BindCoordinate>; } export enum BindCoordinate { X = 0, Y = 1, WIDTH = 2, HEIGHT = 3, POSITION = 4, SIZE = 5, ALL = 6, } export namespace BoxAlignment { export const $gtype: GObject.GType<BoxAlignment>; } export enum BoxAlignment { START = 0, END = 1, CENTER = 2, } export namespace ButtonState { export const $gtype: GObject.GType<ButtonState>; } export enum ButtonState { RELEASED = 0, PRESSED = 1, } export namespace ContentGravity { export const $gtype: GObject.GType<ContentGravity>; } export enum ContentGravity { TOP_LEFT = 0, TOP = 1, TOP_RIGHT = 2, LEFT = 3, CENTER = 4, RIGHT = 5, BOTTOM_LEFT = 6, BOTTOM = 7, BOTTOM_RIGHT = 8, RESIZE_FILL = 9, RESIZE_ASPECT = 10, } export namespace DragAxis { export const $gtype: GObject.GType<DragAxis>; } export enum DragAxis { AXIS_NONE = 0, X_AXIS = 1, Y_AXIS = 2, } export namespace EventType { export const $gtype: GObject.GType<EventType>; } export enum EventType { NOTHING = 0, KEY_PRESS = 1, KEY_RELEASE = 2, MOTION = 3, ENTER = 4, LEAVE = 5, BUTTON_PRESS = 6, BUTTON_RELEASE = 7, SCROLL = 8, STAGE_STATE = 9, DESTROY_NOTIFY = 10, CLIENT_MESSAGE = 11, TOUCH_BEGIN = 12, TOUCH_UPDATE = 13, TOUCH_END = 14, TOUCH_CANCEL = 15, TOUCHPAD_PINCH = 16, TOUCHPAD_SWIPE = 17, PROXIMITY_IN = 18, PROXIMITY_OUT = 19, PAD_BUTTON_PRESS = 20, PAD_BUTTON_RELEASE = 21, PAD_STRIP = 22, PAD_RING = 23, DEVICE_ADDED = 24, DEVICE_REMOVED = 25, IM_COMMIT = 26, IM_DELETE = 27, IM_PREEDIT = 28, EVENT_LAST = 29, } export namespace FlowOrientation { export const $gtype: GObject.GType<FlowOrientation>; } export enum FlowOrientation { HORIZONTAL = 0, VERTICAL = 1, } export namespace FrameResult { export const $gtype: GObject.GType<FrameResult>; } export enum FrameResult { PENDING_PRESENTED = 0, IDLE = 1, } export namespace GestureTriggerEdge { export const $gtype: GObject.GType<GestureTriggerEdge>; } export enum GestureTriggerEdge { NONE = 0, AFTER = 1, BEFORE = 2, } export namespace Gravity { export const $gtype: GObject.GType<Gravity>; } export enum Gravity { NONE = 0, NORTH = 1, NORTH_EAST = 2, EAST = 3, SOUTH_EAST = 4, SOUTH = 5, SOUTH_WEST = 6, WEST = 7, NORTH_WEST = 8, CENTER = 9, } export namespace GridPosition { export const $gtype: GObject.GType<GridPosition>; } export enum GridPosition { LEFT = 0, RIGHT = 1, TOP = 2, BOTTOM = 3, } export class ImageError extends GLib.Error { static $gtype: GObject.GType<ImageError>; constructor(options: { message: string; code: number }); constructor(copy: ImageError); // Properties static DATA: number; // Members static quark(): GLib.Quark; } export class InitError extends GLib.Error { static $gtype: GObject.GType<InitError>; constructor(options: { message: string; code: number }); constructor(copy: InitError); // Properties static SUCCESS: number; static ERROR_UNKNOWN: number; static ERROR_THREADS: number; static ERROR_BACKEND: number; static ERROR_INTERNAL: number; // Members static quark(): GLib.Quark; } export namespace InputAxis { export const $gtype: GObject.GType<InputAxis>; } export enum InputAxis { IGNORE = 0, X = 1, Y = 2, PRESSURE = 3, XTILT = 4, YTILT = 5, WHEEL = 6, DISTANCE = 7, ROTATION = 8, SLIDER = 9, LAST = 10, } export namespace InputContentPurpose { export const $gtype: GObject.GType<InputContentPurpose>; } export enum InputContentPurpose { NORMAL = 0, ALPHA = 1, DIGITS = 2, NUMBER = 3, PHONE = 4, URL = 5, EMAIL = 6, NAME = 7, PASSWORD = 8, DATE = 9, TIME = 10, DATETIME = 11, TERMINAL = 12, } export namespace InputDeviceMapping { export const $gtype: GObject.GType<InputDeviceMapping>; } export enum InputDeviceMapping { ABSOLUTE = 0, RELATIVE = 1, } export namespace InputDevicePadSource { export const $gtype: GObject.GType<InputDevicePadSource>; } export enum InputDevicePadSource { UNKNOWN = 0, FINGER = 1, } export namespace InputDeviceToolType { export const $gtype: GObject.GType<InputDeviceToolType>; } export enum InputDeviceToolType { NONE = 0, PEN = 1, ERASER = 2, BRUSH = 3, PENCIL = 4, AIRBRUSH = 5, MOUSE = 6, LENS = 7, } export namespace InputDeviceType { export const $gtype: GObject.GType<InputDeviceType>; } export enum InputDeviceType { POINTER_DEVICE = 0, KEYBOARD_DEVICE = 1, EXTENSION_DEVICE = 2, JOYSTICK_DEVICE = 3, TABLET_DEVICE = 4, TOUCHPAD_DEVICE = 5, TOUCHSCREEN_DEVICE = 6, PEN_DEVICE = 7, ERASER_DEVICE = 8, CURSOR_DEVICE = 9, PAD_DEVICE = 10, N_DEVICE_TYPES = 11, } export namespace InputMode { export const $gtype: GObject.GType<InputMode>; } export enum InputMode { LOGICAL = 0, PHYSICAL = 1, FLOATING = 2, } export namespace InputPanelState { export const $gtype: GObject.GType<InputPanelState>; } export enum InputPanelState { OFF = 0, ON = 1, TOGGLE = 2, } export namespace Interpolation { export const $gtype: GObject.GType<Interpolation>; } export enum Interpolation { LINEAR = 0, CUBIC = 1, } export namespace KeyState { export const $gtype: GObject.GType<KeyState>; } export enum KeyState { RELEASED = 0, PRESSED = 1, } export namespace LongPressState { export const $gtype: GObject.GType<LongPressState>; } export enum LongPressState { QUERY = 0, ACTIVATE = 1, CANCEL = 2, } export namespace Orientation { export const $gtype: GObject.GType<Orientation>; } export enum Orientation { HORIZONTAL = 0, VERTICAL = 1, } export namespace PanAxis { export const $gtype: GObject.GType<PanAxis>; } export enum PanAxis { AXIS_NONE = 0, X_AXIS = 1, Y_AXIS = 2, AXIS_AUTO = 3, } export namespace PathNodeType { export const $gtype: GObject.GType<PathNodeType>; } export enum PathNodeType { MOVE_TO = 0, LINE_TO = 1, CURVE_TO = 2, CLOSE = 3, REL_MOVE_TO = 32, REL_LINE_TO = 33, REL_CURVE_TO = 34, } export namespace PickMode { export const $gtype: GObject.GType<PickMode>; } export enum PickMode { NONE = 0, REACTIVE = 1, ALL = 2, } export namespace PointerA11yDwellClickType { export const $gtype: GObject.GType<PointerA11yDwellClickType>; } export enum PointerA11yDwellClickType { NONE = 0, PRIMARY = 1, SECONDARY = 2, MIDDLE = 3, DOUBLE = 4, DRAG = 5, } export namespace PointerA11yDwellDirection { export const $gtype: GObject.GType<PointerA11yDwellDirection>; } export enum PointerA11yDwellDirection { NONE = 0, LEFT = 1, RIGHT = 2, UP = 3, DOWN = 4, } export namespace PointerA11yDwellMode { export const $gtype: GObject.GType<PointerA11yDwellMode>; } export enum PointerA11yDwellMode { WINDOW = 0, GESTURE = 1, } export namespace PointerA11yTimeoutType { export const $gtype: GObject.GType<PointerA11yTimeoutType>; } export enum PointerA11yTimeoutType { SECONDARY_CLICK = 0, DWELL = 1, GESTURE = 2, } export namespace RequestMode { export const $gtype: GObject.GType<RequestMode>; } export enum RequestMode { HEIGHT_FOR_WIDTH = 0, WIDTH_FOR_HEIGHT = 1, CONTENT_SIZE = 2, } export namespace RotateAxis { export const $gtype: GObject.GType<RotateAxis>; } export enum RotateAxis { X_AXIS = 0, Y_AXIS = 1, Z_AXIS = 2, } export namespace RotateDirection { export const $gtype: GObject.GType<RotateDirection>; } export enum RotateDirection { CW = 0, CCW = 1, } export namespace ScalingFilter { export const $gtype: GObject.GType<ScalingFilter>; } export enum ScalingFilter { LINEAR = 0, NEAREST = 1, TRILINEAR = 2, } export class ScriptError extends GLib.Error { static $gtype: GObject.GType<ScriptError>; constructor(options: { message: string; code: number }); constructor(copy: ScriptError); // Properties static TYPE_FUNCTION: number; static PROPERTY: number; static VALUE: number; // Members static quark(): GLib.Quark; } export namespace ScrollDirection { export const $gtype: GObject.GType<ScrollDirection>; } export enum ScrollDirection { UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3, SMOOTH = 4, } export namespace ScrollSource { export const $gtype: GObject.GType<ScrollSource>; } export enum ScrollSource { UNKNOWN = 0, WHEEL = 1, FINGER = 2, CONTINUOUS = 3, } export namespace ShaderType { export const $gtype: GObject.GType<ShaderType>; } export enum ShaderType { VERTEX_SHADER = 0, FRAGMENT_SHADER = 1, } export namespace SnapEdge { export const $gtype: GObject.GType<SnapEdge>; } export enum SnapEdge { TOP = 0, RIGHT = 1, BOTTOM = 2, LEFT = 3, } export namespace StaticColor { export const $gtype: GObject.GType<StaticColor>; } export enum StaticColor { WHITE = 0, BLACK = 1, RED = 2, DARK_RED = 3, GREEN = 4, DARK_GREEN = 5, BLUE = 6, DARK_BLUE = 7, CYAN = 8, DARK_CYAN = 9, MAGENTA = 10, DARK_MAGENTA = 11, YELLOW = 12, DARK_YELLOW = 13, GRAY = 14, DARK_GRAY = 15, LIGHT_GRAY = 16, BUTTER = 17, BUTTER_LIGHT = 18, BUTTER_DARK = 19, ORANGE = 20, ORANGE_LIGHT = 21, ORANGE_DARK = 22, CHOCOLATE = 23, CHOCOLATE_LIGHT = 24, CHOCOLATE_DARK = 25, CHAMELEON = 26, CHAMELEON_LIGHT = 27, CHAMELEON_DARK = 28, SKY_BLUE = 29, SKY_BLUE_LIGHT = 30, SKY_BLUE_DARK = 31, PLUM = 32, PLUM_LIGHT = 33, PLUM_DARK = 34, SCARLET_RED = 35, SCARLET_RED_LIGHT = 36, SCARLET_RED_DARK = 37, ALUMINIUM_1 = 38, ALUMINIUM_2 = 39, ALUMINIUM_3 = 40, ALUMINIUM_4 = 41, ALUMINIUM_5 = 42, ALUMINIUM_6 = 43, TRANSPARENT = 44, } export namespace StepMode { export const $gtype: GObject.GType<StepMode>; } export enum StepMode { START = 0, END = 1, } export namespace TextDirection { export const $gtype: GObject.GType<TextDirection>; } export enum TextDirection { DEFAULT = 0, LTR = 1, RTL = 2, } export namespace TextureQuality { export const $gtype: GObject.GType<TextureQuality>; } export enum TextureQuality { LOW = 0, MEDIUM = 1, HIGH = 2, } export namespace TimelineDirection { export const $gtype: GObject.GType<TimelineDirection>; } export enum TimelineDirection { FORWARD = 0, BACKWARD = 1, } export namespace TouchpadGesturePhase { export const $gtype: GObject.GType<TouchpadGesturePhase>; } export enum TouchpadGesturePhase { BEGIN = 0, UPDATE = 1, END = 2, CANCEL = 3, } export namespace UnitType { export const $gtype: GObject.GType<UnitType>; } export enum UnitType { PIXEL = 0, EM = 1, MM = 2, POINT = 3, CM = 4, } export namespace ZoomAxis { export const $gtype: GObject.GType<ZoomAxis>; } export enum ZoomAxis { X_AXIS = 0, Y_AXIS = 1, BOTH = 2, } export namespace ActorFlags { export const $gtype: GObject.GType<ActorFlags>; } export enum ActorFlags { MAPPED = 2, REALIZED = 4, REACTIVE = 8, VISIBLE = 16, NO_LAYOUT = 32, } export namespace ContentRepeat { export const $gtype: GObject.GType<ContentRepeat>; } export enum ContentRepeat { NONE = 0, X_AXIS = 1, Y_AXIS = 2, BOTH = 3, } export namespace DebugFlag { export const $gtype: GObject.GType<DebugFlag>; } export enum DebugFlag { MISC = 1, ACTOR = 2, TEXTURE = 4, EVENT = 8, PAINT = 16, PANGO = 32, BACKEND = 64, SCHEDULER = 128, SCRIPT = 256, SHADER = 512, MULTISTAGE = 1024, ANIMATION = 2048, LAYOUT = 4096, PICK = 8192, EVENTLOOP = 16384, CLIPPING = 32768, OOB_TRANSFORMS = 65536, } export namespace DrawDebugFlag { export const $gtype: GObject.GType<DrawDebugFlag>; } export enum DrawDebugFlag { DISABLE_SWAP_EVENTS = 1, DISABLE_CLIPPED_REDRAWS = 2, REDRAWS = 4, PAINT_VOLUMES = 8, DISABLE_CULLING = 16, DISABLE_OFFSCREEN_REDIRECT = 32, CONTINUOUS_REDRAW = 64, PAINT_DEFORM_TILES = 128, PAINT_DAMAGE_REGION = 256, } export namespace EffectPaintFlags { export const $gtype: GObject.GType<EffectPaintFlags>; } export enum EffectPaintFlags { ACTOR_DIRTY = 1, BYPASS_EFFECT = 2, } export namespace EventFlags { export const $gtype: GObject.GType<EventFlags>; } export enum EventFlags { NONE = 0, FLAG_SYNTHETIC = 1, FLAG_INPUT_METHOD = 2, FLAG_REPEATED = 4, } export namespace FeatureFlags { export const $gtype: GObject.GType<FeatureFlags>; } export enum FeatureFlags { STAGE_STATIC = 64, STAGE_CURSOR = 256, SHADERS_GLSL = 512, OFFSCREEN = 1024, STAGE_MULTIPLE = 2048, SWAP_EVENTS = 4096, } export namespace InputContentHintFlags { export const $gtype: GObject.GType<InputContentHintFlags>; } export enum InputContentHintFlags { COMPLETION = 1, SPELLCHECK = 2, AUTO_CAPITALIZATION = 4, LOWERCASE = 8, UPPERCASE = 16, TITLECASE = 32, HIDDEN_TEXT = 64, SENSITIVE_DATA = 128, LATIN = 256, MULTILINE = 512, } export namespace KeyboardA11yFlags { export const $gtype: GObject.GType<KeyboardA11yFlags>; } export enum KeyboardA11yFlags { KEYBOARD_ENABLED = 1, TIMEOUT_ENABLED = 2, MOUSE_KEYS_ENABLED = 4, SLOW_KEYS_ENABLED = 8, SLOW_KEYS_BEEP_PRESS = 16, SLOW_KEYS_BEEP_ACCEPT = 32, SLOW_KEYS_BEEP_REJECT = 64, BOUNCE_KEYS_ENABLED = 128, BOUNCE_KEYS_BEEP_REJECT = 256, TOGGLE_KEYS_ENABLED = 512, STICKY_KEYS_ENABLED = 1024, STICKY_KEYS_TWO_KEY_OFF = 2048, STICKY_KEYS_BEEP = 4096, FEATURE_STATE_CHANGE_BEEP = 8192, } export namespace ModifierType { export const $gtype: GObject.GType<ModifierType>; } export enum ModifierType { SHIFT_MASK = 1, LOCK_MASK = 2, CONTROL_MASK = 4, MOD1_MASK = 8, MOD2_MASK = 16, MOD3_MASK = 32, MOD4_MASK = 64, MOD5_MASK = 128, BUTTON1_MASK = 256, BUTTON2_MASK = 512, BUTTON3_MASK = 1024, BUTTON4_MASK = 2048, BUTTON5_MASK = 4096, MODIFIER_RESERVED_13_MASK = 8192, MODIFIER_RESERVED_14_MASK = 16384, MODIFIER_RESERVED_15_MASK = 32768, MODIFIER_RESERVED_16_MASK = 65536, MODIFIER_RESERVED_17_MASK = 131072, MODIFIER_RESERVED_18_MASK = 262144, MODIFIER_RESERVED_19_MASK = 524288, MODIFIER_RESERVED_20_MASK = 1048576, MODIFIER_RESERVED_21_MASK = 2097152, MODIFIER_RESERVED_22_MASK = 4194304, MODIFIER_RESERVED_23_MASK = 8388608, MODIFIER_RESERVED_24_MASK = 16777216, MODIFIER_RESERVED_25_MASK = 33554432, SUPER_MASK = 67108864, HYPER_MASK = 134217728, META_MASK = 268435456, MODIFIER_RESERVED_29_MASK = 536870912, RELEASE_MASK = 1073741824, MODIFIER_MASK = 1543512063, } export namespace OffscreenRedirect { export const $gtype: GObject.GType<OffscreenRedirect>; } export enum OffscreenRedirect { AUTOMATIC_FOR_OPACITY = 1, ALWAYS = 2, ON_IDLE = 4, } export namespace PaintFlag { export const $gtype: GObject.GType<PaintFlag>; } export enum PaintFlag { NONE = 0, NO_CURSORS = 1, FORCE_CURSORS = 2, CLEAR = 4, } export namespace PickDebugFlag { export const $gtype: GObject.GType<PickDebugFlag>; } export enum PickDebugFlag { PICKING = 1, } export namespace PointerA11yFlags { export const $gtype: GObject.GType<PointerA11yFlags>; } export enum PointerA11yFlags { SECONDARY_CLICK_ENABLED = 1, DWELL_ENABLED = 2, } export namespace RepaintFlags { export const $gtype: GObject.GType<RepaintFlags>; } export enum RepaintFlags { PRE_PAINT = 1, POST_PAINT = 2, } export namespace ScrollFinishFlags { export const $gtype: GObject.GType<ScrollFinishFlags>; } export enum ScrollFinishFlags { NONE = 0, HORIZONTAL = 1, VERTICAL = 2, } export namespace ScrollMode { export const $gtype: GObject.GType<ScrollMode>; } export enum ScrollMode { NONE = 0, HORIZONTALLY = 1, VERTICALLY = 2, BOTH = 3, } export namespace StageState { export const $gtype: GObject.GType<StageState>; } export enum StageState { ACTIVATED = 8, } export namespace SwipeDirection { export const $gtype: GObject.GType<SwipeDirection>; } export enum SwipeDirection { UP = 1, DOWN = 2, LEFT = 4, RIGHT = 8, } export namespace TextureFlags { export const $gtype: GObject.GType<TextureFlags>; } export enum TextureFlags { NONE = 0, RGB_FLAG_BGR = 2, RGB_FLAG_PREMULT = 4, YUV_FLAG_YUV2 = 8, } export namespace VirtualDeviceType { export const $gtype: GObject.GType<VirtualDeviceType>; } export enum VirtualDeviceType { NONE = 0, KEYBOARD = 1, POINTER = 2, TOUCHSCREEN = 4, } export namespace Action { export interface ConstructorProperties extends ActorMeta.ConstructorProperties { [key: string]: any; } } export abstract class Action extends ActorMeta { static $gtype: GObject.GType<Action>; constructor( properties?: Partial<Action.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Action.ConstructorProperties>, ...args: any[] ): void; } export namespace Actor { export interface ConstructorProperties<A = LayoutManager, B = Content> extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; actions: Action; allocation: ActorBox; background_color: Color; backgroundColor: Color; background_color_set: boolean; backgroundColorSet: boolean; child_transform_set: boolean; childTransformSet: boolean; clip_rect: Graphene.Rect; clipRect: Graphene.Rect; clip_to_allocation: boolean; clipToAllocation: boolean; constraints: Constraint; content: B; content_box: ActorBox; contentBox: ActorBox; content_gravity: ContentGravity; contentGravity: ContentGravity; content_repeat: ContentRepeat; contentRepeat: ContentRepeat; effect: Effect; first_child: Actor; firstChild: Actor; fixed_position_set: boolean; fixedPositionSet: boolean; fixed_x: number; fixedX: number; fixed_y: number; fixedY: number; has_clip: boolean; hasClip: boolean; has_pointer: boolean; hasPointer: boolean; height: number; last_child: Actor; lastChild: Actor; layout_manager: A; layoutManager: A; magnification_filter: ScalingFilter; magnificationFilter: ScalingFilter; mapped: boolean; margin_bottom: number; marginBottom: number; margin_left: number; marginLeft: number; margin_right: number; marginRight: number; margin_top: number; marginTop: number; min_height: number; minHeight: number; min_height_set: boolean; minHeightSet: boolean; min_width: number; minWidth: number; min_width_set: boolean; minWidthSet: boolean; minification_filter: ScalingFilter; minificationFilter: ScalingFilter; name: string; natural_height: number; naturalHeight: number; natural_height_set: boolean; naturalHeightSet: boolean; natural_width: number; naturalWidth: number; natural_width_set: boolean; naturalWidthSet: boolean; offscreen_redirect: OffscreenRedirect; offscreenRedirect: OffscreenRedirect; opacity: number; pivot_point: Graphene.Point; pivotPoint: Graphene.Point; pivot_point_z: number; pivotPointZ: number; position: Graphene.Point; reactive: boolean; realized: boolean; request_mode: RequestMode; requestMode: RequestMode; rotation_angle_x: number; rotationAngleX: number; rotation_angle_y: number; rotationAngleY: number; rotation_angle_z: number; rotationAngleZ: number; scale_x: number; scaleX: number; scale_y: number; scaleY: number; scale_z: number; scaleZ: number; show_on_set_parent: boolean; showOnSetParent: boolean; size: Graphene.Size; text_direction: TextDirection; textDirection: TextDirection; transform_set: boolean; transformSet: boolean; translation_x: number; translationX: number; translation_y: number; translationY: number; translation_z: number; translationZ: number; visible: boolean; width: number; x: number; x_align: ActorAlign; xAlign: ActorAlign; x_expand: boolean; xExpand: boolean; y: number; y_align: ActorAlign; yAlign: ActorAlign; y_expand: boolean; yExpand: boolean; z_position: number; zPosition: number; } } export class Actor<A = LayoutManager, B = Content> extends GObject.InitiallyUnowned implements Atk.ImplementorIface, Animatable, Container<Actor>, Scriptable { static $gtype: GObject.GType<Actor>; constructor( properties?: Partial<Actor.ConstructorProperties<A, B>>, ...args: any[] ); _init( properties?: Partial<Actor.ConstructorProperties<A, B>>, ...args: any[] ): void; // Properties actions: Action; allocation: ActorBox; background_color: Color; backgroundColor: Color; background_color_set: boolean; backgroundColorSet: boolean; child_transform_set: boolean; childTransformSet: boolean; clip_rect: Graphene.Rect; clipRect: Graphene.Rect; clip_to_allocation: boolean; clipToAllocation: boolean; constraints: Constraint; content: B; content_box: ActorBox; contentBox: ActorBox; content_gravity: ContentGravity; contentGravity: ContentGravity; content_repeat: ContentRepeat; contentRepeat: ContentRepeat; effect: Effect; first_child: Actor; firstChild: Actor; fixed_position_set: boolean; fixedPositionSet: boolean; fixed_x: number; fixedX: number; fixed_y: number; fixedY: number; has_clip: boolean; hasClip: boolean; has_pointer: boolean; hasPointer: boolean; height: number; last_child: Actor; lastChild: Actor; layout_manager: A; layoutManager: A; magnification_filter: ScalingFilter; magnificationFilter: ScalingFilter; mapped: boolean; margin_bottom: number; marginBottom: number; margin_left: number; marginLeft: number; margin_right: number; marginRight: number; margin_top: number; marginTop: number; min_height: number; minHeight: number; min_height_set: boolean; minHeightSet: boolean; min_width: number; minWidth: number; min_width_set: boolean; minWidthSet: boolean; minification_filter: ScalingFilter; minificationFilter: ScalingFilter; name: string; natural_height: number; naturalHeight: number; natural_height_set: boolean; naturalHeightSet: boolean; natural_width: number; naturalWidth: number; natural_width_set: boolean; naturalWidthSet: boolean; offscreen_redirect: OffscreenRedirect; offscreenRedirect: OffscreenRedirect; opacity: number; pivot_point: Graphene.Point; pivotPoint: Graphene.Point; pivot_point_z: number; pivotPointZ: number; position: Graphene.Point; reactive: boolean; realized: boolean; request_mode: RequestMode; requestMode: RequestMode; rotation_angle_x: number; rotationAngleX: number; rotation_angle_y: number; rotationAngleY: number; rotation_angle_z: number; rotationAngleZ: number; scale_x: number; scaleX: number; scale_y: number; scaleY: number; scale_z: number; scaleZ: number; show_on_set_parent: boolean; showOnSetParent: boolean; size: Graphene.Size; text_direction: TextDirection; textDirection: TextDirection; transform_set: boolean; transformSet: boolean; translation_x: number; translationX: number; translation_y: number; translationY: number; translation_z: number; translationZ: number; visible: boolean; width: number; x: number; x_align: ActorAlign; xAlign: ActorAlign; x_expand: boolean; xExpand: boolean; y: number; y_align: ActorAlign; yAlign: ActorAlign; y_expand: boolean; yExpand: boolean; z_position: number; zPosition: number; // Fields flags: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'button-press-event', callback: (_source: this, event: ButtonEvent) => boolean ): number; connect_after( signal: 'button-press-event', callback: (_source: this, event: ButtonEvent) => boolean ): number; emit(signal: 'button-press-event', event: ButtonEvent): void; connect( signal: 'button-release-event', callback: (_source: this, event: ButtonEvent) => boolean ): number; connect_after( signal: 'button-release-event', callback: (_source: this, event: ButtonEvent) => boolean ): number; emit(signal: 'button-release-event', event: ButtonEvent): void; connect( signal: 'captured-event', callback: (_source: this, event: Event) => boolean ): number; connect_after( signal: 'captured-event', callback: (_source: this, event: Event) => boolean ): number; emit(signal: 'captured-event', event: Event): void; connect(signal: 'destroy', callback: (_source: this) => void): number; connect_after(signal: 'destroy', callback: (_source: this) => void): number; emit(signal: 'destroy'): void; connect( signal: 'enter-event', callback: (_source: this, event: CrossingEvent) => boolean ): number; connect_after( signal: 'enter-event', callback: (_source: this, event: CrossingEvent) => boolean ): number; emit(signal: 'enter-event', event: CrossingEvent): void; connect( signal: 'event', callback: (_source: this, event: Event) => boolean ): number; connect_after( signal: 'event', callback: (_source: this, event: Event) => boolean ): number; emit(signal: 'event', event: Event): void; connect(signal: 'hide', callback: (_source: this) => void): number; connect_after(signal: 'hide', callback: (_source: this) => void): number; emit(signal: 'hide'): void; connect(signal: 'key-focus-in', callback: (_source: this) => void): number; connect_after( signal: 'key-focus-in', callback: (_source: this) => void ): number; emit(signal: 'key-focus-in'): void; connect(signal: 'key-focus-out', callback: (_source: this) => void): number; connect_after( signal: 'key-focus-out', callback: (_source: this) => void ): number; emit(signal: 'key-focus-out'): void; connect( signal: 'key-press-event', callback: (_source: this, event: KeyEvent) => boolean ): number; connect_after( signal: 'key-press-event', callback: (_source: this, event: KeyEvent) => boolean ): number; emit(signal: 'key-press-event', event: KeyEvent): void; connect( signal: 'key-release-event', callback: (_source: this, event: KeyEvent) => boolean ): number; connect_after( signal: 'key-release-event', callback: (_source: this, event: KeyEvent) => boolean ): number; emit(signal: 'key-release-event', event: KeyEvent): void; connect( signal: 'leave-event', callback: (_source: this, event: CrossingEvent) => boolean ): number; connect_after( signal: 'leave-event', callback: (_source: this, event: CrossingEvent) => boolean ): number; emit(signal: 'leave-event', event: CrossingEvent): void; connect( signal: 'motion-event', callback: (_source: this, event: MotionEvent) => boolean ): number; connect_after( signal: 'motion-event', callback: (_source: this, event: MotionEvent) => boolean ): number; emit(signal: 'motion-event', event: MotionEvent): void; connect( signal: 'paint', callback: (_source: this, paint_context: PaintContext) => void ): number; connect_after( signal: 'paint', callback: (_source: this, paint_context: PaintContext) => void ): number; emit(signal: 'paint', paint_context: PaintContext): void; connect( signal: 'parent-set', callback: (_source: this, old_parent: Actor | null) => void ): number; connect_after( signal: 'parent-set', callback: (_source: this, old_parent: Actor | null) => void ): number; emit(signal: 'parent-set', old_parent: Actor | null): void; connect( signal: 'pick', callback: (_source: this, pick_context: PickContext) => void ): number; connect_after( signal: 'pick', callback: (_source: this, pick_context: PickContext) => void ): number; emit(signal: 'pick', pick_context: PickContext): void; connect( signal: 'queue-redraw', callback: (_source: this, origin: Actor, volume: PaintVolume) => boolean ): number; connect_after( signal: 'queue-redraw', callback: (_source: this, origin: Actor, volume: PaintVolume) => boolean ): number; emit(signal: 'queue-redraw', origin: Actor, volume: PaintVolume): void; connect( signal: 'queue-relayout', callback: (_source: this) => void ): number; connect_after( signal: 'queue-relayout', callback: (_source: this) => void ): number; emit(signal: 'queue-relayout'): void; connect(signal: 'realize', callback: (_source: this) => void): number; connect_after(signal: 'realize', callback: (_source: this) => void): number; emit(signal: 'realize'): void; connect( signal: 'resource-scale-changed', callback: (_source: this) => void ): number; connect_after( signal: 'resource-scale-changed', callback: (_source: this) => void ): number; emit(signal: 'resource-scale-changed'): void; connect( signal: 'scroll-event', callback: (_source: this, event: ScrollEvent) => boolean ): number; connect_after( signal: 'scroll-event', callback: (_source: this, event: ScrollEvent) => boolean ): number; emit(signal: 'scroll-event', event: ScrollEvent): void; connect(signal: 'show', callback: (_source: this) => void): number; connect_after(signal: 'show', callback: (_source: this) => void): number; emit(signal: 'show'): void; connect( signal: 'stage-views-changed', callback: (_source: this) => void ): number; connect_after( signal: 'stage-views-changed', callback: (_source: this) => void ): number; emit(signal: 'stage-views-changed'): void; connect( signal: 'touch-event', callback: (_source: this, event: Event) => boolean ): number; connect_after( signal: 'touch-event', callback: (_source: this, event: Event) => boolean ): number; emit(signal: 'touch-event', event: Event): void; connect( signal: 'transition-stopped', callback: (_source: this, name: string, is_finished: boolean) => void ): number; connect_after( signal: 'transition-stopped', callback: (_source: this, name: string, is_finished: boolean) => void ): number; emit( signal: 'transition-stopped', name: string, is_finished: boolean ): void; connect( signal: 'transitions-completed', callback: (_source: this) => void ): number; connect_after( signal: 'transitions-completed', callback: (_source: this) => void ): number; emit(signal: 'transitions-completed'): void; connect(signal: 'unrealize', callback: (_source: this) => void): number; connect_after( signal: 'unrealize', callback: (_source: this) => void ): number; emit(signal: 'unrealize'): void; // Constructors static ['new'](): Actor; // Members add_action(action: Action): void; add_action_with_name(name: string, action: Action): void; add_child(child: Actor): void; add_constraint(constraint: Constraint): void; add_constraint_with_name(name: string, constraint: Constraint): void; add_effect(effect: Effect): void; add_effect_with_name(name: string, effect: Effect): void; add_transition(name: string, transition: Transition): void; allocate(box: ActorBox): void; allocate_align_fill( box: ActorBox, x_align: number, y_align: number, x_fill: boolean, y_fill: boolean ): void; allocate_available_size( x: number, y: number, available_width: number, available_height: number ): void; allocate_preferred_size(x: number, y: number): void; apply_relative_transform_to_point( ancestor: Actor | null, point: Graphene.Point3D ): Graphene.Point3D; apply_transform_to_point(point: Graphene.Point3D): Graphene.Point3D; bind_model( model: Gio.ListModel | null, create_child_func: ActorCreateChildFunc ): void; clear_actions(): void; clear_constraints(): void; clear_effects(): void; contains(descendant: Actor): boolean; continue_paint(paint_context: PaintContext): void; continue_pick(pick_context: PickContext): void; create_pango_context(): Pango.Context; create_pango_layout(text?: string | null): Pango.Layout; destroy(): void; destroy_all_children(): void; event(event: Event, capture: boolean): boolean; get_abs_allocation_vertices(): Graphene.Point3D[]; get_accessible(): Atk.Object; get_action(name: string): Action; get_actions(): Action[]; get_allocation_box(): ActorBox; get_background_color(): Color; get_child_at_index(index_: number): Actor; get_child_transform(): Matrix; get_children(): Actor[]; get_children(...args: never[]): never; get_clip(): [number | null, number | null, number | null, number | null]; get_clip_to_allocation(): boolean; get_constraint(name: string): Constraint; get_constraints(): Constraint[]; get_content(): B; get_content_box(): ActorBox; get_content_gravity(): ContentGravity; get_content_repeat(): ContentRepeat; get_content_scaling_filters(): [ScalingFilter | null, ScalingFilter | null]; get_default_paint_volume(): PaintVolume; get_easing_delay(): number; get_easing_duration(): number; get_easing_mode(): AnimationMode; get_effect(name: string): Effect; get_effects(): Effect[]; get_first_child(): Actor; get_fixed_position(): [boolean, number | null, number | null]; get_fixed_position_set(): boolean; get_flags(): ActorFlags; get_height(): number; get_last_child(): Actor; get_layout_manager(): A; get_margin(): Margin; get_margin_bottom(): number; get_margin_left(): number; get_margin_right(): number; get_margin_top(): number; get_n_children(): number; get_name(): string; get_next_sibling(): Actor; get_offscreen_redirect(): OffscreenRedirect; get_opacity(): number; get_opacity_override(): number; get_paint_box(): [boolean, ActorBox]; get_paint_opacity(): number; get_paint_visibility(): boolean; get_paint_volume(): PaintVolume; get_pango_context(): Pango.Context; get_parent(): Actor | null; get_pivot_point(): [number | null, number | null]; get_pivot_point_z(): number; get_position(): [number | null, number | null]; get_preferred_height(for_width: number): [number | null, number | null]; get_preferred_size(): [ number | null, number | null, number | null, number | null ]; get_preferred_width(for_height: number): [number | null, number | null]; get_previous_sibling(): Actor; get_reactive(): boolean; get_request_mode(): RequestMode; get_resource_scale(): number; get_rotation_angle(axis: RotateAxis): number; get_scale(): [number | null, number | null]; get_scale_z(): number; get_size(): [number | null, number | null]; get_stage(): Stage; get_text_direction(): TextDirection; get_transform(): Matrix; get_transformed_extents(): Graphene.Rect; get_transformed_paint_volume(relative_to_ancestor: Actor): PaintVolume; get_transformed_position(): [number | null, number | null]; get_transformed_size(): [number | null, number | null]; get_transition(name: string): Transition; get_translation(): [number | null, number | null, number | null]; get_width(): number; get_x(): number; get_x_align(): ActorAlign; get_x_expand(): boolean; get_y(): number; get_y_align(): ActorAlign; get_y_expand(): boolean; get_z_position(): number; grab_key_focus(): void; has_accessible(): boolean; has_actions(): boolean; has_allocation(): boolean; has_constraints(): boolean; has_damage(): boolean; has_effects(): boolean; has_key_focus(): boolean; has_mapped_clones(): boolean; has_overlaps(): boolean; hide(): void; inhibit_culling(): void; insert_child_above(child: Actor, sibling?: Actor | null): void; insert_child_at_index(child: Actor, index_: number): void; insert_child_below(child: Actor, sibling?: Actor | null): void; invalidate_transform(): void; is_effectively_on_stage_view(view: StageView): boolean; is_in_clone_paint(): boolean; is_mapped(): boolean; is_realized(): boolean; is_rotated(): boolean; is_scaled(): boolean; is_visible(): boolean; map(): void; move_by(dx: number, dy: number): void; needs_expand(orientation: Orientation): boolean; paint(paint_context: PaintContext): void; peek_stage_views(): StageView[]; pick(pick_context: PickContext): void; pick_box(pick_context: PickContext, box: ActorBox): void; queue_redraw(): void; queue_redraw_with_clip(clip?: cairo.RectangleInt | null): void; queue_relayout(): void; realize(): void; remove_action(action: Action): void; remove_action_by_name(name: string): void; remove_all_children(): void; remove_all_transitions(): void; remove_child(child: Actor): void; remove_clip(): void; remove_constraint(constraint: Constraint): void; remove_constraint_by_name(name: string): void; remove_effect(effect: Effect): void; remove_effect_by_name(name: string): void; remove_transition(name: string): void; replace_child(old_child: Actor, new_child: Actor): void; restore_easing_state(): void; save_easing_state(): void; set_allocation(box: ActorBox): void; set_background_color(color?: Color | null): void; set_child_above_sibling(child: Actor, sibling?: Actor | null): void; set_child_at_index(child: Actor, index_: number): void; set_child_below_sibling(child: Actor, sibling?: Actor | null): void; set_child_transform(transform?: Matrix | null): void; set_clip(xoff: number, yoff: number, width: number, height: number): void; set_clip_to_allocation(clip_set: boolean): void; set_content(content?: B | null): void; set_content_gravity(gravity: ContentGravity): void; set_content_repeat(repeat: ContentRepeat): void; set_content_scaling_filters( min_filter: ScalingFilter, mag_filter: ScalingFilter ): void; set_easing_delay(msecs: number): void; set_easing_duration(msecs: number): void; set_easing_mode(mode: AnimationMode): void; set_fixed_position_set(is_set: boolean): void; set_flags(flags: ActorFlags): void; set_height(height: number): void; set_layout_manager(manager?: A | null): void; set_margin(margin: Margin): void; set_margin_bottom(margin: number): void; set_margin_left(margin: number): void; set_margin_right(margin: number): void; set_margin_top(margin: number): void; set_name(name: string): void; set_offscreen_redirect(redirect: OffscreenRedirect): void; set_opacity(opacity: number): void; set_opacity_override(opacity: number): void; set_pivot_point(pivot_x: number, pivot_y: number): void; set_pivot_point_z(pivot_z: number): void; set_position(x: number, y: number): void; set_reactive(reactive: boolean): void; set_request_mode(mode: RequestMode): void; set_rotation_angle(axis: RotateAxis, angle: number): void; set_scale(scale_x: number, scale_y: number): void; set_scale_z(scale_z: number): void; set_size(width: number, height: number): void; set_text_direction(text_dir: TextDirection): void; set_transform(transform?: Matrix | null): void; set_translation( translate_x: number, translate_y: number, translate_z: number ): void; set_width(width: number): void; set_x(x: number): void; set_x_align(x_align: ActorAlign): void; set_x_expand(expand: boolean): void; set_y(y: number): void; set_y_align(y_align: ActorAlign): void; set_y_expand(expand: boolean): void; set_z_position(z_position: number): void; should_pick_paint(): boolean; show(): void; transform_stage_point(x: number, y: number): [boolean, number, number]; uninhibit_culling(): void; unmap(): void; unrealize(): void; unset_flags(flags: ActorFlags): void; vfunc_allocate(box: ActorBox): void; vfunc_apply_transform(matrix: Matrix): void; vfunc_button_press_event(event: ButtonEvent): boolean; vfunc_button_release_event(event: ButtonEvent): boolean; vfunc_calculate_resource_scale(phase: number): number; vfunc_captured_event(event: Event): boolean; vfunc_destroy(): void; vfunc_enter_event(event: CrossingEvent): boolean; vfunc_event(event: Event): boolean; vfunc_get_accessible(): Atk.Object; vfunc_get_paint_volume(volume: PaintVolume): boolean; vfunc_get_preferred_height( for_width: number ): [number | null, number | null]; vfunc_get_preferred_width( for_height: number ): [number | null, number | null]; vfunc_has_accessible(): boolean; vfunc_has_overlaps(): boolean; vfunc_hide(): void; vfunc_hide_all(): void; vfunc_key_focus_in(): void; vfunc_key_focus_out(): void; vfunc_key_press_event(event: KeyEvent): boolean; vfunc_key_release_event(event: KeyEvent): boolean; vfunc_leave_event(event: CrossingEvent): boolean; vfunc_map(): void; vfunc_motion_event(event: MotionEvent): boolean; vfunc_paint(paint_context: PaintContext): void; vfunc_paint_node(root: PaintNode): void; vfunc_parent_set(old_parent: Actor): void; vfunc_pick(pick_context: PickContext): void; vfunc_queue_redraw( leaf_that_queued: Actor, paint_volume: PaintVolume ): boolean; vfunc_queue_relayout(): void; vfunc_realize(): void; vfunc_resource_scale_changed(): void; vfunc_scroll_event(event: ScrollEvent): boolean; vfunc_show(): void; vfunc_touch_event(event: TouchEvent): boolean; vfunc_unmap(): void; vfunc_unrealize(): void; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: Actor): void; child_get_property(child: Actor, property: string, value: any): void; child_notify(child: Actor, pspec: GObject.ParamSpec): void; child_set_property(child: Actor, property: string, value: any): void; create_child_meta(actor: Actor): void; destroy_child_meta(actor: Actor): void; find_child_by_name(child_name: string): Actor; get_child_meta(actor: Actor): ChildMeta; lower_child(actor: Actor, sibling?: Actor | null): void; raise_child(actor: Actor, sibling?: Actor | null): void; remove_actor(actor: Actor): void; sort_depth_order(): void; vfunc_actor_added(actor: Actor): void; vfunc_actor_removed(actor: Actor): void; vfunc_add(actor: Actor): void; vfunc_child_notify(child: Actor, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: Actor): void; vfunc_destroy_child_meta(actor: Actor): void; vfunc_get_child_meta(actor: Actor): ChildMeta; vfunc_lower(actor: Actor, sibling?: Actor | null): void; vfunc_raise(actor: Actor, sibling?: Actor | null): void; vfunc_remove(actor: Actor): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace ActorMeta { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; actor: Actor; enabled: boolean; name: string; } } export abstract class ActorMeta extends GObject.InitiallyUnowned { static $gtype: GObject.GType<ActorMeta>; constructor( properties?: Partial<ActorMeta.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ActorMeta.ConstructorProperties>, ...args: any[] ): void; // Properties actor: Actor; enabled: boolean; name: string; // Members get_actor(): Actor; get_enabled(): boolean; get_name(): string; set_enabled(is_enabled: boolean): void; set_name(name: string): void; vfunc_set_actor(actor?: Actor | null): void; vfunc_set_enabled(is_enabled: boolean): void; } export namespace ActorNode { export interface ConstructorProperties extends PaintNode.ConstructorProperties { [key: string]: any; } } export class ActorNode extends PaintNode { static $gtype: GObject.GType<ActorNode>; constructor( properties?: Partial<ActorNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ActorNode.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](actor: Actor): ActorNode; } export namespace AlignConstraint { export interface ConstructorProperties extends Constraint.ConstructorProperties { [key: string]: any; align_axis: AlignAxis; alignAxis: AlignAxis; factor: number; pivot_point: Graphene.Point; pivotPoint: Graphene.Point; source: Actor; } } export class AlignConstraint extends Constraint { static $gtype: GObject.GType<AlignConstraint>; constructor( properties?: Partial<AlignConstraint.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<AlignConstraint.ConstructorProperties>, ...args: any[] ): void; // Properties align_axis: AlignAxis; alignAxis: AlignAxis; factor: number; pivot_point: Graphene.Point; pivotPoint: Graphene.Point; source: Actor; // Constructors static ['new']( source: Actor | null, axis: AlignAxis, factor: number ): AlignConstraint; // Members get_align_axis(): AlignAxis; get_factor(): number; get_pivot_point(): Graphene.Point; get_source(): Actor; set_align_axis(axis: AlignAxis): void; set_factor(factor: number): void; set_pivot_point(pivot_point: Graphene.Point): void; set_source(source?: Actor | null): void; } export namespace Backend { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class Backend extends GObject.Object { static $gtype: GObject.GType<Backend>; constructor( properties?: Partial<Backend.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Backend.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'font-changed', callback: (_source: this) => void): number; connect_after( signal: 'font-changed', callback: (_source: this) => void ): number; emit(signal: 'font-changed'): void; connect( signal: 'resolution-changed', callback: (_source: this) => void ): number; connect_after( signal: 'resolution-changed', callback: (_source: this) => void ): number; emit(signal: 'resolution-changed'): void; connect( signal: 'settings-changed', callback: (_source: this) => void ): number; connect_after( signal: 'settings-changed', callback: (_source: this) => void ): number; emit(signal: 'settings-changed'): void; // Members get_default_seat(): Seat; get_font_options(): cairo.FontOptions; get_input_method(): InputMethod; get_resolution(): number; set_font_options(options: cairo.FontOptions): void; set_input_method(method: InputMethod): void; } export namespace BinLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; x_align: BinAlignment; xAlign: BinAlignment; y_align: BinAlignment; yAlign: BinAlignment; } } export class BinLayout extends LayoutManager { static $gtype: GObject.GType<BinLayout>; constructor( properties?: Partial<BinLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BinLayout.ConstructorProperties>, ...args: any[] ): void; // Properties x_align: BinAlignment; xAlign: BinAlignment; y_align: BinAlignment; yAlign: BinAlignment; // Constructors static ['new'](x_align: BinAlignment, y_align: BinAlignment): BinLayout; } export namespace BindConstraint { export interface ConstructorProperties extends Constraint.ConstructorProperties { [key: string]: any; coordinate: BindCoordinate; offset: number; source: Actor; } } export class BindConstraint extends Constraint { static $gtype: GObject.GType<BindConstraint>; constructor( properties?: Partial<BindConstraint.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BindConstraint.ConstructorProperties>, ...args: any[] ): void; // Properties coordinate: BindCoordinate; offset: number; source: Actor; // Constructors static ['new']( source: Actor | null, coordinate: BindCoordinate, offset: number ): BindConstraint; // Members get_coordinate(): BindCoordinate; get_offset(): number; get_source(): Actor; set_coordinate(coordinate: BindCoordinate): void; set_offset(offset: number): void; set_source(source?: Actor | null): void; } export namespace BindingPool { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; name: string; } } export class BindingPool extends GObject.Object { static $gtype: GObject.GType<BindingPool>; constructor( properties?: Partial<BindingPool.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BindingPool.ConstructorProperties>, ...args: any[] ): void; // Properties name: string; // Constructors static ['new'](name: string): BindingPool; // Members activate( key_val: number, modifiers: ModifierType, gobject: GObject.Object ): boolean; block_action(action_name: string): void; find_action(key_val: number, modifiers: ModifierType): string; install_action( action_name: string, key_val: number, modifiers: ModifierType, callback: BindingActionFunc ): void; install_closure( action_name: string, key_val: number, modifiers: ModifierType, closure: GObject.Closure ): void; override_action( key_val: number, modifiers: ModifierType, callback: GObject.Callback ): void; override_closure( key_val: number, modifiers: ModifierType, closure: GObject.Closure ): void; remove_action(key_val: number, modifiers: ModifierType): void; unblock_action(action_name: string): void; static find(name: string): BindingPool; static get_for_class(klass?: any | null): BindingPool; } export namespace BlurEffect { export interface ConstructorProperties extends OffscreenEffect.ConstructorProperties { [key: string]: any; } } export class BlurEffect extends OffscreenEffect { static $gtype: GObject.GType<BlurEffect>; constructor( properties?: Partial<BlurEffect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BlurEffect.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): BlurEffect; } export namespace BoxLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; homogeneous: boolean; orientation: Orientation; pack_start: boolean; packStart: boolean; spacing: number; } } export class BoxLayout extends LayoutManager { static $gtype: GObject.GType<BoxLayout>; constructor( properties?: Partial<BoxLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BoxLayout.ConstructorProperties>, ...args: any[] ): void; // Properties homogeneous: boolean; orientation: Orientation; pack_start: boolean; packStart: boolean; spacing: number; // Constructors static ['new'](): BoxLayout; // Members get_homogeneous(): boolean; get_orientation(): Orientation; get_pack_start(): boolean; get_spacing(): number; set_homogeneous(homogeneous: boolean): void; set_orientation(orientation: Orientation): void; set_pack_start(pack_start: boolean): void; set_spacing(spacing: number): void; } export namespace BrightnessContrastEffect { export interface ConstructorProperties extends OffscreenEffect.ConstructorProperties { [key: string]: any; brightness: Color; contrast: Color; } } export class BrightnessContrastEffect extends OffscreenEffect { static $gtype: GObject.GType<BrightnessContrastEffect>; constructor( properties?: Partial<BrightnessContrastEffect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BrightnessContrastEffect.ConstructorProperties>, ...args: any[] ): void; // Properties brightness: Color; contrast: Color; // Constructors static ['new'](): BrightnessContrastEffect; // Members get_brightness(): [number | null, number | null, number | null]; get_contrast(): [number | null, number | null, number | null]; set_brightness(brightness: number): void; set_brightness_full(red: number, green: number, blue: number): void; set_contrast(contrast: number): void; set_contrast_full(red: number, green: number, blue: number): void; } export namespace Canvas { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; height: number; scale_factor: number; scaleFactor: number; width: number; } } export class Canvas extends GObject.Object implements Content { static $gtype: GObject.GType<Canvas>; constructor( properties?: Partial<Canvas.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Canvas.ConstructorProperties>, ...args: any[] ): void; // Properties height: number; scale_factor: number; scaleFactor: number; width: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'draw', callback: ( _source: this, cr: cairo.Context, width: number, height: number ) => boolean ): number; connect_after( signal: 'draw', callback: ( _source: this, cr: cairo.Context, width: number, height: number ) => boolean ): number; emit( signal: 'draw', cr: cairo.Context, width: number, height: number ): void; // Members get_scale_factor(): number; set_scale_factor(scale: number): void; set_size(width: number, height: number): boolean; vfunc_draw(cr: cairo.Context, width: number, height: number): boolean; static new(): Content; // Implemented Members get_preferred_size(): [boolean, number, number]; invalidate(): void; invalidate_size(): void; vfunc_attached(actor: Actor): void; vfunc_detached(actor: Actor): void; vfunc_get_preferred_size(): [boolean, number, number]; vfunc_invalidate(): void; vfunc_invalidate_size(): void; vfunc_paint_content( actor: Actor, node: PaintNode, paint_context: PaintContext ): void; } export namespace ChildMeta { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; actor: Actor; container: Container; } } export abstract class ChildMeta extends GObject.Object { static $gtype: GObject.GType<ChildMeta>; constructor( properties?: Partial<ChildMeta.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ChildMeta.ConstructorProperties>, ...args: any[] ): void; // Properties actor: Actor; container: Container; // Members get_actor(): Actor; get_container(): Container; } export namespace ClickAction { export interface ConstructorProperties extends Action.ConstructorProperties { [key: string]: any; held: boolean; long_press_duration: number; longPressDuration: number; long_press_threshold: number; longPressThreshold: number; pressed: boolean; } } export class ClickAction extends Action { static $gtype: GObject.GType<ClickAction>; constructor( properties?: Partial<ClickAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ClickAction.ConstructorProperties>, ...args: any[] ): void; // Properties held: boolean; long_press_duration: number; longPressDuration: number; long_press_threshold: number; longPressThreshold: number; pressed: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'clicked', callback: (_source: this, actor: Actor) => void ): number; connect_after( signal: 'clicked', callback: (_source: this, actor: Actor) => void ): number; emit(signal: 'clicked', actor: Actor): void; connect( signal: 'long-press', callback: ( _source: this, actor: Actor, state: LongPressState ) => boolean ): number; connect_after( signal: 'long-press', callback: ( _source: this, actor: Actor, state: LongPressState ) => boolean ): number; emit(signal: 'long-press', actor: Actor, state: LongPressState): void; // Constructors static ['new'](): ClickAction; // Members get_button(): number; get_coords(): [number, number]; get_state(): ModifierType; release(): void; vfunc_clicked(actor: Actor): void; vfunc_long_press(actor: Actor, state: LongPressState): boolean; } export namespace ClipNode { export interface ConstructorProperties extends PaintNode.ConstructorProperties { [key: string]: any; } } export class ClipNode extends PaintNode { static $gtype: GObject.GType<ClipNode>; constructor( properties?: Partial<ClipNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ClipNode.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): ClipNode; } export namespace Clone { export interface ConstructorProperties<A extends Actor = Actor> extends Actor.ConstructorProperties { [key: string]: any; source: A; } } export class Clone<A extends Actor = Actor> extends Actor implements Atk.ImplementorIface, Animatable, Container<A>, Scriptable { static $gtype: GObject.GType<Clone>; constructor( properties?: Partial<Clone.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<Clone.ConstructorProperties<A>>, ...args: any[] ): void; // Properties source: A; // Constructors static ['new'](source: Actor): Clone; static ['new'](...args: never[]): never; // Members get_source(): A; set_source(source?: A | null): void; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace ColorNode { export interface ConstructorProperties extends PipelineNode.ConstructorProperties { [key: string]: any; } } export class ColorNode extends PipelineNode { static $gtype: GObject.GType<ColorNode>; constructor( properties?: Partial<ColorNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ColorNode.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](color?: Color | null): ColorNode; } export namespace ColorizeEffect { export interface ConstructorProperties extends OffscreenEffect.ConstructorProperties { [key: string]: any; tint: Color; } } export class ColorizeEffect extends OffscreenEffect { static $gtype: GObject.GType<ColorizeEffect>; constructor( properties?: Partial<ColorizeEffect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ColorizeEffect.ConstructorProperties>, ...args: any[] ): void; // Properties tint: Color; // Constructors static ['new'](tint: Color): ColorizeEffect; // Members get_tint(): Color; set_tint(tint: Color): void; } export namespace Constraint { export interface ConstructorProperties extends ActorMeta.ConstructorProperties { [key: string]: any; } } export abstract class Constraint extends ActorMeta { static $gtype: GObject.GType<Constraint>; constructor( properties?: Partial<Constraint.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Constraint.ConstructorProperties>, ...args: any[] ): void; // Members update_preferred_size( actor: Actor, direction: Orientation, for_size: number, minimum_size: number, natural_size: number ): [number, number]; vfunc_update_allocation(actor: Actor, allocation: ActorBox): void; vfunc_update_preferred_size( actor: Actor, direction: Orientation, for_size: number, minimum_size: number, natural_size: number ): [number, number]; } export namespace DeformEffect { export interface ConstructorProperties extends OffscreenEffect.ConstructorProperties { [key: string]: any; x_tiles: number; xTiles: number; y_tiles: number; yTiles: number; } } export abstract class DeformEffect extends OffscreenEffect { static $gtype: GObject.GType<DeformEffect>; constructor( properties?: Partial<DeformEffect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DeformEffect.ConstructorProperties>, ...args: any[] ): void; // Properties x_tiles: number; xTiles: number; y_tiles: number; yTiles: number; // Members get_back_material(): Cogl.Handle; get_n_tiles(): [number, number]; invalidate(): void; set_back_material(material?: Cogl.Handle | null): void; set_n_tiles(x_tiles: number, y_tiles: number): void; vfunc_deform_vertex( width: number, height: number, vertex: Cogl.TextureVertex ): void; } export namespace DesaturateEffect { export interface ConstructorProperties extends OffscreenEffect.ConstructorProperties { [key: string]: any; factor: number; } } export class DesaturateEffect extends OffscreenEffect { static $gtype: GObject.GType<DesaturateEffect>; constructor( properties?: Partial<DesaturateEffect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DesaturateEffect.ConstructorProperties>, ...args: any[] ): void; // Properties factor: number; // Constructors static ['new'](factor: number): DesaturateEffect; // Members get_factor(): number; set_factor(factor: number): void; } export namespace Effect { export interface ConstructorProperties extends ActorMeta.ConstructorProperties { [key: string]: any; } } export abstract class Effect extends ActorMeta { static $gtype: GObject.GType<Effect>; constructor( properties?: Partial<Effect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Effect.ConstructorProperties>, ...args: any[] ): void; // Members queue_repaint(): void; vfunc_modify_paint_volume(volume: PaintVolume): boolean; vfunc_paint(paint_context: PaintContext, flags: EffectPaintFlags): void; vfunc_pick(pick_context: PickContext): void; vfunc_post_paint(paint_context: PaintContext): void; vfunc_pre_paint(paint_context: PaintContext): boolean; } export namespace FixedLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; } } export class FixedLayout extends LayoutManager { static $gtype: GObject.GType<FixedLayout>; constructor( properties?: Partial<FixedLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FixedLayout.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): FixedLayout; } export namespace FlowLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; column_spacing: number; columnSpacing: number; homogeneous: boolean; max_column_width: number; maxColumnWidth: number; max_row_height: number; maxRowHeight: number; min_column_width: number; minColumnWidth: number; min_row_height: number; minRowHeight: number; orientation: FlowOrientation; row_spacing: number; rowSpacing: number; snap_to_grid: boolean; snapToGrid: boolean; } } export class FlowLayout extends LayoutManager { static $gtype: GObject.GType<FlowLayout>; constructor( properties?: Partial<FlowLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FlowLayout.ConstructorProperties>, ...args: any[] ): void; // Properties column_spacing: number; columnSpacing: number; homogeneous: boolean; max_column_width: number; maxColumnWidth: number; max_row_height: number; maxRowHeight: number; min_column_width: number; minColumnWidth: number; min_row_height: number; minRowHeight: number; orientation: FlowOrientation; row_spacing: number; rowSpacing: number; snap_to_grid: boolean; snapToGrid: boolean; // Constructors static ['new'](orientation: FlowOrientation): FlowLayout; // Members get_column_spacing(): number; get_column_width(): [number, number]; get_homogeneous(): boolean; get_orientation(): FlowOrientation; get_row_height(): [number, number]; get_row_spacing(): number; get_snap_to_grid(): boolean; set_column_spacing(spacing: number): void; set_column_width(min_width: number, max_width: number): void; set_homogeneous(homogeneous: boolean): void; set_orientation(orientation: FlowOrientation): void; set_row_height(min_height: number, max_height: number): void; set_row_spacing(spacing: number): void; set_snap_to_grid(snap_to_grid: boolean): void; } export namespace FrameClock { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class FrameClock extends GObject.Object { static $gtype: GObject.GType<FrameClock>; constructor( properties?: Partial<FrameClock.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FrameClock.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'destroy', callback: (_source: this) => void): number; connect_after(signal: 'destroy', callback: (_source: this) => void): number; emit(signal: 'destroy'): void; // Constructors static ['new']( refresh_rate: number, iface: FrameListenerIface, user_data?: any | null ): FrameClock; // Members add_timeline(timeline: Timeline): void; destroy(): void; get_refresh_rate(): number; inhibit(): void; remove_timeline(timeline: Timeline): void; schedule_update(): void; schedule_update_now(): void; uninhibit(): void; } export namespace GestureAction { export interface ConstructorProperties extends Action.ConstructorProperties { [key: string]: any; n_touch_points: number; nTouchPoints: number; threshold_trigger_distance_x: number; thresholdTriggerDistanceX: number; threshold_trigger_distance_y: number; thresholdTriggerDistanceY: number; threshold_trigger_edge: GestureTriggerEdge; thresholdTriggerEdge: GestureTriggerEdge; } } export class GestureAction extends Action { static $gtype: GObject.GType<GestureAction>; constructor( properties?: Partial<GestureAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureAction.ConstructorProperties>, ...args: any[] ): void; // Properties n_touch_points: number; nTouchPoints: number; threshold_trigger_distance_x: number; thresholdTriggerDistanceX: number; threshold_trigger_distance_y: number; thresholdTriggerDistanceY: number; threshold_trigger_edge: GestureTriggerEdge; thresholdTriggerEdge: GestureTriggerEdge; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'gesture-begin', callback: (_source: this, actor: Actor) => boolean ): number; connect_after( signal: 'gesture-begin', callback: (_source: this, actor: Actor) => boolean ): number; emit(signal: 'gesture-begin', actor: Actor): void; connect( signal: 'gesture-cancel', callback: (_source: this, actor: Actor) => void ): number; connect_after( signal: 'gesture-cancel', callback: (_source: this, actor: Actor) => void ): number; emit(signal: 'gesture-cancel', actor: Actor): void; connect( signal: 'gesture-end', callback: (_source: this, actor: Actor) => void ): number; connect_after( signal: 'gesture-end', callback: (_source: this, actor: Actor) => void ): number; emit(signal: 'gesture-end', actor: Actor): void; connect( signal: 'gesture-progress', callback: (_source: this, actor: Actor) => boolean ): number; connect_after( signal: 'gesture-progress', callback: (_source: this, actor: Actor) => boolean ): number; emit(signal: 'gesture-progress', actor: Actor): void; // Constructors static ['new'](): GestureAction; // Members cancel(): void; get_device(point: number): InputDevice; get_last_event(point: number): Event; get_motion_coords(point: number): [number | null, number | null]; get_motion_delta(point: number): [number, number | null, number | null]; get_n_current_points(): number; get_n_touch_points(): number; get_press_coords(point: number): [number | null, number | null]; get_release_coords(point: number): [number | null, number | null]; get_sequence(point: number): EventSequence; get_threshold_trigger_distance(): [number | null, number | null]; get_threshold_trigger_edge(): GestureTriggerEdge; get_threshold_trigger_egde(): GestureTriggerEdge; get_velocity(point: number): [number, number | null, number | null]; set_n_touch_points(nb_points: number): void; set_threshold_trigger_distance(x: number, y: number): void; set_threshold_trigger_edge(edge: GestureTriggerEdge): void; vfunc_gesture_begin(actor: Actor): boolean; vfunc_gesture_cancel(actor: Actor): void; vfunc_gesture_end(actor: Actor): void; vfunc_gesture_prepare(actor: Actor): boolean; vfunc_gesture_progress(actor: Actor): boolean; } export namespace GridLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; column_homogeneous: boolean; columnHomogeneous: boolean; column_spacing: number; columnSpacing: number; orientation: Orientation; row_homogeneous: boolean; rowHomogeneous: boolean; row_spacing: number; rowSpacing: number; } } export class GridLayout extends LayoutManager { static $gtype: GObject.GType<GridLayout>; constructor( properties?: Partial<GridLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GridLayout.ConstructorProperties>, ...args: any[] ): void; // Properties column_homogeneous: boolean; columnHomogeneous: boolean; column_spacing: number; columnSpacing: number; orientation: Orientation; row_homogeneous: boolean; rowHomogeneous: boolean; row_spacing: number; rowSpacing: number; // Constructors static ['new'](): GridLayout; // Members attach( child: Actor, left: number, top: number, width: number, height: number ): void; attach_next_to( child: Actor, sibling: Actor | null, side: GridPosition, width: number, height: number ): void; get_child_at(left: number, top: number): Actor; get_column_homogeneous(): boolean; get_column_spacing(): number; get_orientation(): Orientation; get_row_homogeneous(): boolean; get_row_spacing(): number; insert_column(position: number): void; insert_next_to(sibling: Actor, side: GridPosition): void; insert_row(position: number): void; set_column_homogeneous(homogeneous: boolean): void; set_column_spacing(spacing: number): void; set_orientation(orientation: Orientation): void; set_row_homogeneous(homogeneous: boolean): void; set_row_spacing(spacing: number): void; } export namespace Image { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Image extends GObject.Object implements Content { static $gtype: GObject.GType<Image>; constructor( properties?: Partial<Image.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Image.ConstructorProperties>, ...args: any[] ): void; // Members get_texture(): Cogl.Texture; set_area( data: Uint8Array | string, pixel_format: Cogl.PixelFormat, rect: cairo.RectangleInt, row_stride: number ): boolean; set_bytes( data: GLib.Bytes | Uint8Array, pixel_format: Cogl.PixelFormat, width: number, height: number, row_stride: number ): boolean; set_data( data: Uint8Array | string, pixel_format: Cogl.PixelFormat, width: number, height: number, row_stride: number ): boolean; set_data(...args: never[]): never; static new(): Content; // Implemented Members get_preferred_size(): [boolean, number, number]; invalidate(): void; invalidate_size(): void; vfunc_attached(actor: Actor): void; vfunc_detached(actor: Actor): void; vfunc_get_preferred_size(): [boolean, number, number]; vfunc_invalidate(): void; vfunc_invalidate_size(): void; vfunc_paint_content( actor: Actor, node: PaintNode, paint_context: PaintContext ): void; } export namespace InputDevice { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; backend: Backend; device_mode: InputMode; deviceMode: InputMode; device_node: string; deviceNode: string; device_type: InputDeviceType; deviceType: InputDeviceType; enabled: boolean; has_cursor: boolean; hasCursor: boolean; id: number; mapping_mode: InputDeviceMapping; mappingMode: InputDeviceMapping; n_axes: number; nAxes: number; n_mode_groups: number; nModeGroups: number; n_rings: number; nRings: number; n_strips: number; nStrips: number; name: string; product_id: string; productId: string; seat: Seat; vendor_id: string; vendorId: string; } } export class InputDevice extends GObject.Object { static $gtype: GObject.GType<InputDevice>; constructor( properties?: Partial<InputDevice.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<InputDevice.ConstructorProperties>, ...args: any[] ): void; // Properties backend: Backend; device_mode: InputMode; deviceMode: InputMode; device_node: string; deviceNode: string; device_type: InputDeviceType; deviceType: InputDeviceType; enabled: boolean; has_cursor: boolean; hasCursor: boolean; id: number; mapping_mode: InputDeviceMapping; mappingMode: InputDeviceMapping; n_axes: number; nAxes: number; n_mode_groups: number; nModeGroups: number; n_rings: number; nRings: number; n_strips: number; nStrips: number; name: string; product_id: string; productId: string; seat: Seat; vendor_id: string; vendorId: string; // Members get_actor(sequence?: EventSequence | null): Actor; get_associated_device(): InputDevice; get_axis(index_: number): InputAxis; get_axis_value(axes: number[], axis: InputAxis): [boolean, number]; get_coords(sequence: EventSequence | null): [boolean, Graphene.Point]; get_device_id(): number; get_device_mode(): InputMode; get_device_name(): string; get_device_node(): string; get_device_type(): InputDeviceType; get_enabled(): boolean; get_grabbed_actor(): Actor; get_group_n_modes(group: number): number; get_has_cursor(): boolean; get_key(index_: number): [boolean, number, ModifierType]; get_mapping_mode(): InputDeviceMapping; get_mode_switch_button_group(button: number): number; get_modifier_state(): ModifierType; get_n_axes(): number; get_n_keys(): number; get_n_mode_groups(): number; get_n_rings(): number; get_n_strips(): number; get_physical_devices(): InputDevice[]; get_pointer_stage(): Stage; get_product_id(): string; get_seat(): Seat; get_vendor_id(): string; grab(actor: Actor): void; is_grouped(other_device: InputDevice): boolean; is_mode_switch_button(group: number, button: number): boolean; keycode_to_evdev(hardware_keycode: number, evdev_keycode: number): boolean; sequence_get_grabbed_actor(sequence: EventSequence): Actor; sequence_grab(sequence: EventSequence, actor: Actor): void; sequence_ungrab(sequence: EventSequence): void; set_enabled(enabled: boolean): void; set_key(index_: number, keyval: number, modifiers: ModifierType): void; set_mapping_mode(mapping: InputDeviceMapping): void; ungrab(): void; update_from_event(event: Event, update_stage: boolean): void; vfunc_get_group_n_modes(group: number): number; vfunc_is_grouped(other_device: InputDevice): boolean; vfunc_is_mode_switch_button(group: number, button: number): boolean; vfunc_keycode_to_evdev( hardware_keycode: number, evdev_keycode: number ): boolean; vfunc_update_from_tool(tool: InputDeviceTool): void; } export namespace InputDeviceTool { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; id: number; serial: number; type: InputDeviceToolType; } } export abstract class InputDeviceTool extends GObject.Object { static $gtype: GObject.GType<InputDeviceTool>; constructor( properties?: Partial<InputDeviceTool.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<InputDeviceTool.ConstructorProperties>, ...args: any[] ): void; // Properties id: number; serial: number; type: InputDeviceToolType; // Members get_id(): number; get_serial(): number; get_tool_type(): InputDeviceToolType; } export namespace InputFocus { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class InputFocus extends GObject.Object { static $gtype: GObject.GType<InputFocus>; constructor( properties?: Partial<InputFocus.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<InputFocus.ConstructorProperties>, ...args: any[] ): void; // Members filter_event(event: Event): boolean; is_focused(): boolean; reset(): void; set_can_show_preedit(can_show_preedit: boolean): void; set_content_hints(hint: InputContentHintFlags): void; set_content_purpose(purpose: InputContentPurpose): void; set_cursor_location(rect: Graphene.Rect): void; set_input_panel_state(state: InputPanelState): void; set_surrounding(text: string, cursor: number, anchor: number): void; vfunc_commit_text(text: string): void; vfunc_delete_surrounding(offset: number, len: number): void; vfunc_focus_in(input_method: InputMethod): void; vfunc_focus_out(): void; vfunc_request_surrounding(): void; vfunc_set_preedit_text(preedit: string, cursor: number): void; } export namespace InputMethod { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; can_show_preedit: boolean; canShowPreedit: boolean; content_hints: InputContentHintFlags; contentHints: InputContentHintFlags; content_purpose: InputContentPurpose; contentPurpose: InputContentPurpose; } } export abstract class InputMethod extends GObject.Object { static $gtype: GObject.GType<InputMethod>; constructor( properties?: Partial<InputMethod.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<InputMethod.ConstructorProperties>, ...args: any[] ): void; // Properties can_show_preedit: boolean; canShowPreedit: boolean; content_hints: InputContentHintFlags; contentHints: InputContentHintFlags; content_purpose: InputContentPurpose; contentPurpose: InputContentPurpose; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'commit', callback: (_source: this, object: string) => void ): number; connect_after( signal: 'commit', callback: (_source: this, object: string) => void ): number; emit(signal: 'commit', object: string): void; connect( signal: 'cursor-location-changed', callback: (_source: this, object: Graphene.Rect) => void ): number; connect_after( signal: 'cursor-location-changed', callback: (_source: this, object: Graphene.Rect) => void ): number; emit(signal: 'cursor-location-changed', object: Graphene.Rect): void; connect( signal: 'delete-surrounding', callback: (_source: this, object: number, p0: number) => void ): number; connect_after( signal: 'delete-surrounding', callback: (_source: this, object: number, p0: number) => void ): number; emit(signal: 'delete-surrounding', object: number, p0: number): void; connect( signal: 'input-panel-state', callback: (_source: this, object: InputPanelState) => void ): number; connect_after( signal: 'input-panel-state', callback: (_source: this, object: InputPanelState) => void ): number; emit(signal: 'input-panel-state', object: InputPanelState): void; connect( signal: 'request-surrounding', callback: (_source: this) => void ): number; connect_after( signal: 'request-surrounding', callback: (_source: this) => void ): number; emit(signal: 'request-surrounding'): void; // Members commit(text: string): void; delete_surrounding(offset: number, len: number): void; focus_in(focus: InputFocus): void; focus_out(): void; forward_key( keyval: number, keycode: number, state: number, time_: number, press: boolean ): void; notify_key_event(event: Event, filtered: boolean): void; request_surrounding(): void; set_input_panel_state(state: InputPanelState): void; set_preedit_text(preedit: string | null, cursor: number): void; vfunc_filter_key_event(key: Event): boolean; vfunc_focus_in(actor: InputFocus): void; vfunc_focus_out(): void; vfunc_reset(): void; vfunc_set_cursor_location(rect: Graphene.Rect): void; vfunc_set_surrounding(text: string, cursor: number, anchor: number): void; vfunc_update_content_hints(hint: InputContentHintFlags): void; vfunc_update_content_purpose(purpose: InputContentPurpose): void; } export namespace Interval { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; final: GObject.Value; initial: GObject.Value; value_type: GObject.GType; valueType: GObject.GType; } } export class Interval extends GObject.InitiallyUnowned implements Scriptable { static $gtype: GObject.GType<Interval>; constructor( properties?: Partial<Interval.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Interval.ConstructorProperties>, ...args: any[] ): void; // Properties 'final': GObject.Value; initial: GObject.Value; value_type: GObject.GType; valueType: GObject.GType; // Constructors static new_with_values( gtype: GObject.GType, initial?: GObject.Value | null, _final?: GObject.Value | null ): Interval; // Members clone(): Interval; compute(factor: number): unknown; compute_value(factor: number): [boolean, unknown]; get_final_value(): unknown; get_initial_value(): unknown; get_value_type(): GObject.GType; is_valid(): boolean; peek_final_value(): unknown; peek_initial_value(): unknown; set_final(value: any): void; set_initial(value: any): void; validate(pspec: GObject.ParamSpec): boolean; vfunc_compute_value(factor: number): [boolean, unknown]; vfunc_validate(pspec: GObject.ParamSpec): boolean; // Implemented Members get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace KeyframeTransition { export interface ConstructorProperties extends PropertyTransition.ConstructorProperties { [key: string]: any; } } export class KeyframeTransition extends PropertyTransition implements Scriptable { static $gtype: GObject.GType<KeyframeTransition>; constructor( properties?: Partial<KeyframeTransition.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<KeyframeTransition.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](property_name: string): KeyframeTransition; static ['new'](...args: never[]): never; // Members clear(): void; get_key_frame( index_: number ): [number | null, AnimationMode | null, unknown]; get_n_key_frames(): number; set_key_frame( index_: number, key: number, mode: AnimationMode, value: any ): void; set_key_frames(key_frames: number[]): void; set_modes(modes: AnimationMode[]): void; set_values(values: GObject.Value[]): void; // Implemented Members get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace Keymap { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class Keymap extends GObject.Object { static $gtype: GObject.GType<Keymap>; constructor( properties?: Partial<Keymap.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Keymap.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'state-changed', callback: (_source: this) => void): number; connect_after( signal: 'state-changed', callback: (_source: this) => void ): number; emit(signal: 'state-changed'): void; // Members get_caps_lock_state(): boolean; get_direction(): Pango.Direction; get_num_lock_state(): boolean; vfunc_get_caps_lock_state(): boolean; vfunc_get_direction(): Pango.Direction; vfunc_get_num_lock_state(): boolean; } export namespace LayerNode { export interface ConstructorProperties extends PaintNode.ConstructorProperties { [key: string]: any; } } export class LayerNode extends PaintNode { static $gtype: GObject.GType<LayerNode>; constructor( properties?: Partial<LayerNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LayerNode.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( projection: Cogl.Matrix, viewport: cairo.Rectangle, width: number, height: number, opacity: number ): LayerNode; } export namespace LayoutManager { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; } } export abstract class LayoutManager extends GObject.InitiallyUnowned { static $gtype: GObject.GType<LayoutManager>; constructor( properties?: Partial<LayoutManager.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LayoutManager.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'layout-changed', callback: (_source: this) => void ): number; connect_after( signal: 'layout-changed', callback: (_source: this) => void ): number; emit(signal: 'layout-changed'): void; // Members allocate(container: Container, allocation: ActorBox): void; child_get_property( container: Container, actor: Actor, property_name: string, value: any ): void; child_set_property( container: Container, actor: Actor, property_name: string, value: any ): void; find_child_property(name: string): GObject.ParamSpec; get_child_meta(container: Container, actor: Actor): LayoutMeta; get_preferred_height( container: Container, for_width: number ): [number | null, number | null]; get_preferred_width( container: Container, for_height: number ): [number | null, number | null]; layout_changed(): void; list_child_properties(): GObject.ParamSpec[]; set_container(container?: Container | null): void; vfunc_allocate(container: Container, allocation: ActorBox): void; vfunc_get_child_meta_type(): GObject.GType; vfunc_get_preferred_height( container: Container, for_width: number ): [number | null, number | null]; vfunc_get_preferred_width( container: Container, for_height: number ): [number | null, number | null]; vfunc_layout_changed(): void; vfunc_set_container(container?: Container | null): void; } export namespace LayoutMeta { export interface ConstructorProperties extends ChildMeta.ConstructorProperties { [key: string]: any; manager: LayoutManager; } } export abstract class LayoutMeta extends ChildMeta { static $gtype: GObject.GType<LayoutMeta>; constructor( properties?: Partial<LayoutMeta.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LayoutMeta.ConstructorProperties>, ...args: any[] ): void; // Properties manager: LayoutManager; // Members get_manager(): LayoutManager; } export namespace OffscreenEffect { export interface ConstructorProperties extends Effect.ConstructorProperties { [key: string]: any; } } export abstract class OffscreenEffect extends Effect { static $gtype: GObject.GType<OffscreenEffect>; constructor( properties?: Partial<OffscreenEffect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<OffscreenEffect.ConstructorProperties>, ...args: any[] ): void; // Members create_texture(width: number, height: number): Cogl.Handle; get_target_rect(): [boolean, Graphene.Rect]; get_target_size(): [boolean, number, number]; get_texture(): Cogl.Handle; paint_target(paint_context: PaintContext): void; vfunc_create_texture(width: number, height: number): Cogl.Handle; vfunc_paint_target(paint_context: PaintContext): void; } export namespace PageTurnEffect { export interface ConstructorProperties extends DeformEffect.ConstructorProperties { [key: string]: any; angle: number; period: number; radius: number; } } export class PageTurnEffect extends DeformEffect { static $gtype: GObject.GType<PageTurnEffect>; constructor( properties?: Partial<PageTurnEffect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PageTurnEffect.ConstructorProperties>, ...args: any[] ): void; // Properties angle: number; period: number; radius: number; // Constructors static ['new']( period: number, angle: number, radius: number ): PageTurnEffect; // Members get_angle(): number; get_period(): number; get_radius(): number; set_angle(angle: number): void; set_period(period: number): void; set_radius(radius: number): void; } export namespace PaintNode { export interface ConstructorProperties { [key: string]: any; } } export abstract class PaintNode { static $gtype: GObject.GType<PaintNode>; constructor( properties?: Partial<PaintNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PaintNode.ConstructorProperties>, ...args: any[] ): void; // Members add_child(child: PaintNode): void; add_multitexture_rectangle( rect: ActorBox, text_coords: number, text_coords_len: number ): void; add_rectangle(rect: ActorBox): void; add_texture_rectangle( rect: ActorBox, x_1: number, y_1: number, x_2: number, y_2: number ): void; get_framebuffer(): Cogl.Framebuffer; paint(paint_context: PaintContext): void; ref(): PaintNode; set_name(name: string): void; unref(): void; } export namespace PanAction { export interface ConstructorProperties extends GestureAction.ConstructorProperties { [key: string]: any; acceleration_factor: number; accelerationFactor: number; deceleration: number; interpolate: boolean; pan_axis: PanAxis; panAxis: PanAxis; } } export class PanAction extends GestureAction { static $gtype: GObject.GType<PanAction>; constructor( properties?: Partial<PanAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PanAction.ConstructorProperties>, ...args: any[] ): void; // Properties acceleration_factor: number; accelerationFactor: number; deceleration: number; interpolate: boolean; pan_axis: PanAxis; panAxis: PanAxis; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'pan', callback: ( _source: this, actor: Actor, is_interpolated: boolean ) => boolean ): number; connect_after( signal: 'pan', callback: ( _source: this, actor: Actor, is_interpolated: boolean ) => boolean ): number; emit(signal: 'pan', actor: Actor, is_interpolated: boolean): void; connect( signal: 'pan-stopped', callback: (_source: this, actor: Actor) => void ): number; connect_after( signal: 'pan-stopped', callback: (_source: this, actor: Actor) => void ): number; emit(signal: 'pan-stopped', actor: Actor): void; // Constructors static ['new'](): PanAction; // Members get_acceleration_factor(): number; get_constrained_motion_delta( point: number ): [number, number | null, number | null]; get_deceleration(): number; get_interpolate(): boolean; get_interpolated_coords(): [number | null, number | null]; get_interpolated_delta(): [number, number | null, number | null]; get_motion_coords(point: number): [number | null, number | null]; get_motion_delta(point: number): [number, number | null, number | null]; get_pan_axis(): PanAxis; set_acceleration_factor(factor: number): void; set_deceleration(rate: number): void; set_interpolate(should_interpolate: boolean): void; set_pan_axis(axis: PanAxis): void; vfunc_pan(actor: Actor, is_interpolated: boolean): boolean; vfunc_pan_stopped(actor: Actor): void; } export namespace ParamSpecUnit { export interface ConstructorProperties extends GObject.ParamSpec.ConstructorProperties { [key: string]: any; } } export class ParamSpecUnit extends GObject.ParamSpec { static $gtype: GObject.GType<ParamSpecUnit>; constructor( properties?: Partial<ParamSpecUnit.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ParamSpecUnit.ConstructorProperties>, ...args: any[] ): void; } export namespace Path { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; description: string; length: number; } } export class Path extends GObject.InitiallyUnowned { static $gtype: GObject.GType<Path>; constructor( properties?: Partial<Path.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Path.ConstructorProperties>, ...args: any[] ): void; // Properties description: string; length: number; // Constructors static ['new'](): Path; static new_with_description(desc: string): Path; // Members add_cairo_path(cpath: cairo.Path): void; add_close(): void; add_curve_to( x_1: number, y_1: number, x_2: number, y_2: number, x_3: number, y_3: number ): void; add_line_to(x: number, y: number): void; add_move_to(x: number, y: number): void; add_node(node: PathNode): void; add_rel_curve_to( x_1: number, y_1: number, x_2: number, y_2: number, x_3: number, y_3: number ): void; add_rel_line_to(x: number, y: number): void; add_rel_move_to(x: number, y: number): void; add_string(str: string): boolean; clear(): void; foreach(callback: PathCallback): void; get_description(): string; get_length(): number; get_n_nodes(): number; get_node(index_: number): PathNode; get_nodes(): PathNode[]; get_position(progress: number): [number, Knot]; insert_node(index_: number, node: PathNode): void; remove_node(index_: number): void; replace_node(index_: number, node: PathNode): void; set_description(str: string): boolean; to_cairo_path(cr: cairo.Context): void; } export namespace PathConstraint { export interface ConstructorProperties extends Constraint.ConstructorProperties { [key: string]: any; offset: number; path: Path; } } export class PathConstraint extends Constraint { static $gtype: GObject.GType<PathConstraint>; constructor( properties?: Partial<PathConstraint.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PathConstraint.ConstructorProperties>, ...args: any[] ): void; // Properties offset: number; path: Path; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'node-reached', callback: (_source: this, actor: Actor, index: number) => void ): number; connect_after( signal: 'node-reached', callback: (_source: this, actor: Actor, index: number) => void ): number; emit(signal: 'node-reached', actor: Actor, index: number): void; // Constructors static ['new'](path: Path | null, offset: number): PathConstraint; // Members get_offset(): number; get_path(): Path; set_offset(offset: number): void; set_path(path?: Path | null): void; } export namespace PipelineNode { export interface ConstructorProperties extends PaintNode.ConstructorProperties { [key: string]: any; } } export class PipelineNode extends PaintNode { static $gtype: GObject.GType<PipelineNode>; constructor( properties?: Partial<PipelineNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PipelineNode.ConstructorProperties>, ...args: any[] ): void; } export namespace PropertyTransition { export interface ConstructorProperties extends Transition.ConstructorProperties { [key: string]: any; property_name: string; propertyName: string; } } export class PropertyTransition extends Transition implements Scriptable { static $gtype: GObject.GType<PropertyTransition>; constructor( properties?: Partial<PropertyTransition.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PropertyTransition.ConstructorProperties>, ...args: any[] ): void; // Properties property_name: string; propertyName: string; // Constructors static ['new'](property_name?: string | null): PropertyTransition; static ['new'](...args: never[]): never; static new_for_actor( actor: Actor, property_name?: string | null ): PropertyTransition; static new_for_actor(...args: never[]): never; // Members get_property_name(): string; set_property_name(property_name?: string | null): void; // Implemented Members get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace RootNode { export interface ConstructorProperties extends PaintNode.ConstructorProperties { [key: string]: any; } } export class RootNode extends PaintNode { static $gtype: GObject.GType<RootNode>; constructor( properties?: Partial<RootNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<RootNode.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( framebuffer: Cogl.Framebuffer, clear_color: Color, clear_flags: Cogl.BufferBit ): RootNode; } export namespace RotateAction { export interface ConstructorProperties extends GestureAction.ConstructorProperties { [key: string]: any; } } export class RotateAction extends GestureAction { static $gtype: GObject.GType<RotateAction>; constructor( properties?: Partial<RotateAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<RotateAction.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'rotate', callback: (_source: this, actor: Actor, angle: number) => boolean ): number; connect_after( signal: 'rotate', callback: (_source: this, actor: Actor, angle: number) => boolean ): number; emit(signal: 'rotate', actor: Actor, angle: number): void; // Constructors static ['new'](): RotateAction; // Members vfunc_rotate(actor: Actor, angle: number): boolean; } export namespace Script { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; filename: string; filename_set: boolean; filenameSet: boolean; translation_domain: string; translationDomain: string; } } export class Script extends GObject.Object { static $gtype: GObject.GType<Script>; constructor( properties?: Partial<Script.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Script.ConstructorProperties>, ...args: any[] ): void; // Properties filename: string; filename_set: boolean; filenameSet: boolean; translation_domain: string; translationDomain: string; // Constructors static ['new'](): Script; // Members add_search_paths(paths: string[]): void; connect_signals(user_data?: any | null): void; connect_signals_full(func: ScriptConnectFunc): void; ensure_objects(): void; get_object<T = GObject.Object>(name: string): T; get_translation_domain(): string; get_type_from_name(type_name: string): GObject.GType; list_objects(): GObject.Object[]; load_from_data(data: string, length: number): number; load_from_file(filename: string): number; load_from_resource(resource_path: string): number; lookup_filename(filename: string): string; set_translation_domain(domain?: string | null): void; unmerge_objects(merge_id: number): void; vfunc_get_type_from_name(type_name: string): GObject.GType; } export namespace ScrollActor { export interface ConstructorProperties<A extends Actor = Actor> extends Actor.ConstructorProperties { [key: string]: any; scroll_mode: ScrollMode; scrollMode: ScrollMode; } } export class ScrollActor<A extends Actor = Actor> extends Actor implements Atk.ImplementorIface, Animatable, Container<A>, Scriptable { static $gtype: GObject.GType<ScrollActor>; constructor( properties?: Partial<ScrollActor.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<ScrollActor.ConstructorProperties<A>>, ...args: any[] ): void; // Properties scroll_mode: ScrollMode; scrollMode: ScrollMode; // Constructors static ['new'](): ScrollActor; // Members get_scroll_mode(): ScrollMode; scroll_to_point(point: Graphene.Point): void; scroll_to_rect(rect: Graphene.Rect): void; set_scroll_mode(mode: ScrollMode): void; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace Seat { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; backend: Backend; touch_mode: boolean; touchMode: boolean; } } export abstract class Seat extends GObject.Object { static $gtype: GObject.GType<Seat>; constructor( properties?: Partial<Seat.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Seat.ConstructorProperties>, ...args: any[] ): void; // Properties backend: Backend; touch_mode: boolean; touchMode: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'device-added', callback: (_source: this, object: InputDevice) => void ): number; connect_after( signal: 'device-added', callback: (_source: this, object: InputDevice) => void ): number; emit(signal: 'device-added', object: InputDevice): void; connect( signal: 'device-removed', callback: (_source: this, object: InputDevice) => void ): number; connect_after( signal: 'device-removed', callback: (_source: this, object: InputDevice) => void ): number; emit(signal: 'device-removed', object: InputDevice): void; connect( signal: 'is-unfocus-inhibited-changed', callback: (_source: this) => void ): number; connect_after( signal: 'is-unfocus-inhibited-changed', callback: (_source: this) => void ): number; emit(signal: 'is-unfocus-inhibited-changed'): void; connect( signal: 'kbd-a11y-flags-changed', callback: ( _source: this, settings_flags: number, changed_mask: number ) => void ): number; connect_after( signal: 'kbd-a11y-flags-changed', callback: ( _source: this, settings_flags: number, changed_mask: number ) => void ): number; emit( signal: 'kbd-a11y-flags-changed', settings_flags: number, changed_mask: number ): void; connect( signal: 'kbd-a11y-mods-state-changed', callback: ( _source: this, latched_mask: number, locked_mask: number ) => void ): number; connect_after( signal: 'kbd-a11y-mods-state-changed', callback: ( _source: this, latched_mask: number, locked_mask: number ) => void ): number; emit( signal: 'kbd-a11y-mods-state-changed', latched_mask: number, locked_mask: number ): void; connect( signal: 'ptr-a11y-dwell-click-type-changed', callback: (_source: this, click_type: PointerA11yDwellClickType) => void ): number; connect_after( signal: 'ptr-a11y-dwell-click-type-changed', callback: (_source: this, click_type: PointerA11yDwellClickType) => void ): number; emit( signal: 'ptr-a11y-dwell-click-type-changed', click_type: PointerA11yDwellClickType ): void; connect( signal: 'ptr-a11y-timeout-started', callback: ( _source: this, device: InputDevice, timeout_type: PointerA11yTimeoutType, delay: number ) => void ): number; connect_after( signal: 'ptr-a11y-timeout-started', callback: ( _source: this, device: InputDevice, timeout_type: PointerA11yTimeoutType, delay: number ) => void ): number; emit( signal: 'ptr-a11y-timeout-started', device: InputDevice, timeout_type: PointerA11yTimeoutType, delay: number ): void; connect( signal: 'ptr-a11y-timeout-stopped', callback: ( _source: this, device: InputDevice, timeout_type: PointerA11yTimeoutType, clicked: boolean ) => void ): number; connect_after( signal: 'ptr-a11y-timeout-stopped', callback: ( _source: this, device: InputDevice, timeout_type: PointerA11yTimeoutType, clicked: boolean ) => void ): number; emit( signal: 'ptr-a11y-timeout-stopped', device: InputDevice, timeout_type: PointerA11yTimeoutType, clicked: boolean ): void; connect( signal: 'tool-changed', callback: ( _source: this, object: InputDevice, p0: InputDeviceTool ) => void ): number; connect_after( signal: 'tool-changed', callback: ( _source: this, object: InputDevice, p0: InputDeviceTool ) => void ): number; emit( signal: 'tool-changed', object: InputDevice, p0: InputDeviceTool ): void; // Members bell_notify(): void; compress_motion(event: Event, to_discard: Event): void; create_virtual_device(device_type: InputDeviceType): VirtualInputDevice; ensure_a11y_state(): void; get_kbd_a11y_settings(settings: KbdA11ySettings): void; get_keyboard(): InputDevice; get_keymap(): Keymap; get_pointer(): InputDevice; get_pointer_a11y_settings(settings: PointerA11ySettings): void; get_touch_mode(): boolean; handle_device_event(event: Event): boolean; inhibit_unfocus(): void; is_unfocus_inhibited(): boolean; list_devices(): InputDevice[]; set_kbd_a11y_settings(settings: KbdA11ySettings): void; set_pointer_a11y_dwell_click_type( click_type: PointerA11yDwellClickType ): void; set_pointer_a11y_settings(settings: PointerA11ySettings): void; uninhibit_unfocus(): void; warp_pointer(x: number, y: number): void; vfunc_apply_kbd_a11y_settings(settings: KbdA11ySettings): void; vfunc_bell_notify(): void; vfunc_compress_motion(event: Event, to_discard: Event): void; vfunc_copy_event_data(src: Event, dest: Event): void; vfunc_create_virtual_device( device_type: InputDeviceType ): VirtualInputDevice; vfunc_free_event_data(event: Event): void; vfunc_get_keyboard(): InputDevice; vfunc_get_keymap(): Keymap; vfunc_get_pointer(): InputDevice; vfunc_handle_device_event(event: Event): boolean; vfunc_warp_pointer(x: number, y: number): void; } export namespace Settings { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; backend: Backend; dnd_drag_threshold: number; dndDragThreshold: number; double_click_distance: number; doubleClickDistance: number; double_click_time: number; doubleClickTime: number; font_antialias: number; fontAntialias: number; font_dpi: number; fontDpi: number; font_hint_style: string; fontHintStyle: string; font_hinting: number; fontHinting: number; font_name: string; fontName: string; font_subpixel_order: string; fontSubpixelOrder: string; fontconfig_timestamp: number; fontconfigTimestamp: number; long_press_duration: number; longPressDuration: number; password_hint_time: number; passwordHintTime: number; unscaled_font_dpi: number; unscaledFontDpi: number; } } export class Settings extends GObject.Object { static $gtype: GObject.GType<Settings>; constructor( properties?: Partial<Settings.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Settings.ConstructorProperties>, ...args: any[] ): void; // Properties backend: Backend; dnd_drag_threshold: number; dndDragThreshold: number; double_click_distance: number; doubleClickDistance: number; double_click_time: number; doubleClickTime: number; font_antialias: number; fontAntialias: number; font_dpi: number; fontDpi: number; font_hint_style: string; fontHintStyle: string; font_hinting: number; fontHinting: number; font_name: string; fontName: string; font_subpixel_order: string; fontSubpixelOrder: string; fontconfig_timestamp: number; fontconfigTimestamp: number; long_press_duration: number; longPressDuration: number; password_hint_time: number; passwordHintTime: number; unscaled_font_dpi: number; unscaledFontDpi: number; // Members static get_default(): Settings; } export namespace ShaderEffect { export interface ConstructorProperties extends OffscreenEffect.ConstructorProperties { [key: string]: any; shader_type: ShaderType; shaderType: ShaderType; } } export class ShaderEffect extends OffscreenEffect { static $gtype: GObject.GType<ShaderEffect>; constructor( properties?: Partial<ShaderEffect.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShaderEffect.ConstructorProperties>, ...args: any[] ): void; // Properties shader_type: ShaderType; shaderType: ShaderType; // Constructors static ['new'](shader_type: ShaderType): ShaderEffect; // Members get_program(): Cogl.Handle; get_shader(): Cogl.Handle; set_shader_source(source: string): boolean; set_uniform_value(name: string, value: any): void; vfunc_get_static_shader_source(): string; } export namespace ShaderFloat { export interface ConstructorProperties { [key: string]: any; } } export class ShaderFloat { static $gtype: GObject.GType<ShaderFloat>; constructor( properties?: Partial<ShaderFloat.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShaderFloat.ConstructorProperties>, ...args: any[] ): void; } export namespace ShaderInt { export interface ConstructorProperties { [key: string]: any; } } export class ShaderInt { static $gtype: GObject.GType<ShaderInt>; constructor( properties?: Partial<ShaderInt.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShaderInt.ConstructorProperties>, ...args: any[] ): void; } export namespace ShaderMatrix { export interface ConstructorProperties { [key: string]: any; } } export class ShaderMatrix { static $gtype: GObject.GType<ShaderMatrix>; constructor( properties?: Partial<ShaderMatrix.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShaderMatrix.ConstructorProperties>, ...args: any[] ): void; } export namespace SnapConstraint { export interface ConstructorProperties extends Constraint.ConstructorProperties { [key: string]: any; from_edge: SnapEdge; fromEdge: SnapEdge; offset: number; source: Actor; to_edge: SnapEdge; toEdge: SnapEdge; } } export class SnapConstraint extends Constraint { static $gtype: GObject.GType<SnapConstraint>; constructor( properties?: Partial<SnapConstraint.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SnapConstraint.ConstructorProperties>, ...args: any[] ): void; // Properties from_edge: SnapEdge; fromEdge: SnapEdge; offset: number; source: Actor; to_edge: SnapEdge; toEdge: SnapEdge; // Constructors static ['new']( source: Actor | null, from_edge: SnapEdge, to_edge: SnapEdge, offset: number ): SnapConstraint; // Members get_edges(): [SnapEdge, SnapEdge]; get_offset(): number; get_source(): Actor; set_edges(from_edge: SnapEdge, to_edge: SnapEdge): void; set_offset(offset: number): void; set_source(source?: Actor | null): void; } export namespace Stage { export interface ConstructorProperties<A extends Actor = Actor> extends Actor.ConstructorProperties { [key: string]: any; key_focus: Actor; keyFocus: Actor; perspective: Perspective; title: string; } } export class Stage<A extends Actor = Actor> extends Actor implements Atk.ImplementorIface, Animatable, Container<A>, Scriptable { static $gtype: GObject.GType<Stage>; constructor( properties?: Partial<Stage.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<Stage.ConstructorProperties<A>>, ...args: any[] ): void; // Properties key_focus: Actor; keyFocus: Actor; perspective: Perspective; title: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; connect( signal: 'after-paint', callback: (_source: this, view: StageView) => void ): number; connect_after( signal: 'after-paint', callback: (_source: this, view: StageView) => void ): number; emit(signal: 'after-paint', view: StageView): void; connect( signal: 'after-update', callback: (_source: this, view: StageView) => void ): number; connect_after( signal: 'after-update', callback: (_source: this, view: StageView) => void ): number; emit(signal: 'after-update', view: StageView): void; connect( signal: 'before-paint', callback: (_source: this, view: StageView) => void ): number; connect_after( signal: 'before-paint', callback: (_source: this, view: StageView) => void ): number; emit(signal: 'before-paint', view: StageView): void; connect( signal: 'before-update', callback: (_source: this, view: StageView) => void ): number; connect_after( signal: 'before-update', callback: (_source: this, view: StageView) => void ): number; emit(signal: 'before-update', view: StageView): void; connect(signal: 'deactivate', callback: (_source: this) => void): number; connect_after( signal: 'deactivate', callback: (_source: this) => void ): number; emit(signal: 'deactivate'): void; connect( signal: 'gl-video-memory-purged', callback: (_source: this) => void ): number; connect_after( signal: 'gl-video-memory-purged', callback: (_source: this) => void ): number; emit(signal: 'gl-video-memory-purged'): void; connect( signal: 'paint-view', callback: ( _source: this, view: StageView, redraw_clip: cairo.Region ) => void ): number; connect_after( signal: 'paint-view', callback: ( _source: this, view: StageView, redraw_clip: cairo.Region ) => void ): number; emit( signal: 'paint-view', view: StageView, redraw_clip: cairo.Region ): void; connect( signal: 'presented', callback: ( _source: this, view: StageView, frame_info: any | null ) => void ): number; connect_after( signal: 'presented', callback: ( _source: this, view: StageView, frame_info: any | null ) => void ): number; emit(signal: 'presented', view: StageView, frame_info: any | null): void; // Members capture_into(paint: boolean, rect: cairo.RectangleInt, data: number): void; clear_stage_views(): void; ensure_viewport(): void; event(event: Event): boolean; event(...args: never[]): never; get_actor_at_pos(pick_mode: PickMode, x: number, y: number): Actor; get_capture_final_size( rect: cairo.RectangleInt, width: number, height: number, scale: number ): boolean; get_frame_counter(): number; get_key_focus(): Actor; get_minimum_size(): [number, number]; get_motion_events_enabled(): boolean; get_perspective(): Perspective | null; get_throttle_motion_events(): boolean; get_title(): string; get_use_alpha(): boolean; paint_to_buffer( rect: cairo.RectangleInt, scale: number, data: number, stride: number, format: Cogl.PixelFormat, paint_flags: PaintFlag ): boolean; paint_to_framebuffer( framebuffer: Cogl.Framebuffer, rect: cairo.RectangleInt, scale: number, paint_flags: PaintFlag ): void; read_pixels( x: number, y: number, width: number, height: number ): Uint8Array; schedule_update(): void; set_key_focus(actor?: Actor | null): void; set_minimum_size(width: number, height: number): void; set_motion_events_enabled(enabled: boolean): void; set_throttle_motion_events(throttle: boolean): void; set_title(title: string): void; set_use_alpha(use_alpha: boolean): void; vfunc_activate(): void; vfunc_before_paint(view: StageView): void; vfunc_deactivate(): void; vfunc_paint_view(view: StageView, redraw_clip: cairo.Region): void; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace StageManager { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; default_stage: Stage; defaultStage: Stage; } } export class StageManager extends GObject.Object { static $gtype: GObject.GType<StageManager>; constructor( properties?: Partial<StageManager.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StageManager.ConstructorProperties>, ...args: any[] ): void; // Properties default_stage: Stage; defaultStage: Stage; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'stage-added', callback: (_source: this, stage: Stage) => void ): number; connect_after( signal: 'stage-added', callback: (_source: this, stage: Stage) => void ): number; emit(signal: 'stage-added', stage: Stage): void; connect( signal: 'stage-removed', callback: (_source: this, stage: Stage) => void ): number; connect_after( signal: 'stage-removed', callback: (_source: this, stage: Stage) => void ): number; emit(signal: 'stage-removed', stage: Stage): void; // Members get_default_stage(): Stage; list_stages(): Stage[]; peek_stages(): Stage[]; vfunc_stage_added(stage: Stage): void; vfunc_stage_removed(stage: Stage): void; static get_default(): StageManager; } export namespace StageView { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; layout: cairo.RectangleInt; name: string; refresh_rate: number; refreshRate: number; scale: number; stage: Stage; use_shadowfb: boolean; useShadowfb: boolean; } } export class StageView extends GObject.Object { static $gtype: GObject.GType<StageView>; constructor( properties?: Partial<StageView.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StageView.ConstructorProperties>, ...args: any[] ): void; // Properties layout: cairo.RectangleInt; name: string; refresh_rate: number; refreshRate: number; scale: number; stage: Stage; use_shadowfb: boolean; useShadowfb: boolean; // Members assign_next_scanout(scanout: Cogl.Scanout): void; destroy(): void; get_framebuffer(): Cogl.Framebuffer; get_layout(rect: cairo.RectangleInt): void; get_offscreen_transformation_matrix(matrix: Cogl.Matrix): void; get_onscreen(): Cogl.Framebuffer; get_refresh_rate(): number; get_scale(): number; invalidate_offscreen_blit_pipeline(): void; vfunc_get_offscreen_transformation_matrix(matrix: Cogl.Matrix): void; vfunc_setup_offscreen_blit_pipeline(pipeline: Cogl.Pipeline): void; vfunc_transform_rect_to_onscreen( src_rect: cairo.RectangleInt, dst_width: number, dst_height: number, dst_rect: cairo.RectangleInt ): void; } export namespace SwipeAction { export interface ConstructorProperties extends GestureAction.ConstructorProperties { [key: string]: any; } } export class SwipeAction extends GestureAction { static $gtype: GObject.GType<SwipeAction>; constructor( properties?: Partial<SwipeAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SwipeAction.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'swept', callback: ( _source: this, actor: Actor, direction: SwipeDirection ) => void ): number; connect_after( signal: 'swept', callback: ( _source: this, actor: Actor, direction: SwipeDirection ) => void ): number; emit(signal: 'swept', actor: Actor, direction: SwipeDirection): void; connect( signal: 'swipe', callback: ( _source: this, actor: Actor, direction: SwipeDirection ) => boolean ): number; connect_after( signal: 'swipe', callback: ( _source: this, actor: Actor, direction: SwipeDirection ) => boolean ): number; emit(signal: 'swipe', actor: Actor, direction: SwipeDirection): void; // Constructors static ['new'](): SwipeAction; // Members vfunc_swept(actor: Actor, direction: SwipeDirection): void; vfunc_swipe(actor: Actor, direction: SwipeDirection): boolean; } export namespace TapAction { export interface ConstructorProperties extends GestureAction.ConstructorProperties { [key: string]: any; } } export class TapAction extends GestureAction { static $gtype: GObject.GType<TapAction>; constructor( properties?: Partial<TapAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TapAction.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'tap', callback: (_source: this, actor: Actor) => void ): number; connect_after( signal: 'tap', callback: (_source: this, actor: Actor) => void ): number; emit(signal: 'tap', actor: Actor): void; // Constructors static ['new'](): TapAction; // Members vfunc_tap(actor: Actor): boolean; } export namespace Text { export interface ConstructorProperties<A extends Actor = Actor> extends Actor.ConstructorProperties { [key: string]: any; activatable: boolean; attributes: Pango.AttrList; buffer: TextBuffer; color: Color; cursor_color: Color; cursorColor: Color; cursor_color_set: boolean; cursorColorSet: boolean; cursor_position: number; cursorPosition: number; cursor_size: number; cursorSize: number; cursor_visible: boolean; cursorVisible: boolean; editable: boolean; ellipsize: Pango.EllipsizeMode; font_description: Pango.FontDescription; fontDescription: Pango.FontDescription; font_name: string; fontName: string; input_hints: InputContentHintFlags; inputHints: InputContentHintFlags; input_purpose: InputContentPurpose; inputPurpose: InputContentPurpose; justify: boolean; line_alignment: Pango.Alignment; lineAlignment: Pango.Alignment; line_wrap: boolean; lineWrap: boolean; line_wrap_mode: Pango.WrapMode; lineWrapMode: Pango.WrapMode; max_length: number; maxLength: number; password_char: number; passwordChar: number; position: number | any; selectable: boolean; selected_text_color: Color; selectedTextColor: Color; selected_text_color_set: boolean; selectedTextColorSet: boolean; selection_bound: number; selectionBound: number; selection_color: Color; selectionColor: Color; selection_color_set: boolean; selectionColorSet: boolean; single_line_mode: boolean; singleLineMode: boolean; text: string; use_markup: boolean; useMarkup: boolean; } } export class Text<A extends Actor = Actor> extends Actor implements Atk.ImplementorIface, Animatable, Container<A>, Scriptable { static $gtype: GObject.GType<Text>; constructor( properties?: Partial<Text.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<Text.ConstructorProperties<A>>, ...args: any[] ): void; // Properties activatable: boolean; attributes: Pango.AttrList; buffer: TextBuffer; color: Color; cursor_color: Color; cursorColor: Color; cursor_color_set: boolean; cursorColorSet: boolean; cursor_position: number; cursorPosition: number; cursor_size: number; cursorSize: number; cursor_visible: boolean; cursorVisible: boolean; editable: boolean; ellipsize: Pango.EllipsizeMode; font_description: Pango.FontDescription; fontDescription: Pango.FontDescription; font_name: string; fontName: string; input_hints: InputContentHintFlags; inputHints: InputContentHintFlags; input_purpose: InputContentPurpose; inputPurpose: InputContentPurpose; justify: boolean; line_alignment: Pango.Alignment; lineAlignment: Pango.Alignment; line_wrap: boolean; lineWrap: boolean; line_wrap_mode: Pango.WrapMode; lineWrapMode: Pango.WrapMode; max_length: number; maxLength: number; password_char: number; passwordChar: number; position: number | any; selectable: boolean; selected_text_color: Color; selectedTextColor: Color; selected_text_color_set: boolean; selectedTextColorSet: boolean; selection_bound: number; selectionBound: number; selection_color: Color; selectionColor: Color; selection_color_set: boolean; selectionColorSet: boolean; single_line_mode: boolean; singleLineMode: boolean; text: string; use_markup: boolean; useMarkup: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; connect( signal: 'cursor-changed', callback: (_source: this) => void ): number; connect_after( signal: 'cursor-changed', callback: (_source: this) => void ): number; emit(signal: 'cursor-changed'): void; connect( signal: 'cursor-event', callback: (_source: this, rect: Graphene.Rect) => void ): number; connect_after( signal: 'cursor-event', callback: (_source: this, rect: Graphene.Rect) => void ): number; emit(signal: 'cursor-event', rect: Graphene.Rect): void; connect( signal: 'delete-text', callback: (_source: this, start_pos: number, end_pos: number) => void ): number; connect_after( signal: 'delete-text', callback: (_source: this, start_pos: number, end_pos: number) => void ): number; emit(signal: 'delete-text', start_pos: number, end_pos: number): void; connect( signal: 'insert-text', callback: ( _source: this, new_text: string, new_text_length: number, position: any | null ) => void ): number; connect_after( signal: 'insert-text', callback: ( _source: this, new_text: string, new_text_length: number, position: any | null ) => void ): number; emit( signal: 'insert-text', new_text: string, new_text_length: number, position: any | null ): void; connect(signal: 'text-changed', callback: (_source: this) => void): number; connect_after( signal: 'text-changed', callback: (_source: this) => void ): number; emit(signal: 'text-changed'): void; // Constructors static ['new'](): Text; static new_full(font_name: string, text: string, color: Color): Text; static new_with_buffer(buffer: TextBuffer): Text; static new_with_text(font_name: string | null, text: string): Text; // Members activate(): boolean; coords_to_position(x: number, y: number): number; delete_chars(n_chars: number): void; delete_selection(): boolean; delete_text(start_pos: number, end_pos: number): void; get_activatable(): boolean; get_attributes(): Pango.AttrList; get_buffer(): TextBuffer; get_chars(start_pos: number, end_pos: number): string; get_color(): Color; get_cursor_color(): Color; get_cursor_position(): number; get_cursor_rect(): Graphene.Rect; get_cursor_size(): number; get_cursor_visible(): boolean; get_editable(): boolean; get_ellipsize(): Pango.EllipsizeMode; get_font_description(): Pango.FontDescription; get_font_name(): string; get_input_hints(): InputContentHintFlags; get_input_purpose(): InputContentPurpose; get_justify(): boolean; get_layout(): Pango.Layout; get_layout_offsets(): [number, number]; get_line_alignment(): Pango.Alignment; get_line_wrap(): boolean; get_line_wrap_mode(): Pango.WrapMode; get_max_length(): number; get_password_char(): number; get_selectable(): boolean; get_selected_text_color(): Color; get_selection(): string; get_selection_bound(): number; get_selection_color(): Color; get_single_line_mode(): boolean; get_text(): string; get_use_markup(): boolean; has_preedit(): boolean; insert_text(text: string, position: number): void; insert_unichar(wc: number): void; position_to_coords(position: number): [boolean, number, number, number]; set_activatable(activatable: boolean): void; set_attributes(attrs?: Pango.AttrList | null): void; set_buffer(buffer: TextBuffer): void; set_color(color: Color): void; set_cursor_color(color?: Color | null): void; set_cursor_position(position: number): void; set_cursor_size(size: number): void; set_cursor_visible(cursor_visible: boolean): void; set_editable(editable: boolean): void; set_ellipsize(mode: Pango.EllipsizeMode): void; set_font_description(font_desc: Pango.FontDescription): void; set_font_name(font_name?: string | null): void; set_input_hints(hints: InputContentHintFlags): void; set_input_purpose(purpose: InputContentPurpose): void; set_justify(justify: boolean): void; set_line_alignment(alignment: Pango.Alignment): void; set_line_wrap(line_wrap: boolean): void; set_line_wrap_mode(wrap_mode: Pango.WrapMode): void; set_markup(markup?: string | null): void; set_max_length(max: number): void; set_password_char(wc: number): void; set_preedit_string( preedit_str: string | null, preedit_attrs: Pango.AttrList | null, cursor_pos: number ): void; set_selectable(selectable: boolean): void; set_selected_text_color(color?: Color | null): void; set_selection(start_pos: number, end_pos: number): void; set_selection_bound(selection_bound: number): void; set_selection_color(color?: Color | null): void; set_single_line_mode(single_line: boolean): void; set_text(text?: string | null): void; set_use_markup(setting: boolean): void; vfunc_activate(): void; vfunc_cursor_changed(): void; vfunc_cursor_event(rect: Graphene.Rect): void; vfunc_text_changed(): void; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace TextBuffer { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; length: number; max_length: number; maxLength: number; text: string; } } export class TextBuffer extends GObject.Object { static $gtype: GObject.GType<TextBuffer>; constructor( properties?: Partial<TextBuffer.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextBuffer.ConstructorProperties>, ...args: any[] ): void; // Properties length: number; max_length: number; maxLength: number; text: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'deleted-text', callback: (_source: this, position: number, n_chars: number) => void ): number; connect_after( signal: 'deleted-text', callback: (_source: this, position: number, n_chars: number) => void ): number; emit(signal: 'deleted-text', position: number, n_chars: number): void; connect( signal: 'inserted-text', callback: ( _source: this, position: number, chars: string, n_chars: number ) => void ): number; connect_after( signal: 'inserted-text', callback: ( _source: this, position: number, chars: string, n_chars: number ) => void ): number; emit( signal: 'inserted-text', position: number, chars: string, n_chars: number ): void; // Constructors static ['new'](): TextBuffer; static new_with_text(text: string | null, text_len: number): TextBuffer; // Members delete_text(position: number, n_chars: number): number; emit_deleted_text(position: number, n_chars: number): void; emit_inserted_text(position: number, chars: string, n_chars: number): void; get_bytes(): number; get_length(): number; get_max_length(): number; get_text(): string; insert_text(position: number, chars: string, n_chars: number): number; set_max_length(max_length: number): void; set_text(chars: string, n_chars: number): void; vfunc_delete_text(position: number, n_chars: number): number; vfunc_deleted_text(position: number, n_chars: number): void; vfunc_get_length(): number; vfunc_get_text(n_bytes: number): string; vfunc_insert_text(position: number, chars: string, n_chars: number): number; vfunc_inserted_text(position: number, chars: string, n_chars: number): void; } export namespace TextNode { export interface ConstructorProperties extends PaintNode.ConstructorProperties { [key: string]: any; } } export class TextNode extends PaintNode { static $gtype: GObject.GType<TextNode>; constructor( properties?: Partial<TextNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextNode.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( layout?: Pango.Layout | null, color?: Color | null ): TextNode; } export namespace TextureNode { export interface ConstructorProperties extends PipelineNode.ConstructorProperties { [key: string]: any; } } export class TextureNode extends PipelineNode { static $gtype: GObject.GType<TextureNode>; constructor( properties?: Partial<TextureNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextureNode.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( texture: Cogl.Texture, color: Color | null, min_filter: ScalingFilter, mag_filter: ScalingFilter ): TextureNode; } export namespace Timeline { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; actor: Actor; auto_reverse: boolean; autoReverse: boolean; delay: number; direction: TimelineDirection; duration: number; frame_clock: FrameClock; frameClock: FrameClock; progress_mode: AnimationMode; progressMode: AnimationMode; repeat_count: number; repeatCount: number; } } export class Timeline extends GObject.Object implements Scriptable { static $gtype: GObject.GType<Timeline>; constructor( properties?: Partial<Timeline.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Timeline.ConstructorProperties>, ...args: any[] ): void; // Properties actor: Actor; auto_reverse: boolean; autoReverse: boolean; delay: number; direction: TimelineDirection; duration: number; frame_clock: FrameClock; frameClock: FrameClock; progress_mode: AnimationMode; progressMode: AnimationMode; repeat_count: number; repeatCount: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'completed', callback: (_source: this) => void): number; connect_after( signal: 'completed', callback: (_source: this) => void ): number; emit(signal: 'completed'): void; connect( signal: 'marker-reached', callback: (_source: this, marker_name: string, msecs: number) => void ): number; connect_after( signal: 'marker-reached', callback: (_source: this, marker_name: string, msecs: number) => void ): number; emit(signal: 'marker-reached', marker_name: string, msecs: number): void; connect( signal: 'new-frame', callback: (_source: this, msecs: number) => void ): number; connect_after( signal: 'new-frame', callback: (_source: this, msecs: number) => void ): number; emit(signal: 'new-frame', msecs: number): void; connect(signal: 'paused', callback: (_source: this) => void): number; connect_after(signal: 'paused', callback: (_source: this) => void): number; emit(signal: 'paused'): void; connect(signal: 'started', callback: (_source: this) => void): number; connect_after(signal: 'started', callback: (_source: this) => void): number; emit(signal: 'started'): void; connect( signal: 'stopped', callback: (_source: this, is_finished: boolean) => void ): number; connect_after( signal: 'stopped', callback: (_source: this, is_finished: boolean) => void ): number; emit(signal: 'stopped', is_finished: boolean): void; // Constructors static ['new'](duration_ms: number): Timeline; static new_for_actor(actor: Actor, duration_ms: number): Timeline; static new_for_frame_clock( frame_clock: FrameClock, duration_ms: number ): Timeline; // Members add_marker(marker_name: string, progress: number): void; add_marker_at_time(marker_name: string, msecs: number): void; advance(msecs: number): void; advance_to_marker(marker_name: string): void; get_actor(): Actor; get_auto_reverse(): boolean; get_cubic_bezier_progress(): [boolean, Graphene.Point, Graphene.Point]; get_current_repeat(): number; get_delay(): number; get_delta(): number; get_direction(): TimelineDirection; get_duration(): number; get_duration_hint(): number; get_elapsed_time(): number; get_progress(): number; get_progress_mode(): AnimationMode; get_repeat_count(): number; get_step_progress(): [boolean, number, StepMode]; has_marker(marker_name: string): boolean; is_playing(): boolean; list_markers(msecs: number): string[]; pause(): void; remove_marker(marker_name: string): void; rewind(): void; set_actor(actor?: Actor | null): void; set_auto_reverse(reverse: boolean): void; set_cubic_bezier_progress(c_1: Graphene.Point, c_2: Graphene.Point): void; set_delay(msecs: number): void; set_direction(direction: TimelineDirection): void; set_duration(msecs: number): void; set_frame_clock(frame_clock: FrameClock): void; set_progress_func(func?: TimelineProgressFunc | null): void; set_progress_mode(mode: AnimationMode): void; set_repeat_count(count: number): void; set_step_progress(n_steps: number, step_mode: StepMode): void; skip(msecs: number): void; start(): void; stop(): void; vfunc_completed(): void; vfunc_marker_reached(marker_name: string, msecs: number): void; vfunc_new_frame(msecs: number): void; vfunc_paused(): void; vfunc_started(): void; vfunc_stopped(is_finished: boolean): void; // Implemented Members get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace TransformNode { export interface ConstructorProperties extends PaintNode.ConstructorProperties { [key: string]: any; } } export class TransformNode extends PaintNode { static $gtype: GObject.GType<TransformNode>; constructor( properties?: Partial<TransformNode.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TransformNode.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](projection: Cogl.Matrix): TransformNode; } export namespace Transition { export interface ConstructorProperties extends Timeline.ConstructorProperties { [key: string]: any; animatable: Animatable; interval: Interval; remove_on_complete: boolean; removeOnComplete: boolean; } } export abstract class Transition extends Timeline implements Scriptable { static $gtype: GObject.GType<Transition>; constructor( properties?: Partial<Transition.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Transition.ConstructorProperties>, ...args: any[] ): void; // Properties animatable: Animatable; interval: Interval; remove_on_complete: boolean; removeOnComplete: boolean; // Members get_animatable(): Animatable; get_interval(): Interval; get_remove_on_complete(): boolean; set_animatable(animatable?: Animatable | null): void; set_from(value: any): void; set_interval(interval?: Interval | null): void; set_remove_on_complete(remove_complete: boolean): void; set_to(value: any): void; vfunc_attached(animatable: Animatable): void; vfunc_compute_value( animatable: Animatable, interval: Interval, progress: number ): void; vfunc_detached(animatable: Animatable): void; // Implemented Members get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace TransitionGroup { export interface ConstructorProperties extends Transition.ConstructorProperties { [key: string]: any; } } export class TransitionGroup extends Transition implements Scriptable { static $gtype: GObject.GType<TransitionGroup>; constructor( properties?: Partial<TransitionGroup.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TransitionGroup.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): TransitionGroup; static ['new'](...args: never[]): never; // Members add_transition(transition: Transition): void; remove_all(): void; remove_transition(transition: Transition): void; // Implemented Members get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export namespace VirtualInputDevice { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; device_type: InputDeviceType; deviceType: InputDeviceType; seat: Seat; } } export class VirtualInputDevice extends GObject.Object { static $gtype: GObject.GType<VirtualInputDevice>; constructor( properties?: Partial<VirtualInputDevice.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<VirtualInputDevice.ConstructorProperties>, ...args: any[] ): void; // Properties device_type: InputDeviceType; deviceType: InputDeviceType; seat: Seat; // Members get_device_type(): number; notify_absolute_motion(time_us: number, x: number, y: number): void; notify_button( time_us: number, button: number, button_state: ButtonState ): void; notify_discrete_scroll( time_us: number, direction: ScrollDirection, scroll_source: ScrollSource ): void; notify_key(time_us: number, key: number, key_state: KeyState): void; notify_keyval(time_us: number, keyval: number, key_state: KeyState): void; notify_relative_motion(time_us: number, dx: number, dy: number): void; notify_scroll_continuous( time_us: number, dx: number, dy: number, scroll_source: ScrollSource, finish_flags: ScrollFinishFlags ): void; notify_touch_down( time_us: number, slot: number, x: number, y: number ): void; notify_touch_motion( time_us: number, slot: number, x: number, y: number ): void; notify_touch_up(time_us: number, slot: number): void; vfunc_notify_absolute_motion(time_us: number, x: number, y: number): void; vfunc_notify_button( time_us: number, button: number, button_state: ButtonState ): void; vfunc_notify_discrete_scroll( time_us: number, direction: ScrollDirection, scroll_source: ScrollSource ): void; vfunc_notify_key(time_us: number, key: number, key_state: KeyState): void; vfunc_notify_keyval( time_us: number, keyval: number, key_state: KeyState ): void; vfunc_notify_relative_motion(time_us: number, dx: number, dy: number): void; vfunc_notify_scroll_continuous( time_us: number, dx: number, dy: number, scroll_source: ScrollSource, finish_flags: ScrollFinishFlags ): void; vfunc_notify_touch_down( time_us: number, slot: number, x: number, y: number ): void; vfunc_notify_touch_motion( time_us: number, slot: number, x: number, y: number ): void; vfunc_notify_touch_up(time_us: number, slot: number): void; } export namespace ZoomAction { export interface ConstructorProperties extends GestureAction.ConstructorProperties { [key: string]: any; zoom_axis: ZoomAxis; zoomAxis: ZoomAxis; } } export class ZoomAction extends GestureAction { static $gtype: GObject.GType<ZoomAction>; constructor( properties?: Partial<ZoomAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ZoomAction.ConstructorProperties>, ...args: any[] ): void; // Properties zoom_axis: ZoomAxis; zoomAxis: ZoomAxis; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'zoom', callback: ( _source: this, actor: Actor, focal_point: Graphene.Point, factor: number ) => boolean ): number; connect_after( signal: 'zoom', callback: ( _source: this, actor: Actor, focal_point: Graphene.Point, factor: number ) => boolean ): number; emit( signal: 'zoom', actor: Actor, focal_point: Graphene.Point, factor: number ): void; // Constructors static ['new'](): ZoomAction; // Members get_focal_point(): Graphene.Point; get_transformed_focal_point(): Graphene.Point; get_zoom_axis(): ZoomAxis; set_zoom_axis(axis: ZoomAxis): void; vfunc_zoom( actor: Actor, focal_point: Graphene.Point, factor: number ): boolean; } export class ActorBox { static $gtype: GObject.GType<ActorBox>; constructor(x_1: number, y_1: number, x_2: number, y_2: number); constructor( properties?: Partial<{ x1?: number; y1?: number; x2?: number; y2?: number; }> ); constructor(copy: ActorBox); // Fields x1: number; y1: number; x2: number; y2: number; // Constructors static ['new']( x_1: number, y_1: number, x_2: number, y_2: number ): ActorBox; // Members clamp_to_pixel(): void; contains(x: number, y: number): boolean; copy(): ActorBox; equal(box_b: ActorBox): boolean; free(): void; from_vertices(verts: Graphene.Point3D[]): void; get_area(): number; get_height(): number; get_origin(): [number | null, number | null]; get_size(): [number | null, number | null]; get_width(): number; get_x(): number; get_y(): number; init(x_1: number, y_1: number, x_2: number, y_2: number): ActorBox; init_rect(x: number, y: number, width: number, height: number): void; interpolate(_final: ActorBox, progress: number): ActorBox; is_initialized(): boolean; scale(scale: number): void; set_origin(x: number, y: number): void; set_size(width: number, height: number): void; union(b: ActorBox): ActorBox; static alloc(): ActorBox; } export class ActorIter { static $gtype: GObject.GType<ActorIter>; constructor( properties?: Partial<{ dummy1?: any; dummy2?: any; dummy3?: any; dummy4?: number; dummy5?: any; }> ); constructor(copy: ActorIter); // Fields dummy1: any; dummy2: any; dummy3: any; dummy4: number; dummy5: any; // Members destroy(): void; init(root: Actor): void; is_valid(): boolean; next(): [boolean, Actor]; prev(): [boolean, Actor]; remove(): void; } export class ActorMetaPrivate { static $gtype: GObject.GType<ActorMetaPrivate>; constructor(copy: ActorMetaPrivate); } export class ActorPrivate { static $gtype: GObject.GType<ActorPrivate>; constructor(copy: ActorPrivate); } export class AnyEvent { static $gtype: GObject.GType<AnyEvent>; constructor(copy: AnyEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; } export class BinLayoutPrivate { static $gtype: GObject.GType<BinLayoutPrivate>; constructor(copy: BinLayoutPrivate); } export class BoxLayoutPrivate { static $gtype: GObject.GType<BoxLayoutPrivate>; constructor(copy: BoxLayoutPrivate); } export class ButtonEvent { static $gtype: GObject.GType<ButtonEvent>; constructor(copy: ButtonEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; x: number; y: number; modifier_state: ModifierType; button: number; click_count: number; axes: number; device: InputDevice; } export class CanvasPrivate { static $gtype: GObject.GType<CanvasPrivate>; constructor(copy: CanvasPrivate); } export class Capture { static $gtype: GObject.GType<Capture>; constructor(copy: Capture); // Fields image: cairo.Surface; rect: cairo.RectangleInt; } export class ClickActionPrivate { static $gtype: GObject.GType<ClickActionPrivate>; constructor(copy: ClickActionPrivate); } export class ClonePrivate { static $gtype: GObject.GType<ClonePrivate>; constructor(copy: ClonePrivate); } export class Color { static $gtype: GObject.GType<Color>; constructor(); constructor( properties?: Partial<{ red?: number; green?: number; blue?: number; alpha?: number; }> ); constructor(copy: Color); // Fields red: number; green: number; blue: number; alpha: number; // Constructors static alloc(): Color; static ['new']( red: number, green: number, blue: number, alpha: number ): Color; // Members add(b: Color): Color; copy(): Color; darken(): Color; equal(v2: Color): boolean; free(): void; hash(): number; init(red: number, green: number, blue: number, alpha: number): Color; interpolate(_final: Color, progress: number): Color; lighten(): Color; shade(factor: number): Color; subtract(b: Color): Color; to_hls(): [number, number, number]; to_pixel(): number; to_string(): string; static from_hls(hue: number, luminance: number, saturation: number): Color; static from_pixel(pixel: number): Color; static from_string(str: string): [boolean, Color]; static get_static(color: StaticColor): Color; } export class CrossingEvent { static $gtype: GObject.GType<CrossingEvent>; constructor(copy: CrossingEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; x: number; y: number; device: InputDevice; sequence: EventSequence; related: Actor; } export class DeformEffectPrivate { static $gtype: GObject.GType<DeformEffectPrivate>; constructor(copy: DeformEffectPrivate); } export class DeviceEvent { static $gtype: GObject.GType<DeviceEvent>; constructor(copy: DeviceEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; device: InputDevice; } export class EventSequence { static $gtype: GObject.GType<EventSequence>; constructor(copy: EventSequence); } export class FlowLayoutPrivate { static $gtype: GObject.GType<FlowLayoutPrivate>; constructor(copy: FlowLayoutPrivate); } export class FrameListenerIface { static $gtype: GObject.GType<FrameListenerIface>; constructor(copy: FrameListenerIface); } export class GestureActionPrivate { static $gtype: GObject.GType<GestureActionPrivate>; constructor(copy: GestureActionPrivate); } export class GridLayoutPrivate { static $gtype: GObject.GType<GridLayoutPrivate>; constructor(copy: GridLayoutPrivate); } export class IMEvent { static $gtype: GObject.GType<IMEvent>; constructor(copy: IMEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; text: string; offset: number; len: number; } export class ImagePrivate { static $gtype: GObject.GType<ImagePrivate>; constructor(copy: ImagePrivate); } export class IntervalPrivate { static $gtype: GObject.GType<IntervalPrivate>; constructor(copy: IntervalPrivate); } export class KbdA11ySettings { static $gtype: GObject.GType<KbdA11ySettings>; constructor(copy: KbdA11ySettings); // Fields controls: KeyboardA11yFlags; slowkeys_delay: number; debounce_delay: number; timeout_delay: number; mousekeys_init_delay: number; mousekeys_max_speed: number; mousekeys_accel_time: number; } export class KeyEvent { static $gtype: GObject.GType<KeyEvent>; constructor(copy: KeyEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; modifier_state: ModifierType; keyval: number; hardware_keycode: number; unicode_value: number; device: InputDevice; } export class KeyframeTransitionPrivate { static $gtype: GObject.GType<KeyframeTransitionPrivate>; constructor(copy: KeyframeTransitionPrivate); } export class Knot { static $gtype: GObject.GType<Knot>; constructor( properties?: Partial<{ x?: number; y?: number; }> ); constructor(copy: Knot); // Fields x: number; y: number; // Members copy(): Knot; equal(knot_b: Knot): boolean; free(): void; } export class Margin { static $gtype: GObject.GType<Margin>; constructor(); constructor( properties?: Partial<{ left?: number; right?: number; top?: number; bottom?: number; }> ); constructor(copy: Margin); // Fields left: number; right: number; top: number; bottom: number; // Constructors static ['new'](): Margin; // Members copy(): Margin; free(): void; } export class MotionEvent { static $gtype: GObject.GType<MotionEvent>; constructor(copy: MotionEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; x: number; y: number; modifier_state: ModifierType; axes: number; device: InputDevice; } export class OffscreenEffectPrivate { static $gtype: GObject.GType<OffscreenEffectPrivate>; constructor(copy: OffscreenEffectPrivate); } export class PadButtonEvent { static $gtype: GObject.GType<PadButtonEvent>; constructor(copy: PadButtonEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; button: number; group: number; device: InputDevice; mode: number; } export class PadRingEvent { static $gtype: GObject.GType<PadRingEvent>; constructor(copy: PadRingEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; device: InputDevice; ring_source: InputDevicePadSource; ring_number: number; group: number; angle: number; mode: number; } export class PadStripEvent { static $gtype: GObject.GType<PadStripEvent>; constructor(copy: PadStripEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; device: InputDevice; strip_source: InputDevicePadSource; strip_number: number; group: number; value: number; mode: number; } export class PaintContext { static $gtype: GObject.GType<PaintContext>; constructor(copy: PaintContext); // Members destroy(): void; get_framebuffer(): Cogl.Framebuffer; get_redraw_clip(): cairo.Region; pop_framebuffer(): void; push_framebuffer(framebuffer: Cogl.Framebuffer): void; ref(): PaintContext; unref(): void; } export class PaintNodePrivate { static $gtype: GObject.GType<PaintNodePrivate>; constructor(copy: PaintNodePrivate); } export class PaintVolume { static $gtype: GObject.GType<PaintVolume>; constructor(copy: PaintVolume); // Members copy(): PaintVolume; free(): void; get_depth(): number; get_height(): number; get_origin(): Graphene.Point3D; get_width(): number; set_depth(depth: number): void; set_from_allocation(actor: Actor): boolean; set_height(height: number): void; set_origin(origin: Graphene.Point3D): void; set_width(width: number): void; union(another_pv: PaintVolume): void; union_box(box: ActorBox): void; } export class PanActionPrivate { static $gtype: GObject.GType<PanActionPrivate>; constructor(copy: PanActionPrivate); } export class PathNode { static $gtype: GObject.GType<PathNode>; constructor(copy: PathNode); // Fields type: PathNodeType; points: Knot[]; // Members copy(): PathNode; equal(node_b: PathNode): boolean; free(): void; } export class PathPrivate { static $gtype: GObject.GType<PathPrivate>; constructor(copy: PathPrivate); } export class Perspective { static $gtype: GObject.GType<Perspective>; constructor( properties?: Partial<{ fovy?: number; aspect?: number; z_near?: number; z_far?: number; }> ); constructor(copy: Perspective); // Fields fovy: number; aspect: number; z_near: number; z_far: number; } export class PickContext { static $gtype: GObject.GType<PickContext>; constructor(copy: PickContext); // Members destroy(): void; ref(): PickContext; unref(): void; } export class PointerA11ySettings { static $gtype: GObject.GType<PointerA11ySettings>; constructor(copy: PointerA11ySettings); // Fields controls: PointerA11yFlags; dwell_click_type: PointerA11yDwellClickType; dwell_mode: PointerA11yDwellMode; dwell_gesture_single: PointerA11yDwellDirection; dwell_gesture_double: PointerA11yDwellDirection; dwell_gesture_drag: PointerA11yDwellDirection; dwell_gesture_secondary: PointerA11yDwellDirection; secondary_click_delay: number; dwell_delay: number; dwell_threshold: number; } export class PropertyTransitionPrivate { static $gtype: GObject.GType<PropertyTransitionPrivate>; constructor(copy: PropertyTransitionPrivate); } export class ProximityEvent { static $gtype: GObject.GType<ProximityEvent>; constructor(copy: ProximityEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; device: InputDevice; } export class RotateActionPrivate { static $gtype: GObject.GType<RotateActionPrivate>; constructor(copy: RotateActionPrivate); } export class ScriptPrivate { static $gtype: GObject.GType<ScriptPrivate>; constructor(copy: ScriptPrivate); } export class ScrollActorPrivate { static $gtype: GObject.GType<ScrollActorPrivate>; constructor(copy: ScrollActorPrivate); } export class ScrollEvent { static $gtype: GObject.GType<ScrollEvent>; constructor(copy: ScrollEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; x: number; y: number; direction: ScrollDirection; modifier_state: ModifierType; axes: number; device: InputDevice; scroll_source: ScrollSource; finish_flags: ScrollFinishFlags; } export class Shader { static $gtype: GObject.GType<Shader>; constructor(copy: Shader); } export class ShaderEffectPrivate { static $gtype: GObject.GType<ShaderEffectPrivate>; constructor(copy: ShaderEffectPrivate); } export class StagePrivate { static $gtype: GObject.GType<StagePrivate>; constructor(copy: StagePrivate); } export class StageStateEvent { static $gtype: GObject.GType<StageStateEvent>; constructor(copy: StageStateEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; changed_mask: StageState; new_state: StageState; } export class SwipeActionPrivate { static $gtype: GObject.GType<SwipeActionPrivate>; constructor(copy: SwipeActionPrivate); } export class TapActionPrivate { static $gtype: GObject.GType<TapActionPrivate>; constructor(copy: TapActionPrivate); } export class TextBufferPrivate { static $gtype: GObject.GType<TextBufferPrivate>; constructor(copy: TextBufferPrivate); } export class TextPrivate { static $gtype: GObject.GType<TextPrivate>; constructor(copy: TextPrivate); } export class TimelinePrivate { static $gtype: GObject.GType<TimelinePrivate>; constructor(copy: TimelinePrivate); } export class TouchEvent { static $gtype: GObject.GType<TouchEvent>; constructor(copy: TouchEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; x: number; y: number; sequence: EventSequence; modifier_state: ModifierType; axes: number; device: InputDevice; } export class TouchpadPinchEvent { static $gtype: GObject.GType<TouchpadPinchEvent>; constructor(copy: TouchpadPinchEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; phase: TouchpadGesturePhase; x: number; y: number; dx: number; dy: number; angle_delta: number; scale: number; n_fingers: number; } export class TouchpadSwipeEvent { static $gtype: GObject.GType<TouchpadSwipeEvent>; constructor(copy: TouchpadSwipeEvent); // Fields type: EventType; time: number; flags: EventFlags; stage: Stage; source: Actor; phase: TouchpadGesturePhase; n_fingers: number; x: number; y: number; dx: number; dy: number; } export class TransitionGroupPrivate { static $gtype: GObject.GType<TransitionGroupPrivate>; constructor(copy: TransitionGroupPrivate); } export class TransitionPrivate { static $gtype: GObject.GType<TransitionPrivate>; constructor(copy: TransitionPrivate); } export class Units { static $gtype: GObject.GType<Units>; constructor(copy: Units); // Fields unit_type: UnitType; value: number; pixels: number; pixels_set: number; serial: number; // Members copy(): Units; free(): void; get_unit_type(): UnitType; get_unit_value(): number; to_pixels(): number; to_string(): string; static from_cm(cm: number): Units; static from_em(em: number): Units; static from_em_for_font(font_name: string | null, em: number): Units; static from_mm(mm: number): Units; static from_pixels(px: number): Units; static from_pt(pt: number): Units; static from_string(str: string): [boolean, Units]; } export class ZoomActionPrivate { static $gtype: GObject.GType<ZoomActionPrivate>; constructor(copy: ZoomActionPrivate); } export class Event { static $gtype: GObject.GType<Event>; constructor(type: EventType); constructor(copy: Event); // Fields any: AnyEvent; button: ButtonEvent; key: KeyEvent; motion: MotionEvent; scroll: ScrollEvent; stage_state: StageStateEvent; crossing: CrossingEvent; touch: TouchEvent; touchpad_pinch: TouchpadPinchEvent; touchpad_swipe: TouchpadSwipeEvent; proximity: ProximityEvent; pad_button: PadButtonEvent; pad_strip: PadStripEvent; pad_ring: PadRingEvent; device: DeviceEvent; im: IMEvent; // Constructors static ['new'](type: EventType): Event; // Members copy(): Event; free(): void; get_angle(target: Event): number; get_axes(): [number, number]; get_button(): number; get_click_count(): number; get_coords(): [number, number]; get_device(): InputDevice; get_device_id(): number; get_device_tool(): InputDeviceTool; get_device_type(): InputDeviceType; get_distance(target: Event): number; get_event_sequence(): EventSequence; get_flags(): EventFlags; get_gesture_motion_delta(): [number | null, number | null]; get_gesture_phase(): TouchpadGesturePhase; get_gesture_pinch_angle_delta(): number; get_gesture_pinch_scale(): number; get_key_code(): number; get_key_symbol(): number; get_key_unicode(): number; get_mode_group(): number; get_pad_event_details(): [ boolean, number | null, number | null, number | null ]; get_position(position: Graphene.Point): void; get_related(): Actor; get_scroll_delta(): [number, number]; get_scroll_direction(): ScrollDirection; get_scroll_finish_flags(): ScrollFinishFlags; get_scroll_source(): ScrollSource; get_source(): Actor; get_source_device(): InputDevice; get_stage(): Stage; get_state(): ModifierType; get_state_full(): [ ModifierType | null, ModifierType | null, ModifierType | null, ModifierType | null, ModifierType | null ]; get_time(): number; get_touchpad_gesture_finger_count(): number; has_control_modifier(): boolean; has_shift_modifier(): boolean; is_pointer_emulated(): boolean; put(): void; set_button(button: number): void; set_coords(x: number, y: number): void; set_device(device?: InputDevice | null): void; set_device_tool(tool?: InputDeviceTool | null): void; set_flags(flags: EventFlags): void; set_key_code(key_code: number): void; set_key_symbol(key_sym: number): void; set_key_unicode(key_unicode: number): void; set_related(actor?: Actor | null): void; set_scroll_delta(dx: number, dy: number): void; set_scroll_direction(direction: ScrollDirection): void; set_source(actor?: Actor | null): void; set_source_device(device?: InputDevice | null): void; set_stage(stage?: Stage | null): void; set_state(state: ModifierType): void; set_time(time_: number): void; type(): EventType; static add_filter(stage: Stage | null, func: EventFilterFunc): number; static get(): Event; static peek(): Event; static remove_filter(id: number): void; } export interface AnimatableNamespace { $gtype: GObject.GType<Animatable>; prototype: AnimatablePrototype; } export type Animatable = AnimatablePrototype; export interface AnimatablePrototype extends GObject.Object { // Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; } export const Animatable: AnimatableNamespace; export interface ContainerNamespace { $gtype: GObject.GType<Container>; prototype: ContainerPrototype; class_find_child_property( klass: GObject.Object, property_name: string ): GObject.ParamSpec; class_list_child_properties(klass: GObject.Object): GObject.ParamSpec[]; } export type Container<A extends Actor = Actor> = ContainerPrototype<A>; export interface ContainerPrototype<A extends Actor = Actor> extends GObject.Object { // Members add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): ChildMeta; get_children(): A[]; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; } export const Container: ContainerNamespace; export interface ContentNamespace { $gtype: GObject.GType<Content>; prototype: ContentPrototype; } export type Content = ContentPrototype; export interface ContentPrototype extends GObject.Object { // Members get_preferred_size(): [boolean, number, number]; invalidate(): void; invalidate_size(): void; vfunc_attached(actor: Actor): void; vfunc_detached(actor: Actor): void; vfunc_get_preferred_size(): [boolean, number, number]; vfunc_invalidate(): void; vfunc_invalidate_size(): void; vfunc_paint_content( actor: Actor, node: PaintNode, paint_context: PaintContext ): void; } export const Content: ContentNamespace; export interface ScriptableNamespace { $gtype: GObject.GType<Scriptable>; prototype: ScriptablePrototype; } export type Scriptable = ScriptablePrototype; export interface ScriptablePrototype extends GObject.Object { // Members get_id(): string; parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property(script: Script, name: string, value: any): void; vfunc_set_id(id_: string): void; } export const Scriptable: ScriptableNamespace; export type Matrix = Cogl.Matrix;
the_stack
import * as React from 'react'; import { useState, useEffect, useRef, useCallback, useMemo } from 'react'; import flatten from 'lodash/flatten'; let Schema = require('async-validator'); Schema = Schema.default ? Schema.default : Schema; function validate<F>( { ...fieldsOptions }: { [N in keyof F]: GetFieldDecoratorOptions<F>; }, { ...values }: { [N in keyof F]?: F[N]; }, ns?: (keyof F)[] ) { return new Promise((resolve, reject) => { ns = ns || (Object.keys(fieldsOptions) as (keyof F)[]); const fieldsRule: { [N in keyof F]?: Validator<F>[]; } = {}; for (const name in fieldsOptions) { if (ns.includes(name)) { fieldsRule[name] = fieldsOptions[name].rules || [{ required: false }]; } } for (const name in values) { if (!ns.includes(name)) { delete values[name]; } } new Schema(fieldsRule).validate( values, ( errors: | { field: keyof F; message: string; }[] | null ) => { if (errors) { const errorsObj: { [N in keyof F]?: [{ message: string; field: keyof F }]; } = {}; for (const { field, message } of errors || []) { errorsObj[field] = [{ message, field }]; } reject({ errors: errorsObj, values }); } else { resolve(values); } } ); }); } export type TypeValues<V> = { [N in keyof V]?: V[N]; }; export type TypeErrors<V> = { [N in keyof V]?: { message: string; field: keyof V; }[]; }; type triggerFn = (...arg: any[]) => void; function useForm<V = any>( createOptions: CreateOptions<V> = {} ): FormMethods<V> { const cacheData = useRef<{ fieldsTouched: { /** * `undefined` means `false` here */ [N in keyof V]?: true; }; fieldsValidated: { [N in keyof V]?: true; }; fieldsTrigger: { [N in keyof V]?: triggerFn; }; currentField?: keyof V; }>({ fieldsTouched: {}, fieldsValidated: {}, fieldsTrigger: {} }); const fieldsOptions = useRef< { [N in keyof V]: GetFieldDecoratorOptions<V>; } >({} as any); const [errors, setErrors] = useState<TypeErrors<V>>({}); const [values, setValues] = useState<TypeValues<V>>({}); const valuesRef = useRef(values); useEffect(() => { valuesRef.current = values; }, [values]); const [fieldsValidating, setFieldsValidating] = useState< { [N in keyof V]: { validating: boolean; value: any; }; } >({} as any); const fieldsValidatingRef = useRef(fieldsValidating); useEffect(() => { const { current: { fieldsTouched: fieldsChanged, currentField } } = cacheData; if (currentField === undefined || !fieldsChanged[currentField]) { return; } const fieldsValidating = fieldsValidatingRef.current; fieldsValidating[currentField] = { validating: true, value: values[currentField] }; async function validateCurrentField() { if (currentField === undefined || !fieldsChanged[currentField]) { return; } try { await validate(fieldsOptions.current, values, [currentField]); setErrors(errors => { const errs = { ...errors }; delete errs[currentField]; return errs; }); } catch ({ errors: newErrors }) { setErrors(oldErrors => ({ ...oldErrors, ...newErrors })); } finally { if (values[currentField] === fieldsValidating[currentField].value) { fieldsValidating[currentField].validating = false; } setFieldsValidating({ ...fieldsValidating }); delete cacheData.current.currentField; } } setFieldsValidating({ ...fieldsValidating }); validateCurrentField(); }, [values, fieldsOptions]); const getFieldProps = useCallback( ( name: keyof V | (keyof V)[], options: GetFieldDecoratorOptions<V> = {} ) => { const n = name instanceof Array ? name[0] : name; const { trigger = 'onChange', valuePropName = 'value', normalize = (e: any) => (e && e.target ? e.target[valuePropName] : e) } = fieldsOptions.current[n]; const props: any = { [trigger]: (...arg: any) => { const value = normalize(...arg); setValues(oldValues => { const currentValue: { [N in keyof V]?: V[N] } = {}; if (name instanceof Array && value instanceof Array) { name.forEach((n, index) => (currentValue[n] = value[index])); } else { currentValue[n] = value; } // eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion const values = { ...oldValues, ...currentValue } as typeof oldValues; const { current } = cacheData; current.currentField = n; current.fieldsTouched[n] = true; if (createOptions.onValuesChange) { createOptions.onValuesChange( // eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion { [n]: value } as typeof values, values ); } valuesRef.current = values; return values; }); }, 'data-__field': { errors: errors[n], value: values[n], validating: fieldsValidating[name instanceof Array ? name[0] : name].validating }, 'data-__meta': { validate: [ { rules: options.rules } ] } }; if (name instanceof Array) { const value: any = []; name.forEach(n => { value.push(values[n]); }); props[valuePropName] = value; } else { props[valuePropName] = values[name] as any; } return props; }, [values, createOptions, errors, fieldsValidating] ); const objFilter = useCallback( (obj: { [N in keyof V]?: any }, ns?: (keyof V)[]) => { if (ns) { (Object.keys(obj) as (keyof V)[]).forEach(name => { if (!ns.includes(name)) { delete obj[name]; } }); } return obj; }, [] ); const resetFields = useCallback((ns?: (keyof V)[]) => { const { current } = cacheData; delete current.currentField; if (!ns) { setValues(() => ({})); setErrors(() => ({})); Object.keys(current).forEach(name => (current[name] = {})); } else { ns.forEach(name => { delete current.fieldsTouched[name]; setValues( values => ({ ...values, [name]: undefined } as typeof values) ); setErrors(oldErrors => { const errors = { ...oldErrors }; delete errors[name]; return errors; }); }); } }, []); const validateFields = useCallback( (ns?: (keyof V)[], options = {}): Promise<V> => new Promise(async (resolve, reject) => { const { fieldsValidated } = cacheData.current; if (ns) { ns.forEach(name => { fieldsValidated[name] = true; }); } if (options.force) { Object.keys(fieldsValidated).forEach(name => { if (fieldsValidated[name]) { delete errors[name]; } }); } validate(fieldsOptions.current, valuesRef.current, ns) .then(values => resolve(values as V)) .catch(a => { const { errors: newErrors } = a; setErrors(errors => ({ ...errors, ...newErrors })); reject(newErrors[Object.keys(newErrors)[0]][0]); }); }), [errors] ); const reRenderRef = useRef(true); reRenderRef.current = true; const getFieldDecorator = useCallback( ( name, options = { rules: [{ required: false }] } ) => { if (reRenderRef.current) { fieldsOptions.current = {} as any; reRenderRef.current = false; } const setOptions = (name: keyof V, index?: number) => { fieldsOptions.current[name] = options; values[name] = values[name] !== undefined || cacheData.current.fieldsTouched[name] ? values[name] : index !== undefined ? (options.initialValue || [])[index] : options.initialValue; if (!fieldsValidating[name]) { fieldsValidating[name] = { validating: false, value: values[name] }; } }; valuesRef.current = values; if (name instanceof Array) { name.forEach((n, i) => setOptions(n, i)); } else { setOptions(name as keyof V); } const props: any = getFieldProps(name, options); return (fieldElem: React.ReactElement) => { const { trigger = 'onChange' } = options; let triggerFn = (cacheData as any).current.fieldsTrigger[name]; if (!triggerFn && cacheData) { triggerFn = cacheData.current.fieldsTrigger[name] = (...arg: any) => { if ((fieldElem.props as any)[trigger]) { (fieldElem.props as any)[trigger](...arg); } props[trigger](...arg); }; } return React.cloneElement(fieldElem, { ...fieldElem.props, ...props, [trigger]: triggerFn } as any); }; }, [fieldsValidating, values, getFieldProps] ); const setFieldsValue = useCallback( ({ ...newValues }) => setValues(oldValues => { const values = { ...oldValues, ...newValues }; valuesRef.current = values; return values; }), [] ); const getFieldsValue = useCallback( ns => { const result = { ...valuesRef.current }; objFilter(result, ns); return result; }, [objFilter] ); const getFieldValue = useCallback(name => valuesRef.current[name], []); const getFieldsError = useCallback( ns => { const result = { ...errors }; objFilter(result, ns); return result; }, [errors, objFilter] ); const getFieldError = useCallback((name): any => errors[name] || [], [ errors ]); const setFields = useCallback(fields => { setValues(oldValues => { const values = { ...oldValues }; for (const name in fields) { const { value } = fields[name]; values[name] = value; } return values; }); setErrors(oldErrors => { const errors = { ...oldErrors }; for (const name in fields) { const errorArr = fields[name].errors || []; errors[name] = errorArr.map(({ message }: any) => ({ message, field: name })); } return errors; }); }, []); const isFieldTouched = useCallback( name => Boolean(cacheData.current.fieldsTouched[name]), [] ); const isFieldsTouched = useCallback( (names: (keyof V)[] = []) => names.some(x => Boolean(cacheData.current.fieldsTouched[x])), [] ); const isFieldValidating = useCallback( name => fieldsValidating[name].validating, [fieldsValidating] ); const errorsArr = useMemo( () => flatten(Object.keys(errors).map(key => errors[key] || [])), [errors] ); return { errors, errorsArr, values, resetFields, validateFields, getFieldDecorator, setFieldsValue, getFieldsValue, getFieldValue, getFieldsError, getFieldError, setFields, isFieldTouched, isFieldsTouched, isFieldValidating }; } export interface CreateOptions<V> { onValuesChange?: ( changedValues: TypeValues<V>, allValues: TypeValues<V> ) => void; } export interface FormMethods<V> { errors: TypeErrors<V>; errorsArr: { message: string; field: keyof V; }[]; values: TypeValues<V>; validateFields: ( ns?: (keyof V)[], options?: ValidateFieldsOptions ) => Promise<V>; resetFields: (ns?: (keyof V)[]) => void; getFieldDecorator: < P extends React.InputHTMLAttributes<React.ReactElement<P>> >( name: keyof V | (keyof V)[], options?: GetFieldDecoratorOptions<V> ) => (element: React.ReactElement<P>) => React.ReactElement<P>; setFieldsValue: ( values: { [N in keyof V]?: V[N]; } ) => void; getFieldsValue: (ns?: (keyof V)[]) => TypeValues<V>; getFieldsError: ( ns?: (keyof V)[] ) => { [N in keyof V]?: { message: string; field: keyof V; }[]; }; getFieldValue: (name: keyof V) => V[keyof V] | undefined; getFieldError: ( name: keyof V ) => { message: string; field: keyof V; }[]; setFields: ( fields: { [N in keyof V]?: { value?: V[N]; errors?: Error[]; }; } ) => void; isFieldTouched(name: keyof V): boolean; isFieldsTouched(names?: (keyof V)[]): boolean; isFieldValidating(name?: keyof V): boolean; } export interface GetFieldDecoratorOptions<V> { rules?: Validator<V>[]; initialValue?: any; trigger?: string; valuePropName?: string; normalize?: (...arg: any) => any; } /** * come from: https://github.com/ant-design/ant-design/blob/master/components/form/Form.tsx */ interface Validator<V> { /** validation error message */ message?: React.ReactNode; /** built-in validation type, available options: https://github.com/yiminghe/async-validator#type */ type?: string; /** indicates whether field is required */ required?: boolean; /** treat required fields that only contain whitespace as errors */ whitespace?: boolean; /** validate the exact length of a field */ len?: number; /** validate the min length of a field */ min?: number; /** validate the max length of a field */ max?: number; /** validate the value from a list of possible values */ enum?: string | string[]; /** validate from a regular expression */ pattern?: RegExp; /** transform a value before validation */ transform?: (value: V) => V; /** custom validate function (Note: callback must be called) */ validator?: ( rule: Validator<V>, value: any, callback: any, source?: any, options?: any ) => any; } export interface FormComponentProps<V> { form: FormMethods<V>; } export interface ValidateFieldsOptions { /** 所有表单域是否在第一个校验规则失败后停止继续校验 */ // first?: boolean; /** 指定哪些表单域在第一个校验规则失败后停止继续校验 */ // firstFields?: string[]; /** 已经校验过的表单域,在 validateTrigger 再次被触发时是否再次校验 */ force?: boolean; /** 定义 validateFieldsAndScroll 的滚动行为 */ // scroll?: DomScrollIntoViewConfig; } export default useForm;
the_stack
import { ValueCell } from '../../../mol-util'; import { Mat4, Vec3, Vec4 } from '../../../mol-math/linear-algebra'; import { transformPositionArray, GroupMapping, createGroupMapping } from '../../util'; import { GeometryUtils } from '../geometry'; import { createColors } from '../color-data'; import { createMarkers } from '../marker-data'; import { createSizes } from '../size-data'; import { TransformData } from '../transform-data'; import { LocationIterator, PositionLocation } from '../../util/location-iterator'; import { LinesValues } from '../../../mol-gl/renderable/lines'; import { Mesh } from '../mesh/mesh'; import { LinesBuilder } from './lines-builder'; import { ParamDefinition as PD } from '../../../mol-util/param-definition'; import { calculateInvariantBoundingSphere, calculateTransformBoundingSphere } from '../../../mol-gl/renderable/util'; import { Sphere3D } from '../../../mol-math/geometry'; import { Theme } from '../../../mol-theme/theme'; import { Color } from '../../../mol-util/color'; import { BaseGeometry } from '../base'; import { createEmptyOverpaint } from '../overpaint-data'; import { createEmptyTransparency } from '../transparency-data'; import { hashFnv32a } from '../../../mol-data/util'; import { createEmptyClipping } from '../clipping-data'; /** Wide line */ export interface Lines { readonly kind: 'lines', /** Number of lines */ lineCount: number, /** Mapping buffer as array of xy values wrapped in a value cell */ readonly mappingBuffer: ValueCell<Float32Array>, /** Index buffer as array of vertex index triplets wrapped in a value cell */ readonly indexBuffer: ValueCell<Uint32Array>, /** Group buffer as array of group ids for each vertex wrapped in a value cell */ readonly groupBuffer: ValueCell<Float32Array>, /** Line start buffer as array of xyz values wrapped in a value cell */ readonly startBuffer: ValueCell<Float32Array>, /** Line end buffer as array of xyz values wrapped in a value cell */ readonly endBuffer: ValueCell<Float32Array>, /** Bounding sphere of the lines */ readonly boundingSphere: Sphere3D /** Maps group ids to line indices */ readonly groupMapping: GroupMapping setBoundingSphere(boundingSphere: Sphere3D): void } export namespace Lines { export function create(mappings: Float32Array, indices: Uint32Array, groups: Float32Array, starts: Float32Array, ends: Float32Array, lineCount: number, lines?: Lines): Lines { return lines ? update(mappings, indices, groups, starts, ends, lineCount, lines) : fromArrays(mappings, indices, groups, starts, ends, lineCount); } export function createEmpty(lines?: Lines): Lines { const mb = lines ? lines.mappingBuffer.ref.value : new Float32Array(0); const ib = lines ? lines.indexBuffer.ref.value : new Uint32Array(0); const gb = lines ? lines.groupBuffer.ref.value : new Float32Array(0); const sb = lines ? lines.startBuffer.ref.value : new Float32Array(0); const eb = lines ? lines.endBuffer.ref.value : new Float32Array(0); return create(mb, ib, gb, sb, eb, 0, lines); } export function fromMesh(mesh: Mesh, lines?: Lines) { const vb = mesh.vertexBuffer.ref.value; const ib = mesh.indexBuffer.ref.value; const gb = mesh.groupBuffer.ref.value; const builder = LinesBuilder.create(mesh.triangleCount * 3, mesh.triangleCount / 10, lines); // TODO avoid duplicate lines for (let i = 0, il = mesh.triangleCount * 3; i < il; i += 3) { const i0 = ib[i], i1 = ib[i + 1], i2 = ib[i + 2]; const x0 = vb[i0 * 3], y0 = vb[i0 * 3 + 1], z0 = vb[i0 * 3 + 2]; const x1 = vb[i1 * 3], y1 = vb[i1 * 3 + 1], z1 = vb[i1 * 3 + 2]; const x2 = vb[i2 * 3], y2 = vb[i2 * 3 + 1], z2 = vb[i2 * 3 + 2]; builder.add(x0, y0, z0, x1, y1, z1, gb[i0]); builder.add(x0, y0, z0, x2, y2, z2, gb[i0]); builder.add(x1, y1, z1, x2, y2, z2, gb[i1]); } return builder.getLines(); } function hashCode(lines: Lines) { return hashFnv32a([ lines.lineCount, lines.mappingBuffer.ref.version, lines.indexBuffer.ref.version, lines.groupBuffer.ref.version, lines.startBuffer.ref.version, lines.endBuffer.ref.version ]); } function fromArrays(mappings: Float32Array, indices: Uint32Array, groups: Float32Array, starts: Float32Array, ends: Float32Array, lineCount: number): Lines { const boundingSphere = Sphere3D(); let groupMapping: GroupMapping; let currentHash = -1; let currentGroup = -1; const lines = { kind: 'lines' as const, lineCount, mappingBuffer: ValueCell.create(mappings), indexBuffer: ValueCell.create(indices), groupBuffer: ValueCell.create(groups), startBuffer: ValueCell.create(starts), endBuffer: ValueCell.create(ends), get boundingSphere() { const newHash = hashCode(lines); if (newHash !== currentHash) { const s = calculateInvariantBoundingSphere(lines.startBuffer.ref.value, lines.lineCount * 4, 4); const e = calculateInvariantBoundingSphere(lines.endBuffer.ref.value, lines.lineCount * 4, 4); Sphere3D.expandBySphere(boundingSphere, s, e); currentHash = newHash; } return boundingSphere; }, get groupMapping() { if (lines.groupBuffer.ref.version !== currentGroup) { groupMapping = createGroupMapping(lines.groupBuffer.ref.value, lines.lineCount, 4); currentGroup = lines.groupBuffer.ref.version; } return groupMapping; }, setBoundingSphere(sphere: Sphere3D) { Sphere3D.copy(boundingSphere, sphere); currentHash = hashCode(lines); } }; return lines; } function update(mappings: Float32Array, indices: Uint32Array, groups: Float32Array, starts: Float32Array, ends: Float32Array, lineCount: number, lines: Lines) { if (lineCount > lines.lineCount) { ValueCell.update(lines.mappingBuffer, mappings); ValueCell.update(lines.indexBuffer, indices); } lines.lineCount = lineCount; ValueCell.update(lines.groupBuffer, groups); ValueCell.update(lines.startBuffer, starts); ValueCell.update(lines.endBuffer, ends); return lines; } export function transform(lines: Lines, t: Mat4) { const start = lines.startBuffer.ref.value; transformPositionArray(t, start, 0, lines.lineCount * 4); ValueCell.update(lines.startBuffer, start); const end = lines.endBuffer.ref.value; transformPositionArray(t, end, 0, lines.lineCount * 4); ValueCell.update(lines.endBuffer, end); } // export const Params = { ...BaseGeometry.Params, sizeFactor: PD.Numeric(3, { min: 0, max: 10, step: 0.1 }), lineSizeAttenuation: PD.Boolean(false), }; export type Params = typeof Params export const Utils: GeometryUtils<Lines, Params> = { Params, createEmpty, createValues, createValuesSimple, updateValues, updateBoundingSphere, createRenderableState: BaseGeometry.createRenderableState, updateRenderableState: BaseGeometry.updateRenderableState, createPositionIterator }; function createPositionIterator(lines: Lines, transform: TransformData): LocationIterator { const groupCount = lines.lineCount * 4; const instanceCount = transform.instanceCount.ref.value; const location = PositionLocation(); const p = location.position; const s = lines.startBuffer.ref.value; const e = lines.endBuffer.ref.value; const m = transform.aTransform.ref.value; const getLocation = (groupIndex: number, instanceIndex: number) => { const v = groupIndex % 4 === 0 ? s : e; if (instanceIndex < 0) { Vec3.fromArray(p, v, groupIndex * 3); } else { Vec3.transformMat4Offset(p, v, m, 0, groupIndex * 3, instanceIndex * 16); } return location; }; return LocationIterator(groupCount, instanceCount, 2, getLocation); } function createValues(lines: Lines, transform: TransformData, locationIt: LocationIterator, theme: Theme, props: PD.Values<Params>): LinesValues { const { instanceCount, groupCount } = locationIt; const positionIt = createPositionIterator(lines, transform); const color = createColors(locationIt, positionIt, theme.color); const size = createSizes(locationIt, theme.size); const marker = createMarkers(instanceCount * groupCount); const overpaint = createEmptyOverpaint(); const transparency = createEmptyTransparency(); const clipping = createEmptyClipping(); const counts = { drawCount: lines.lineCount * 2 * 3, vertexCount: lines.lineCount * 4, groupCount, instanceCount }; const invariantBoundingSphere = Sphere3D.clone(lines.boundingSphere); const boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount); return { aMapping: lines.mappingBuffer, aGroup: lines.groupBuffer, aStart: lines.startBuffer, aEnd: lines.endBuffer, elements: lines.indexBuffer, boundingSphere: ValueCell.create(boundingSphere), invariantBoundingSphere: ValueCell.create(invariantBoundingSphere), uInvariantBoundingSphere: ValueCell.create(Vec4.ofSphere(invariantBoundingSphere)), ...color, ...size, ...marker, ...overpaint, ...transparency, ...clipping, ...transform, ...BaseGeometry.createValues(props, counts), uSizeFactor: ValueCell.create(props.sizeFactor), dLineSizeAttenuation: ValueCell.create(props.lineSizeAttenuation), dDoubleSided: ValueCell.create(true), dFlipSided: ValueCell.create(false), }; } function createValuesSimple(lines: Lines, props: Partial<PD.Values<Params>>, colorValue: Color, sizeValue: number, transform?: TransformData) { const s = BaseGeometry.createSimple(colorValue, sizeValue, transform); const p = { ...PD.getDefaultValues(Params), ...props }; return createValues(lines, s.transform, s.locationIterator, s.theme, p); } function updateValues(values: LinesValues, props: PD.Values<Params>) { BaseGeometry.updateValues(values, props); ValueCell.updateIfChanged(values.uSizeFactor, props.sizeFactor); ValueCell.updateIfChanged(values.dLineSizeAttenuation, props.lineSizeAttenuation); } function updateBoundingSphere(values: LinesValues, lines: Lines) { const invariantBoundingSphere = Sphere3D.clone(lines.boundingSphere); const boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value); if (!Sphere3D.equals(boundingSphere, values.boundingSphere.ref.value)) { ValueCell.update(values.boundingSphere, boundingSphere); } if (!Sphere3D.equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) { ValueCell.update(values.invariantBoundingSphere, invariantBoundingSphere); ValueCell.update(values.uInvariantBoundingSphere, Vec4.fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere)); } } }
the_stack
import { AttributeContextExpectedValue, AttributeExpectedValue } from '../../Utilities/ObjectValidator'; import { CommonTest } from './CommonTest'; // tslint:disable:max-func-body-length // tslint:disable:variable-name describe('Cdm.ResolutionGuidanceFilterOut', () => { /** * Resolution Guidance Test - FilterOut - Some */ it('TestFilterOutSome', async (done) => { const testName: string = 'TestFilterOutSome'; { const entityName: string = 'Employee'; const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expected_default: AttributeExpectedValue[] = []; const expected_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly: AttributeExpectedValue[] = []; const expected_structured: AttributeExpectedValue[] = []; const expected_normalized_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = []; await CommonTest.runTestWithValues( testName, entityName, expectedContext_default, expectedContext_normalized, expectedContext_referenceOnly, expectedContext_structured, expectedContext_normalized_structured, expectedContext_referenceOnly_normalized, expectedContext_referenceOnly_structured, expectedContext_referenceOnly_normalized_structured, expected_default, expected_normalized, expected_referenceOnly, expected_structured, expected_normalized_structured, expected_referenceOnly_normalized, expected_referenceOnly_structured, expected_referenceOnly_normalized_structured ); } { const entityName: string = 'EmployeeNames'; const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expected_default: AttributeExpectedValue[] = []; const expected_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly: AttributeExpectedValue[] = []; const expected_structured: AttributeExpectedValue[] = []; const expected_normalized_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = []; await CommonTest.runTestWithValues( testName, entityName, expectedContext_default, expectedContext_normalized, expectedContext_referenceOnly, expectedContext_structured, expectedContext_normalized_structured, expectedContext_referenceOnly_normalized, expectedContext_referenceOnly_structured, expectedContext_referenceOnly_normalized_structured, expected_default, expected_normalized, expected_referenceOnly, expected_structured, expected_normalized_structured, expected_referenceOnly_normalized, expected_referenceOnly_structured, expected_referenceOnly_normalized_structured ); } done(); }); /** * Resolution Guidance Test - FilterOut - Some With AttributeGroupRef */ it('TestFilterOutSomeWithAttributeGroupRef', async (done) => { const testName: string = 'TestFilterOutSomeWithAttributeGroupRef'; { const entityName: string = 'Employee'; const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expected_default: AttributeExpectedValue[] = []; const expected_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly: AttributeExpectedValue[] = []; const expected_structured: AttributeExpectedValue[] = []; const expected_normalized_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = []; await CommonTest.runTestWithValues( testName, entityName, expectedContext_default, expectedContext_normalized, expectedContext_referenceOnly, expectedContext_structured, expectedContext_normalized_structured, expectedContext_referenceOnly_normalized, expectedContext_referenceOnly_structured, expectedContext_referenceOnly_normalized_structured, expected_default, expected_normalized, expected_referenceOnly, expected_structured, expected_normalized_structured, expected_referenceOnly_normalized, expected_referenceOnly_structured, expected_referenceOnly_normalized_structured ); } { const entityName: string = 'EmployeeNames'; const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expected_default: AttributeExpectedValue[] = []; const expected_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly: AttributeExpectedValue[] = []; const expected_structured: AttributeExpectedValue[] = []; const expected_normalized_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = []; await CommonTest.runTestWithValues( testName, entityName, expectedContext_default, expectedContext_normalized, expectedContext_referenceOnly, expectedContext_structured, expectedContext_normalized_structured, expectedContext_referenceOnly_normalized, expectedContext_referenceOnly_structured, expectedContext_referenceOnly_normalized_structured, expected_default, expected_normalized, expected_referenceOnly, expected_structured, expected_normalized_structured, expected_referenceOnly_normalized, expected_referenceOnly_structured, expected_referenceOnly_normalized_structured ); } done(); }); /** * Resolution Guidance Test - FilterOut - All */ it('TestFilterOutAll', async (done) => { const testName: string = 'TestFilterOutAll'; { const entityName: string = 'Employee'; const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expected_default: AttributeExpectedValue[] = []; const expected_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly: AttributeExpectedValue[] = []; const expected_structured: AttributeExpectedValue[] = []; const expected_normalized_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = []; await CommonTest.runTestWithValues( testName, entityName, expectedContext_default, expectedContext_normalized, expectedContext_referenceOnly, expectedContext_structured, expectedContext_normalized_structured, expectedContext_referenceOnly_normalized, expectedContext_referenceOnly_structured, expectedContext_referenceOnly_normalized_structured, expected_default, expected_normalized, expected_referenceOnly, expected_structured, expected_normalized_structured, expected_referenceOnly_normalized, expected_referenceOnly_structured, expected_referenceOnly_normalized_structured ); } { const entityName: string = 'EmployeeNames'; const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expected_default: AttributeExpectedValue[] = []; const expected_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly: AttributeExpectedValue[] = []; const expected_structured: AttributeExpectedValue[] = []; const expected_normalized_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = []; await CommonTest.runTestWithValues( testName, entityName, expectedContext_default, expectedContext_normalized, expectedContext_referenceOnly, expectedContext_structured, expectedContext_normalized_structured, expectedContext_referenceOnly_normalized, expectedContext_referenceOnly_structured, expectedContext_referenceOnly_normalized_structured, expected_default, expected_normalized, expected_referenceOnly, expected_structured, expected_normalized_structured, expected_referenceOnly_normalized, expected_referenceOnly_structured, expected_referenceOnly_normalized_structured ); } done(); }); /** * Resolution Guidance Test - FilterOut - All With AttributeGroupRef */ it('TestFilterOutAllWithAttributeGroupRef', async (done) => { const testName: string = 'TestFilterOutAllWithAttributeGroupRef'; { const entityName: string = 'Employee'; const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expected_default: AttributeExpectedValue[] = []; const expected_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly: AttributeExpectedValue[] = []; const expected_structured: AttributeExpectedValue[] = []; const expected_normalized_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = []; await CommonTest.runTestWithValues( testName, entityName, expectedContext_default, expectedContext_normalized, expectedContext_referenceOnly, expectedContext_structured, expectedContext_normalized_structured, expectedContext_referenceOnly_normalized, expectedContext_referenceOnly_structured, expectedContext_referenceOnly_normalized_structured, expected_default, expected_normalized, expected_referenceOnly, expected_structured, expected_normalized_structured, expected_referenceOnly_normalized, expected_referenceOnly_structured, expected_referenceOnly_normalized_structured ); } { const entityName: string = 'EmployeeNames'; const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue(); const expected_default: AttributeExpectedValue[] = []; const expected_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly: AttributeExpectedValue[] = []; const expected_structured: AttributeExpectedValue[] = []; const expected_normalized_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized: AttributeExpectedValue[] = []; const expected_referenceOnly_structured: AttributeExpectedValue[] = []; const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = []; await CommonTest.runTestWithValues( testName, entityName, expectedContext_default, expectedContext_normalized, expectedContext_referenceOnly, expectedContext_structured, expectedContext_normalized_structured, expectedContext_referenceOnly_normalized, expectedContext_referenceOnly_structured, expectedContext_referenceOnly_normalized_structured, expected_default, expected_normalized, expected_referenceOnly, expected_structured, expected_normalized_structured, expected_referenceOnly_normalized, expected_referenceOnly_structured, expected_referenceOnly_normalized_structured ); } done(); }); });
the_stack
import { DIRECTION, DIRECTION_MASK, } from './Constants'; import Point from '../view/geometry/Point'; import Rectangle from '../view/geometry/Rectangle'; import CellState from '../view/cell/CellState'; import type { CellStateStyles } from '../types'; import { getValue, isNullish } from './Utils'; /** * Converts the given degree to radians. */ export const toRadians = (deg: number) => { return (Math.PI * deg) / 180; }; /** * Converts the given radians to degree. */ export const toDegree = (rad: number) => { return (rad * 180) / Math.PI; }; /** * Converts the given arc to a series of curves. */ export const arcToCurves = ( x0: number, y0: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean, x: number, y: number ) => { x -= x0; y -= y0; if (r1 === 0 || r2 === 0) { return []; } const fS = sweepFlag; const psai = angle; r1 = Math.abs(r1); r2 = Math.abs(r2); const ctx = -x / 2; const cty = -y / 2; const cpsi = Math.cos((psai * Math.PI) / 180); const spsi = Math.sin((psai * Math.PI) / 180); const rxd = cpsi * ctx + spsi * cty; const ryd = -1 * spsi * ctx + cpsi * cty; const rxdd = rxd * rxd; const rydd = ryd * ryd; const r1x = r1 * r1; const r2y = r2 * r2; const lamda = rxdd / r1x + rydd / r2y; let sds; if (lamda > 1) { r1 = Math.sqrt(lamda) * r1; r2 = Math.sqrt(lamda) * r2; sds = 0; } else { let seif = 1; if (largeArcFlag === fS) { seif = -1; } sds = seif * Math.sqrt((r1x * r2y - r1x * rydd - r2y * rxdd) / (r1x * rydd + r2y * rxdd)); } const txd = (sds * r1 * ryd) / r2; const tyd = (-1 * sds * r2 * rxd) / r1; const tx = cpsi * txd - spsi * tyd + x / 2; const ty = spsi * txd + cpsi * tyd + y / 2; let rad = Math.atan2((ryd - tyd) / r2, (rxd - txd) / r1) - Math.atan2(0, 1); let s1 = rad >= 0 ? rad : 2 * Math.PI + rad; rad = Math.atan2((-ryd - tyd) / r2, (-rxd - txd) / r1) - Math.atan2((ryd - tyd) / r2, (rxd - txd) / r1); let dr = rad >= 0 ? rad : 2 * Math.PI + rad; if (!fS && dr > 0) { dr -= 2 * Math.PI; } else if (fS && dr < 0) { dr += 2 * Math.PI; } const sse = (dr * 2) / Math.PI; const seg = Math.ceil(sse < 0 ? -1 * sse : sse); const segr = dr / seg; const t = ((8 / 3) * Math.sin(segr / 4) * Math.sin(segr / 4)) / Math.sin(segr / 2); const cpsir1 = cpsi * r1; const cpsir2 = cpsi * r2; const spsir1 = spsi * r1; const spsir2 = spsi * r2; let mc = Math.cos(s1); let ms = Math.sin(s1); let x2 = -t * (cpsir1 * ms + spsir2 * mc); let y2 = -t * (spsir1 * ms - cpsir2 * mc); let x3 = 0; let y3 = 0; let result = []; for (let n = 0; n < seg; ++n) { s1 += segr; mc = Math.cos(s1); ms = Math.sin(s1); x3 = cpsir1 * mc - spsir2 * ms + tx; y3 = spsir1 * mc + cpsir2 * ms + ty; const dx = -t * (cpsir1 * ms + spsir2 * mc); const dy = -t * (spsir1 * ms - cpsir2 * mc); // CurveTo updates x0, y0 so need to restore it const index = n * 6; result[index] = Number(x2 + x0); result[index + 1] = Number(y2 + y0); result[index + 2] = Number(x3 - dx + x0); result[index + 3] = Number(y3 - dy + y0); result[index + 4] = Number(x3 + x0); result[index + 5] = Number(y3 + y0); x2 = x3 + dx; y2 = y3 + dy; } return result; }; /** * Returns the bounding box for the rotated rectangle. * * @param rect {@link Rectangle} to be rotated. * @param angle Number that represents the angle (in degrees). * @param cx Optional {@link Point} that represents the rotation center. If no * rotation center is given then the center of rect is used. */ export const getBoundingBox = ( rect: Rectangle | null, rotation: number, cx: Point | null = null ) => { let result = null; if (rect && rotation !== 0) { const rad = toRadians(rotation); const cos = Math.cos(rad); const sin = Math.sin(rad); cx = cx != null ? cx : new Point(rect.x + rect.width / 2, rect.y + rect.height / 2); let p1 = new Point(rect.x, rect.y); let p2 = new Point(rect.x + rect.width, rect.y); let p3 = new Point(p2.x, rect.y + rect.height); let p4 = new Point(rect.x, p3.y); p1 = getRotatedPoint(p1, cos, sin, cx); p2 = getRotatedPoint(p2, cos, sin, cx); p3 = getRotatedPoint(p3, cos, sin, cx); p4 = getRotatedPoint(p4, cos, sin, cx); result = new Rectangle(p1.x, p1.y, 0, 0); result.add(new Rectangle(p2.x, p2.y, 0, 0)); result.add(new Rectangle(p3.x, p3.y, 0, 0)); result.add(new Rectangle(p4.x, p4.y, 0, 0)); } return result; }; /** * Rotates the given point by the given cos and sin. */ export const getRotatedPoint = (pt: Point, cos: number, sin: number, c = new Point()) => { const x = pt.x - c.x; const y = pt.y - c.y; const x1 = x * cos - y * sin; const y1 = y * cos + x * sin; return new Point(x1 + c.x, y1 + c.y); }; /** * Returns an integer mask of the port constraints of the given map * @param dict the style map to determine the port constraints for * @param defaultValue Default value to return if the key is undefined. * @return the mask of port constraint directions * * @param terminal {@link CelState} that represents the terminal. * @param edge <CellState> that represents the edge. * @param source Boolean that specifies if the terminal is the source terminal. * @param defaultValue Default value to be returned. */ export const getPortConstraints = ( terminal: CellState, edge: CellState, source: boolean, defaultValue: any ) => { const value = getValue( terminal.style, 'portConstraint', getValue(edge.style, source ? 'sourcePortConstraint' : 'targetPortConstraint', null) ); if (isNullish(value)) { return defaultValue; } const directions = value.toString(); let returnValue = DIRECTION_MASK.NONE; const constraintRotationEnabled = getValue(terminal.style, 'portConstraintRotation', 0); let rotation = 0; if (constraintRotationEnabled == 1) { rotation = terminal.style.rotation ?? 0; } let quad = 0; if (rotation > 45) { quad = 1; if (rotation >= 135) { quad = 2; } } else if (rotation < -45) { quad = 3; if (rotation <= -135) { quad = 2; } } if (directions.indexOf(DIRECTION.NORTH) >= 0) { switch (quad) { case 0: returnValue |= DIRECTION_MASK.NORTH; break; case 1: returnValue |= DIRECTION_MASK.EAST; break; case 2: returnValue |= DIRECTION_MASK.SOUTH; break; case 3: returnValue |= DIRECTION_MASK.WEST; break; } } if (directions.indexOf(DIRECTION.WEST) >= 0) { switch (quad) { case 0: returnValue |= DIRECTION_MASK.WEST; break; case 1: returnValue |= DIRECTION_MASK.NORTH; break; case 2: returnValue |= DIRECTION_MASK.EAST; break; case 3: returnValue |= DIRECTION_MASK.SOUTH; break; } } if (directions.indexOf(DIRECTION.SOUTH) >= 0) { switch (quad) { case 0: returnValue |= DIRECTION_MASK.SOUTH; break; case 1: returnValue |= DIRECTION_MASK.WEST; break; case 2: returnValue |= DIRECTION_MASK.NORTH; break; case 3: returnValue |= DIRECTION_MASK.EAST; break; } } if (directions.indexOf(DIRECTION.EAST) >= 0) { switch (quad) { case 0: returnValue |= DIRECTION_MASK.EAST; break; case 1: returnValue |= DIRECTION_MASK.SOUTH; break; case 2: returnValue |= DIRECTION_MASK.WEST; break; case 3: returnValue |= DIRECTION_MASK.NORTH; break; } } return returnValue; }; /** * Reverse the port constraint bitmask. For example, north | east * becomes south | west */ export const reversePortConstraints = (constraint: number) => { let result = 0; result = (constraint & DIRECTION_MASK.WEST) << 3; result |= (constraint & DIRECTION_MASK.NORTH) << 1; result |= (constraint & DIRECTION_MASK.SOUTH) >> 1; result |= (constraint & DIRECTION_MASK.EAST) >> 3; return result; }; /** * Finds the index of the nearest segment on the given cell state for * the specified coordinate pair. */ export const findNearestSegment = (state: CellState, x: number, y: number) => { let index = -1; if (state.absolutePoints.length > 0) { let last = state.absolutePoints[0]; let min = null; for (let i = 1; i < state.absolutePoints.length; i += 1) { const current = state.absolutePoints[i]; if (!last || !current) continue; const dist = ptSegDistSq(last.x, last.y, current.x, current.y, x, y); if (min == null || dist < min) { min = dist; index = i - 1; } last = current; } } return index; }; /** * Adds the given margins to the given rectangle and rotates and flips the * rectangle according to the respective styles in style. */ export const getDirectedBounds = ( rect: Rectangle, m: Rectangle, style: CellStateStyles | null, flipH: boolean, flipV: boolean ) => { const d = getValue(style, 'direction', DIRECTION.EAST); flipH = flipH != null ? flipH : getValue(style, 'flipH', false); flipV = flipV != null ? flipV : getValue(style, 'flipV', false); m.x = Math.round(Math.max(0, Math.min(rect.width, m.x))); m.y = Math.round(Math.max(0, Math.min(rect.height, m.y))); m.width = Math.round(Math.max(0, Math.min(rect.width, m.width))); m.height = Math.round(Math.max(0, Math.min(rect.height, m.height))); if ( (flipV && (d === DIRECTION.SOUTH || d === DIRECTION.NORTH)) || (flipH && (d === DIRECTION.EAST || d === DIRECTION.WEST)) ) { const tmp = m.x; m.x = m.width; m.width = tmp; } if ( (flipH && (d === DIRECTION.SOUTH || d === DIRECTION.NORTH)) || (flipV && (d === DIRECTION.EAST || d === DIRECTION.WEST)) ) { const tmp = m.y; m.y = m.height; m.height = tmp; } const m2 = Rectangle.fromRectangle(m); if (d === DIRECTION.SOUTH) { m2.y = m.x; m2.x = m.height; m2.width = m.y; m2.height = m.width; } else if (d === DIRECTION.WEST) { m2.y = m.height; m2.x = m.width; m2.width = m.x; m2.height = m.y; } else if (d === DIRECTION.NORTH) { m2.y = m.width; m2.x = m.y; m2.width = m.height; m2.height = m.x; } return new Rectangle( rect.x + m2.x, rect.y + m2.y, rect.width - m2.width - m2.x, rect.height - m2.height - m2.y ); }; /** * Returns the intersection between the polygon defined by the array of * points and the line between center and point. */ export const getPerimeterPoint = (pts: Point[], center: Point, point: Point) => { let min = null; for (let i = 0; i < pts.length - 1; i += 1) { const pt = intersection( pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y, center.x, center.y, point.x, point.y ); if (pt != null) { const dx = point.x - pt.x; const dy = point.y - pt.y; const ip = { p: pt, distSq: dy * dy + dx * dx }; if (ip != null && (min == null || min.distSq > ip.distSq)) { min = ip; } } } return min != null ? min.p : null; }; /** * Returns true if the given rectangle intersects the given segment. * * @param bounds {@link Rectangle} that represents the rectangle. * @param p1 {@link Point} that represents the first point of the segment. * @param p2 {@link Point} that represents the second point of the segment. */ export const rectangleIntersectsSegment = (bounds: Rectangle, p1: Point, p2: Point) => { const top = bounds.y; const left = bounds.x; const bottom = top + bounds.height; const right = left + bounds.width; // Find min and max X for the segment let minX = p1.x; let maxX = p2.x; if (p1.x > p2.x) { minX = p2.x; maxX = p1.x; } // Find the intersection of the segment's and rectangle's x-projections if (maxX > right) { maxX = right; } if (minX < left) { minX = left; } if (minX > maxX) { // If their projections do not intersect return false return false; } // Find corresponding min and max Y for min and max X we found before let minY = p1.y; let maxY = p2.y; const dx = p2.x - p1.x; if (Math.abs(dx) > 0.0000001) { const a = (p2.y - p1.y) / dx; const b = p1.y - a * p1.x; minY = a * minX + b; maxY = a * maxX + b; } if (minY > maxY) { const tmp = maxY; maxY = minY; minY = tmp; } // Find the intersection of the segment's and rectangle's y-projections if (maxY > bottom) { maxY = bottom; } if (minY < top) { minY = top; } if (minY > maxY) { // If Y-projections do not intersect return false return false; } return true; }; /** * Returns true if the specified point (x, y) is contained in the given rectangle. * * @param bounds {@link Rectangle} that represents the area. * @param x X-coordinate of the point. * @param y Y-coordinate of the point. */ export const contains = (bounds: Rectangle, x: number, y: number) => { return ( bounds.x <= x && bounds.x + bounds.width >= x && bounds.y <= y && bounds.y + bounds.height >= y ); }; /** * Returns true if the two rectangles intersect. * * @param a {@link Rectangle} to be checked for intersection. * @param b {@link Rectangle} to be checked for intersection. */ export const intersects = (a: Rectangle, b: Rectangle) => { let tw = a.width; let th = a.height; let rw = b.width; let rh = b.height; if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { return false; } const tx = a.x; const ty = a.y; const rx = b.x; const ry = b.y; rw += rx; rh += ry; tw += tx; th += ty; return ( (rw < rx || rw > tx) && (rh < ry || rh > ty) && (tw < tx || tw > rx) && (th < ty || th > ry) ); }; /** * Returns true if the state and the hotspot intersect. * * @param state <CellState> * @param x X-coordinate. * @param y Y-coordinate. * @param hotspot Optional size of the hostpot. * @param min Optional min size of the hostpot. * @param max Optional max size of the hostpot. */ export const intersectsHotspot = ( state: CellState, x: number, y: number, hotspot: number, min: number, max: number ) => { hotspot = hotspot != null ? hotspot : 1; min = min != null ? min : 0; max = max != null ? max : 0; if (hotspot > 0) { let cx = state.getCenterX(); let cy = state.getCenterY(); let w = state.width; let h = state.height; const start = getValue(state.style, 'startSize') * state.view.scale; if (start > 0) { if (getValue(state.style, 'horizontal', true)) { cy = state.y + start / 2; h = start; } else { cx = state.x + start / 2; w = start; } } w = Math.max(min, w * hotspot); h = Math.max(min, h * hotspot); if (max > 0) { w = Math.min(w, max); h = Math.min(h, max); } const rect = new Rectangle(cx - w / 2, cy - h / 2, w, h); const alpha = toRadians(getValue(state.style, 'rotation') || 0); if (alpha != 0) { const cos = Math.cos(-alpha); const sin = Math.sin(-alpha); const cx = new Point(state.getCenterX(), state.getCenterY()); const pt = getRotatedPoint(new Point(x, y), cos, sin, cx); x = pt.x; y = pt.y; } return contains(rect, x, y); } return true; }; /** * Returns true if the specified value is numeric, that is, if it is not * null, not an empty string, not a HEX number and isNaN returns false. * * @param n String representing the possibly numeric value. */ export const isNumeric = (n: any) => { return ( !Number.isNaN(parseFloat(n)) && isFinite(+n) && (typeof n !== 'string' || n.toLowerCase().indexOf('0x') < 0) ); }; /** * Returns true if the given value is an valid integer number. * * @param n String representing the possibly numeric value. */ export const isInteger = (n: string) => { return String(parseInt(n)) === String(n); }; /** * Returns the remainder of division of n by m. You should use this instead * of the built-in operation as the built-in operation does not properly * handle negative numbers. */ export const mod = (n: number, m: number) => { return ((n % m) + m) % m; }; /** * Returns the intersection of two lines as an {@link Point}. * * @param x0 X-coordinate of the first line's startpoint. * @param y0 X-coordinate of the first line's startpoint. * @param x1 X-coordinate of the first line's endpoint. * @param y1 Y-coordinate of the first line's endpoint. * @param x2 X-coordinate of the second line's startpoint. * @param y2 Y-coordinate of the second line's startpoint. * @param x3 X-coordinate of the second line's endpoint. * @param y3 Y-coordinate of the second line's endpoint. */ export const intersection = ( x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number ) => { const denom = (y3 - y2) * (x1 - x0) - (x3 - x2) * (y1 - y0); const nume_a = (x3 - x2) * (y0 - y2) - (y3 - y2) * (x0 - x2); const nume_b = (x1 - x0) * (y0 - y2) - (y1 - y0) * (x0 - x2); const ua = nume_a / denom; const ub = nume_b / denom; if (ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0) { // Get the intersection point const x = x0 + ua * (x1 - x0); const y = y0 + ua * (y1 - y0); return new Point(x, y); } // No intersection return null; }; /** * Returns the square distance between a segment and a point. To get the * distance between a point and a line (with infinite length) use * {@link Utils#ptLineDist}. * * @param x1 X-coordinate of the startpoint of the segment. * @param y1 Y-coordinate of the startpoint of the segment. * @param x2 X-coordinate of the endpoint of the segment. * @param y2 Y-coordinate of the endpoint of the segment. * @param px X-coordinate of the point. * @param py Y-coordinate of the point. */ export const ptSegDistSq = ( x1: number, y1: number, x2: number, y2: number, px: number, py: number ) => { x2 -= x1; y2 -= y1; px -= x1; py -= y1; let dotprod = px * x2 + py * y2; let projlenSq; if (dotprod <= 0.0) { projlenSq = 0.0; } else { px = x2 - px; py = y2 - py; dotprod = px * x2 + py * y2; if (dotprod <= 0.0) { projlenSq = 0.0; } else { projlenSq = (dotprod * dotprod) / (x2 * x2 + y2 * y2); } } let lenSq = px * px + py * py - projlenSq; if (lenSq < 0) { lenSq = 0; } return lenSq; }; /** * Returns the distance between a line defined by two points and a point. * To get the distance between a point and a segment (with a specific * length) use {@link Utils#ptSeqDistSq}. * * @param x1 X-coordinate of point 1 of the line. * @param y1 Y-coordinate of point 1 of the line. * @param x2 X-coordinate of point 1 of the line. * @param y2 Y-coordinate of point 1 of the line. * @param px X-coordinate of the point. * @param py Y-coordinate of the point. */ export const ptLineDist = ( x1: number, y1: number, x2: number, y2: number, px: number, py: number ) => { return ( Math.abs((y2 - y1) * px - (x2 - x1) * py + x2 * y1 - y2 * x1) / Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)) ); }; /** * Returns 1 if the given point on the right side of the segment, 0 if its * on the segment, and -1 if the point is on the left side of the segment. * * @param x1 X-coordinate of the startpoint of the segment. * @param y1 Y-coordinate of the startpoint of the segment. * @param x2 X-coordinate of the endpoint of the segment. * @param y2 Y-coordinate of the endpoint of the segment. * @param px X-coordinate of the point. * @param py Y-coordinate of the point. */ export const relativeCcw = ( x1: number, y1: number, x2: number, y2: number, px: number, py: number ) => { x2 -= x1; y2 -= y1; px -= x1; py -= y1; let ccw = px * y2 - py * x2; if (ccw == 0.0) { ccw = px * x2 + py * y2; if (ccw > 0.0) { px -= x2; py -= y2; ccw = px * x2 + py * y2; if (ccw < 0.0) { ccw = 0.0; } } } return ccw < 0.0 ? -1 : ccw > 0.0 ? 1 : 0; };
the_stack
import * as Doppio from '../doppiojvm'; import JVMThread = Doppio.VM.Threading.JVMThread; import ReferenceClassData = Doppio.VM.ClassFile.ReferenceClassData; import IJVMConstructor = Doppio.VM.ClassFile.IJVMConstructor; import logging = Doppio.Debug.Logging; import util = Doppio.VM.Util; import ThreadStatus = Doppio.VM.Enums.ThreadStatus; import debug = logging.debug; import interfaces = Doppio.VM.Interfaces; import * as JVMTypes from '../../includes/JVMTypes'; import {setImmediate} from 'browserfs'; declare var Websock: { new (): interfaces.IWebsock; } export default function (): any { /** * If an application wants to open a TCP/UDP connection to "foobar.com", the application must first perform * a DNS lookup to determine the IP of that domain, and then open a socket to that IP. Doppio needs to emulate * this same functionality in JavaScript. * * However, the browser does not expose any DNS interfaces, as DNS lookup is provided opaquely by the browser * platform. For example, an application can make a WebSocket connection directly to "https://foobar.com/", and * will never know that domain's IP. * * To get around this missing functionality, Doppio returns an unused private IP in the range of 240.0.0.0 to * 250.0.0.0 for each unique DNS lookup. Doppio uses this IP as a token for that particular DNS lookup. When * the application attempts to connect to an IP in this range, Doppio uses the IP as a key into a hash table, * which returns a domain name that Doppio uses in the resulting WebSocket connection. An application will never * try to connect to one of these invalid IP addresses directly, so Doppio can distinguish between connections to * specific IP addresses and connections to domains. */ var host_lookup: {[addr: number]: string} = {}, host_reverse_lookup: {[real_addr: string]: number} = {}, // 240.0.0.0 .. 250.0.0.0 is currently unused address space next_host_address = 0xF0000000; // See RFC 6455 section 7.4 function websocket_status_to_message(status: number): string { switch (status) { case 1000: return 'Normal closure'; case 1001: return 'Endpoint is going away'; case 1002: return 'WebSocket protocol error'; case 1003: return 'Server received invalid data'; } return 'Unknown status code or error'; } function next_address(): number { next_host_address++; if (next_host_address > 0xFA000000) { logging.error('Out of addresses'); next_host_address = 0xF0000000; } return next_host_address; } function pack_address(address: number[]): number { var i: number, ret = 0; for (i = 3; i >= 0; i--) { ret |= address[i] & 0xFF; ret <<= 8; } return ret; } function host_allocate_address(address: string): number { var ret = next_address(); host_lookup[ret] = address; host_reverse_lookup[address] = ret; return ret; } /** * Asynchronously read data from a socket. Note that if this passes 0 to the * callback, Java will think it has received an EOF. Thus, we should wait until: * - We have at least one byte to return. * - The socket is closed. */ function socket_read_async(impl: JVMTypes.java_net_PlainSocketImpl, b: JVMTypes.JVMArray<number>, offset: number, len: number, resume_cb: (arg: number) => void): void { var i: number, available = impl.$ws.rQlen(), trimmed_len = available < len ? available : len, read = impl.$ws.rQshiftBytes(trimmed_len); for (i = 0; i < trimmed_len; i++) { b.array[offset++] = read[i]; } resume_cb(trimmed_len); } class java_net_Inet4Address { public static 'init()V'(thread: JVMThread): void { // NOP } } class java_net_Inet4AddressImpl { public static 'getLocalHostName()Ljava/lang/String;'(thread: JVMThread, javaThis: JVMTypes.java_net_Inet4AddressImpl): JVMTypes.java_lang_String { return thread.getJVM().internString('localhost'); } public static 'lookupAllHostAddr(Ljava/lang/String;)[Ljava/net/InetAddress;'(thread: JVMThread, javaThis: JVMTypes.java_net_Inet4AddressImpl, hostname: JVMTypes.java_lang_String): void { var rv = util.newObject<JVMTypes.java_net_Inet4Address>(thread, thread.getBsCl(), 'Ljava/net/Inet4Address;'); rv['<init>(Ljava/lang/String;I)V'](thread, [hostname, host_allocate_address(hostname.toString())], (e?: JVMTypes.java_lang_Throwable) => { if (e) { thread.throwException(e); } else { thread.asyncReturn(util.newArrayFromData<JVMTypes.java_net_InetAddress>(thread, thread.getBsCl(), '[Ljava/net/InetAddress;', [rv])); } }); } public static 'getHostByAddr([B)Ljava/lang/String;'(thread: JVMThread, javaThis: JVMTypes.java_net_Inet4AddressImpl, addr: JVMTypes.JVMArray<number>): JVMTypes.java_lang_String { var ret = host_reverse_lookup[pack_address(addr.array)]; if (ret == null) { return null; } return util.initString(thread.getBsCl(), "" + ret); } public static 'isReachable0([BI[BI)Z'(thread: JVMThread, javaThis: JVMTypes.java_net_Inet4AddressImpl, arg0: JVMTypes.JVMArray<number>, arg1: number, arg2: JVMTypes.JVMArray<number>, arg3: number): boolean { return false; } } class java_net_Inet6Address { public static 'init()V'(thread: JVMThread): void { // NOP } } class java_net_InetAddress { public static 'init()V'(thread: JVMThread): void { // NOP } } class java_net_InetAddressImplFactory { public static 'isIPv6Supported()Z'(thread: JVMThread): boolean { return false; } } class java_net_PlainSocketImpl { public static 'socketCreate(Z)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, isServer: number): void { // Check to make sure we're in a browser and the websocket libraries are present if (!util.are_in_browser()) { thread.throwNewException('Ljava/io/IOException;', 'WebSockets are disabled'); } else { var fd = javaThis['java/net/SocketImpl/fd']; // Make the FileDescriptor valid with a dummy fd fd['java/io/FileDescriptor/fd'] = 8374; // Finally, create our websocket instance javaThis.$ws = new Websock(); javaThis.$is_shutdown = false; } } public static 'socketConnect(Ljava/net/InetAddress;II)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, address: JVMTypes.java_net_InetAddress, port: number, timeout: number): void { var i: number, // The IPv4 case holder = address['java/net/InetAddress/holder'], addy = holder['java/net/InetAddress$InetAddressHolder/address'], // Assume scheme is ws for now host = 'ws://'; if (host_lookup[addy] == null) { // Populate host string based off of IP address for (i = 3; i >= 0; i--) { var shift = i * 8; host += "" + ((addy & (0xFF << shift)) >>> shift) + "."; } // trim last '.' host = host.substring(0, host.length - 1); } else { host += host_lookup[addy]; } // Add port host += ":" + port; debug("Connecting to " + host + " with timeout = " + timeout + " ms"); thread.setStatus(ThreadStatus.ASYNC_WAITING); var id = 0, clear_state = () => { window.clearTimeout(id); javaThis.$ws.on('open', () => { }); javaThis.$ws.on('close', () => { }); javaThis.$ws.on('error', () => { }); }, error_cb = (msg: string) => { return (e: any) => { clear_state(); thread.throwNewException('Ljava/io/IOException;', msg + ": " + e); }; }, close_cb = (msg: string) => { return (e: any) => { clear_state(); thread.throwNewException('Ljava/io/IOException;', msg + ": " + websocket_status_to_message(e.status)); }; }; // Success case javaThis.$ws.on('open', () => { debug('Open!'); clear_state(); thread.asyncReturn(); }); // Error cases javaThis.$ws.on('close', close_cb('Connection failed! (Closed)')); // Timeout case. In the case of no timeout, we set a default one of 10s. if (timeout === 0) { timeout = 10000; } // XXX: Casting to a number because NodeJS typings specify a Timer object. id = <number><any> setTimeout(error_cb('Connection timeout!'), timeout); debug("Host: " + host); // Launch! try { javaThis.$ws.open(host); } catch (err) { error_cb('Connection failed! (exception)')(err.message); } } public static 'socketBind(Ljava/net/InetAddress;I)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, arg0: JVMTypes.java_net_InetAddress, arg1: number): void { thread.throwNewException('Ljava/io/IOException;', 'WebSockets doesn\'t know how to bind'); } public static 'socketListen(I)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, arg0: number): void { thread.throwNewException('Ljava/io/IOException;', 'WebSockets doesn\'t know how to listen'); } public static 'socketAccept(Ljava/net/SocketImpl;)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, arg0: JVMTypes.java_net_SocketImpl): void { thread.throwNewException('Ljava/io/IOException;', 'WebSockets doesn\'t know how to accept'); } public static 'socketAvailable()I'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl): void { thread.setStatus(ThreadStatus.ASYNC_WAITING); setImmediate(() => { thread.asyncReturn(javaThis.$ws.rQlen()); }); } public static 'socketClose0(Z)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, arg0: number): void { // TODO: Something isn't working here javaThis.$ws.close(); } public static 'socketShutdown(I)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, arg0: number): void { javaThis.$is_shutdown = true; } public static 'initProto()V'(thread: JVMThread): void { // NOP } public static 'socketSetOption0(IZLjava/lang/Object;)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, arg0: number, arg1: number, arg2: JVMTypes.java_lang_Object): void { // NOP } public static 'socketGetOption(ILjava/lang/Object;)I'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, arg0: number, arg1: JVMTypes.java_lang_Object): number { // NOP return 0; } public static 'socketSendUrgentData(I)V'(thread: JVMThread, javaThis: JVMTypes.java_net_PlainSocketImpl, data: number): void { // Urgent data is meant to jump ahead of the // outbound stream. We keep no notion of this, // so queue up the byte like normal javaThis.$ws.send(data); } } class java_net_SocketInputStream { public static 'socketRead0(Ljava/io/FileDescriptor;[BIII)I'(thread: JVMThread, javaThis: JVMTypes.java_net_SocketInputStream, fd: JVMTypes.java_io_FileDescriptor, b: JVMTypes.JVMArray<number>, offset: number, len: number, timeout: number): void { var impl = <JVMTypes.java_net_PlainSocketImpl> javaThis['java/net/SocketInputStream/impl']; if (impl.$is_shutdown === true) { thread.throwNewException('Ljava/io/IOException;', 'Socket is shutdown.'); } else { thread.setStatus(ThreadStatus.ASYNC_WAITING); setTimeout(() => { socket_read_async(impl, b, offset, len, (arg: number) => { thread.asyncReturn(arg); }) }, timeout); } } public static 'init()V'(thread: JVMThread): void { // NOP } } class java_net_SocketOutputStream { public static 'socketWrite0(Ljava/io/FileDescriptor;[BII)V'(thread: JVMThread, javaThis: JVMTypes.java_net_SocketOutputStream, fd: JVMTypes.java_io_FileDescriptor, b: JVMTypes.JVMArray<number>, offset: number, len: number): void { var impl = <JVMTypes.java_net_PlainSocketImpl> javaThis['java/net/SocketOutputStream/impl']; if (impl.$is_shutdown === true) { thread.throwNewException('Ljava/io/IOException;', 'Socket is shutdown.'); } else if (impl.$ws.get_raw_state() !== WebSocket.OPEN) { thread.throwNewException('Ljava/io/IOException;', 'Connection isn\'t open'); } else { // TODO: This can be optimized by accessing the 'Q' directly impl.$ws.send(b.array.slice(offset, offset + len)); // Let the browser write it out thread.setStatus(ThreadStatus.ASYNC_WAITING); setImmediate(() => { thread.asyncReturn(); }); } } public static 'init()V'(thread: JVMThread): void { // NOP } } class java_net_NetworkInterface { public static 'init()V'(thread: JVMThread): void { // NOP } public static 'getAll()[Ljava/net/NetworkInterface;'(thread: JVMThread): void { let bsCl = thread.getBsCl(); // Create a fake network interface bound to 127.1.1.1. thread.import(['Ljava/net/NetworkInterface;', 'Ljava/net/InetAddress;'], (rv: [IJVMConstructor<JVMTypes.java_net_NetworkInterface>, typeof JVMTypes.java_net_InetAddress]) => { let niCons = rv[0], inetStatics = rv[1], iName = thread.getJVM().internString('doppio1'); inetStatics['getByAddress(Ljava/lang/String;[B)Ljava/net/InetAddress;'](thread, [iName, util.newArrayFromData<number>(thread, thread.getBsCl(), '[B', [127,1,1,1])], (e?: JVMTypes.java_lang_Throwable, rv?: JVMTypes.java_net_InetAddress) => { if (e) { thread.throwException(e); } else { var niObj = new niCons(thread); niObj['<init>(Ljava/lang/String;I[Ljava/net/InetAddress;)V'](thread, [iName, 0, util.newArrayFromData<JVMTypes.java_net_InetAddress>(thread, bsCl, '[Ljava/net/InetAddress;', [rv])], (e?: JVMTypes.java_lang_Throwable) => { if (e) { thread.throwException(e); } else { thread.asyncReturn(util.newArrayFromData<JVMTypes.java_net_NetworkInterface>(thread, bsCl, '[Ljava/net/NetworkInterface;', [niObj])); } }); } }); }); } public static 'getMacAddr0([BLjava/lang/String;I)[B'(thread: JVMThread, inAddr: JVMTypes.JVMArray<number>, name: JVMTypes.JVMArray<number>, ind: number): JVMTypes.JVMArray<number> { return util.newArrayFromData<number>(thread, thread.getBsCl(), '[B', [1,1,1,1,1,1]); } } return { 'java/net/Inet4Address': java_net_Inet4Address, 'java/net/Inet4AddressImpl': java_net_Inet4AddressImpl, 'java/net/Inet6Address': java_net_Inet6Address, 'java/net/InetAddress': java_net_InetAddress, 'java/net/InetAddressImplFactory': java_net_InetAddressImplFactory, 'java/net/PlainSocketImpl': java_net_PlainSocketImpl, 'java/net/SocketInputStream': java_net_SocketInputStream, 'java/net/SocketOutputStream': java_net_SocketOutputStream, 'java/net/NetworkInterface': java_net_NetworkInterface }; };
the_stack
import { Injectable } from "@angular/core"; import { Router } from "@angular/router"; import { ConfigService } from "./config.service"; import { Observable } from "rxjs"; import { ClientService, LoginResponse } from "./client.service"; import { catchError, finalize, map } from "rxjs/operators"; import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http"; import { throwError } from "rxjs/internal/observable/throwError"; declare var localStorage: any; const SESSION_HEADER = "x-evebox-session-id"; /** * The API service exposes the server side API to the rest of the server, * and acts as the "client" to the server. */ @Injectable() export class ApiService { private authenticated = false; constructor(private httpClient: HttpClient, public client: ClientService, private router: Router, private configService: ConfigService) { this.client._sessionId = localStorage._sessionId; } isAuthenticated(): boolean { return this.authenticated; } setSessionId(sessionId: string | null): void { this.client.setSessionId(sessionId); } checkVersion(response: any): void { this.client.checkVersion(response); } applySessionHeader(options: any): void { if (this.client._sessionId) { const headers = options.headers || new Headers(); headers.append(SESSION_HEADER, this.client._sessionId); options.headers = headers; } } setSessionHeader(headers: HttpHeaders): HttpHeaders { if (this.client._sessionId) { return headers.set(SESSION_HEADER, this.client._sessionId); } return headers; } setAuthenticated(authenticated: boolean): void { console.log(`Setting authenticated to ${authenticated}`); this.authenticated = authenticated; this.client.setAuthenticated(authenticated); if (!authenticated) { this.setSessionId(null); this.router.navigate(["/login"]).then(() => { }); } } private handle401(): void { this.setAuthenticated(false); } /** * Low level options request, just fixup the URL. */ _options(path: string): Observable<any> { return this.httpClient.options(this.client.buildUrl(path)); } doRequest(method: string, path: string, options: any = {}): Observable<any> { const headers = options.headers || new HttpHeaders(); options.headers = this.setSessionHeader(headers); options.observe = "response"; return this.httpClient.request<any>(method, path, options) .pipe(map((response: any) => { this.client.updateSessionId(response); this.checkVersion(response); return response.body; }), catchError((error) => { if (error.error instanceof ErrorEvent) { // Client side or network error. } else { if (error.status === 401) { this.handle401(); } } return throwError(error); })); } post(path: string, body: any, options: any = {}): Promise<any> { options.body = body; return this.doRequest("POST", path, options).toPromise(); } updateConfig(): Promise<any> { return this.client.get("api/1/config").toPromise() .then((config) => { console.log("got config"); console.log(config); this.configService.setConfig(config); return config; }); } checkAuth(): Promise<true | false> { console.log(this.client._sessionId); return this.updateConfig() .then(() => { this.setAuthenticated(true); return true; }) .catch((error) => { console.log(`Authentication failed: ${error.message}`); this.router.navigate(["/login"]); return false; }); } login(username: string = "", password: string = ""): Promise<boolean> { return this.client.login(username, password).toPromise() .then((response: LoginResponse) => { this.setSessionId(response.session_id); console.log("Login successful, updating configuration"); return this.updateConfig() .then(() => { this.setAuthenticated(true); return true; }); }); } logout(): Promise<any> { return this.client.logout().pipe( finalize(() => { this.setAuthenticated(false); }) ).toPromise(); } getWithParams(path: string, params = {}): Promise<any> { const qsb: any = []; for (const param of Object.keys(params)) { qsb.push(`${param}=${params[param]}`); } return this.client.get(`${path}?${qsb.join("&")}`).toPromise(); } getVersion(): Promise<any> { return this.client.get("api/1/version").toPromise(); } eventToPcap(what: any, event: any): void { // Set a cook with the session key to expire in 60 seconds from now. const expires = new Date(new Date().getTime() + 60000); const cookie = `${SESSION_HEADER}=${this.client._sessionId}; expires=${expires.toUTCString()}`; console.log("Setting cookie: " + cookie); document.cookie = cookie; const form = document.createElement("form") as HTMLFormElement; form.setAttribute("method", "post"); form.setAttribute("action", "api/1/eve2pcap"); const whatField = document.createElement("input") as HTMLElement; whatField.setAttribute("type", "hidden"); whatField.setAttribute("name", "what"); whatField.setAttribute("value", what); form.appendChild(whatField); const eventField = document.createElement("input") as HTMLElement; eventField.setAttribute("type", "hidden"); eventField.setAttribute("name", "event"); eventField.setAttribute("value", JSON.stringify(event)); form.appendChild(eventField); document.body.appendChild(form); form.submit(); } reportHistogram(options: ReportHistogramOptions = {}): Promise<any> { const query: any = []; if (options.timeRange && options.timeRange > 0) { query.push(`timeRange=${options.timeRange}s`); } if (options.interval) { query.push(`interval=${options.interval}`); } if (options.addressFilter) { query.push(`addressFilter=${options.addressFilter}`); } if (options.queryString) { query.push(`queryString=${options.queryString}`); } if (options.sensorFilter) { query.push(`sensorFilter=${options.sensorFilter}`); } if (options.dnsType) { query.push(`dnsType=${options.dnsType}`); } if (options.eventType) { query.push(`eventType=${options.eventType}`); } return this.client.get(`api/1/report/histogram?${query.join("&")}`).toPromise(); } reportAgg(agg: string, options: ReportAggOptions = {}): Promise<any> { let params = new HttpParams().append("agg", agg); for (const key of Object.keys(options)) { switch (key) { case "timeRange": params = params.append("timeRange", `${options[key]}s`); break; default: params = params.append(key, options[key]); break; } } return this.client.get("api/1/report/agg", params).toPromise(); } /** * Find events - all events, not just alerts. */ eventQuery(options: EventQueryOptions = {}): Observable<any> { let params = new HttpParams(); if (options.queryString) { params = params.append("query_string", options.queryString); } if (options.maxTs) { params = params.append("max_ts", options.maxTs); } if (options.minTs) { params = params.append("min_ts", options.minTs); } if (options.eventType && options.eventType !== "all") { params = params.append("event_type", options.eventType); } if (options.sortOrder) { params = params.append("order", options.sortOrder); } if (options.sortBy) { params = params.append("sort_by", options.sortBy); } if (options.size) { params = params.append("size", options.size.toString()); } if (options.timeRange) { params = params.append("time_range", `${options.timeRange}s`); } return this.client.get("api/1/event-query", params); } flowHistogram(args: any = {}): any { let params = new HttpParams(); const subAggs = []; if (args.appProto) { subAggs.push("app_proto"); } if (subAggs.length > 0) { params = params.append("sub_aggs", subAggs.join(",")); } if (args.timeRange) { params = params.append("time_range", args.timeRange); } if (args.queryString) { params = params.append("query_string", args.queryString); } if (args.interval) { params = params.append("interval", args.interval); } return this.client.get("api/1/flow/histogram", params); } commentOnEvent(eventId: string, comment: string): Promise<any> { console.log(`Commenting on event ${eventId}.`); return this.post(`api/1/event/${eventId}/comment`, { event_id: eventId, comment, }); } commentOnAlertGroup(alertGroup: any, comment: string): Promise<any> { console.log(`Commenting on alert group:`); console.log(alertGroup); const request = { signature_id: alertGroup.event._source.alert.signature_id, src_ip: alertGroup.event._source.src_ip, dest_ip: alertGroup.event._source.dest_ip, min_timestamp: alertGroup.minTs, max_timestamp: alertGroup.maxTs, }; return this.post(`api/1/alert-group/comment`, { alert_group: request, comment: comment, }); } alertQuery(options: { queryString?: string; mustHaveTags?: any[]; mustNotHaveTags?: any[]; timeRange?: string; }): Observable<any> { let params = new HttpParams(); const tags: string[] = []; if (options.mustHaveTags) { options.mustHaveTags.forEach((tag: string) => { tags.push(tag); }); } if (options.mustNotHaveTags) { options.mustNotHaveTags.forEach((tag: string) => { tags.push(`-${tag}`); }); } params = params.append("tags", tags.join(",")); params = params.append("time_range", options.timeRange); params = params.append("query_string", options.queryString); return this.client.get("api/1/alerts", params); } } export interface ReportHistogramOptions { timeRange?: number; interval?: string; addressFilter?: string; queryString?: string; sensorFilter?: string; eventType?: string; dnsType?: string; } // Options for an aggregation report. export interface ReportAggOptions { size?: number; queryString?: string; timeRange?: number; // Event type. eventType?: string; // Subtype info. dnsType?: string; } export interface EventQueryOptions { queryString?: string; maxTs?: string; minTs?: string; eventType?: string; sortOrder?: string; sortBy?: string; size?: number; timeRange?: number; }
the_stack
export default class UIEventsCode { // 3.1.1.1. Writing System Keys public static readonly Backquote: string = 'Backquote'; public static readonly Backslash: string = 'Backslash'; public static readonly BracketLeft: string = 'BracketLeft'; public static readonly BracketRight: string = 'BracketRight'; public static readonly Comma: string = 'Comma'; public static readonly Digit0: string = 'Digit0'; public static readonly Digit1: string = 'Digit1'; public static readonly Digit2: string = 'Digit2'; public static readonly Digit3: string = 'Digit3'; public static readonly Digit4: string = 'Digit4'; public static readonly Digit5: string = 'Digit5'; public static readonly Digit6: string = 'Digit6'; public static readonly Digit7: string = 'Digit7'; public static readonly Digit8: string = 'Digit8'; public static readonly Digit9: string = 'Digit9'; public static readonly Equal: string = 'Equal'; public static readonly IntlBackslash: string = 'IntlBackslash'; public static readonly IntlRo: string = 'IntlRo'; public static readonly IntlYen: string = 'IntlYen'; public static readonly KeyA: string = 'KeyA'; public static readonly KeyB: string = 'KeyB'; public static readonly KeyC: string = 'KeyC'; public static readonly KeyD: string = 'KeyD'; public static readonly KeyE: string = 'KeyE'; public static readonly KeyF: string = 'KeyF'; public static readonly KeyG: string = 'KeyG'; public static readonly KeyH: string = 'KeyH'; public static readonly KeyI: string = 'KeyI'; public static readonly KeyJ: string = 'KeyJ'; public static readonly KeyK: string = 'KeyK'; public static readonly KeyL: string = 'KeyL'; public static readonly KeyM: string = 'KeyM'; public static readonly KeyN: string = 'KeyN'; public static readonly KeyO: string = 'KeyO'; public static readonly KeyP: string = 'KeyP'; public static readonly KeyQ: string = 'KeyQ'; public static readonly KeyR: string = 'KeyR'; public static readonly KeyS: string = 'KeyS'; public static readonly KeyT: string = 'KeyT'; public static readonly KeyU: string = 'KeyU'; public static readonly KeyV: string = 'KeyV'; public static readonly KeyW: string = 'KeyW'; public static readonly KeyX: string = 'KeyX'; public static readonly KeyY: string = 'KeyY'; public static readonly KeyZ: string = 'KeyZ'; public static readonly Minus: string = 'Minus'; public static readonly Period: string = 'Period'; public static readonly Quote: string = 'Quote'; public static readonly Semicolon: string = 'Semicolon'; public static readonly Slash: string = 'Slash'; // 3.1.1.2. Functional Keys public static readonly AltLeft: string = 'AltLeft'; public static readonly AltRight: string = 'AltRight'; public static readonly Backspace: string = 'Backspace'; public static readonly CapsLock: string = 'CapsLock'; public static readonly ContextMenu: string = 'ContextMenu'; public static readonly ControlLeft: string = 'ControlLeft'; public static readonly ControlRight: string = 'ControlRight'; public static readonly Enter: string = 'Enter'; public static readonly MetaLeft: string = 'MetaLeft'; public static readonly MetaRight: string = 'MetaRight'; public static readonly ShiftLeft: string = 'ShiftLeft'; public static readonly ShiftRight: string = 'ShiftRight'; public static readonly Space: string = 'Space'; public static readonly Tab: string = 'Tab'; public static readonly Convert: string = 'Convert'; public static readonly KanaMode: string = 'KanaMode'; public static readonly Lang1: string = 'Lang1'; public static readonly Lang2: string = 'Lang2'; public static readonly Lang3: string = 'Lang3'; public static readonly Lang4: string = 'Lang4'; public static readonly Lang5: string = 'Lang5'; public static readonly NonConvert: string = 'NonConvert'; // 3.1.2. Control Pad Section public static readonly Delete: string = 'Delete'; public static readonly End: string = 'End'; public static readonly Help: string = 'Help'; public static readonly Home: string = 'Home'; public static readonly Insert: string = 'Insert'; public static readonly PageDown: string = 'PageDown'; public static readonly PageUp: string = 'PageUp'; // 3.1.3. Arrow Pad Section public static readonly ArrowDown: string = 'ArrowDown'; public static readonly ArrowLeft: string = 'ArrowLeft'; public static readonly ArrowRight: string = 'ArrowRight'; public static readonly ArrowUp: string = 'ArrowUp'; // 3.1.4. Numpad Section public static readonly NumLock: string = 'NumLock'; public static readonly Numpad0: string = 'Numpad0'; public static readonly Numpad1: string = 'Numpad1'; public static readonly Numpad2: string = 'Numpad2'; public static readonly Numpad3: string = 'Numpad3'; public static readonly Numpad4: string = 'Numpad4'; public static readonly Numpad5: string = 'Numpad5'; public static readonly Numpad6: string = 'Numpad6'; public static readonly Numpad7: string = 'Numpad7'; public static readonly Numpad8: string = 'Numpad8'; public static readonly Numpad9: string = 'Numpad9'; public static readonly NumpadAdd: string = 'NumpadAdd'; public static readonly NumpadBackspace: string = 'NumpadBackspace'; public static readonly NumpadClear: string = 'NumpadClear'; public static readonly NumpadClearEntry: string = 'NumpadClearEntry'; public static readonly NumpadComma: string = 'NumpadComma'; public static readonly NumpadDecimal: string = 'NumpadDecimal'; public static readonly NumpadDivide: string = 'NumpadDivide'; public static readonly NumpadEnter: string = 'NumpadEnter'; public static readonly NumpadEqual: string = 'NumpadEqual'; public static readonly NumpadHash: string = 'NumpadHash'; public static readonly NumpadMemoryAdd: string = 'NumpadMemoryAdd'; public static readonly NumpadMemoryClear: string = 'NumpadMemoryClear'; public static readonly NumpadMemoryRecall: string = 'NumpadMemoryRecall'; public static readonly NumpadMemoryStore: string = 'NumpadMemoryStore'; public static readonly NumpadMemorySubtract: string = 'NumpadMemorySubtract'; public static readonly NumpadMultiply: string = 'NumpadMultiply'; public static readonly NumpadParenLeft: string = 'NumpadParenLeft'; public static readonly NumpadParenRight: string = 'NumpadParenRight'; public static readonly NumpadStar: string = 'NumpadStar'; public static readonly NumpadSubtract: string = 'NumpadSubtract'; // 3.1.5. Function Section public static readonly Escape: string = 'Escape'; public static readonly F1: string = 'F1'; public static readonly F2: string = 'F2'; public static readonly F3: string = 'F3'; public static readonly F4: string = 'F4'; public static readonly F5: string = 'F5'; public static readonly F6: string = 'F6'; public static readonly F7: string = 'F7'; public static readonly F8: string = 'F8'; public static readonly F9: string = 'F9'; public static readonly F10: string = 'F10'; public static readonly F11: string = 'F11'; public static readonly F12: string = 'F12'; public static readonly Fn: string = 'Fn'; public static readonly FnLock: string = 'FnLock'; public static readonly PrintScreen: string = 'PrintScreen'; public static readonly ScrollLock: string = 'ScrollLock'; public static readonly Pause: string = 'Pause'; // 3.1.6. Media Keys public static readonly BrowserBack: string = 'BrowserBack'; public static readonly BrowserFavorites: string = 'BrowserFavorites'; public static readonly BrowserForward: string = 'BrowserForward'; public static readonly BrowserHome: string = 'BrowserHome'; public static readonly BrowserRefresh: string = 'BrowserRefresh'; public static readonly BrowserSearch: string = 'BrowserSearch'; public static readonly BrowserStop: string = 'BrowserStop'; public static readonly Eject: string = 'Eject'; public static readonly LaunchApp1: string = 'LaunchApp1'; public static readonly LaunchApp2: string = 'LaunchApp2'; public static readonly LaunchMail: string = 'LaunchMail'; public static readonly MediaPlayPause: string = 'MediaPlayPause'; public static readonly MediaSelect: string = 'MediaSelect'; public static readonly MediaStop: string = 'MediaStop'; public static readonly MediaTrackNext: string = 'MediaTrackNext'; public static readonly MediaTrackPrevious: string = 'MediaTrackPrevious'; public static readonly Power: string = 'Power'; public static readonly Sleep: string = 'Sleep'; public static readonly AudioVolumeDown: string = 'AudioVolumeDown'; public static readonly AudioVolumeMute: string = 'AudioVolumeMute'; public static readonly AudioVolumeUp: string = 'AudioVolumeUp'; public static readonly WakeUp: string = 'WakeUp'; // 3.1.7. Legacy, Non-Standard and Special Keys public static readonly Hyper: string = 'Hyper'; public static readonly Super: string = 'Super'; public static readonly Turbo: string = 'Turbo'; public static readonly Abort: string = 'Abort'; public static readonly Resume: string = 'Resume'; public static readonly Suspend: string = 'Suspend'; public static readonly Again: string = 'Again'; public static readonly Copy: string = 'Copy'; public static readonly Cut: string = 'Cut'; public static readonly Find: string = 'Find'; public static readonly Open: string = 'Open'; public static readonly Paste: string = 'Paste'; public static readonly Props: string = 'Props'; public static readonly Select: string = 'Select'; public static readonly Undo: string = 'Undo'; public static readonly Hiragana: string = 'Hiragana'; public static readonly Katakana: string = 'Katakana'; public static readonly Unidentified: string = 'Unidentified'; }
the_stack
import * as choki from "chokidar"; import { hook } from "../common/helpers"; import { cache, performanceLog } from "../common/decorators"; import { EventEmitter } from "events"; import * as path from "path"; import { AnalyticsEventLabelDelimiter, CONFIG_FILE_NAME_JS, CONFIG_FILE_NAME_TS, PACKAGE_JSON_FILE_NAME, PLATFORMS_DIR_NAME, PREPARE_READY_EVENT_NAME, SupportedPlatform, TrackActionNames, WEBPACK_COMPILATION_COMPLETE, } from "../constants"; import { IProjectConfigService, IProjectData, IProjectDataService, } from "../definitions/project"; import { INodeModulesDependenciesBuilder, IPlatformController, IPlatformData, IPlatformsDataService, } from "../definitions/platform"; import { IPluginsService } from "../definitions/plugins"; import { IWatchIgnoreListService } from "../declarations"; import { IAnalyticsService, IDictionary, IFileSystem, IHooksService, } from "../common/declarations"; import { injector } from "../common/yok"; import * as _ from "lodash"; // import { project } from "nativescript-dev-xcode"; // import { platform } from "os"; interface IPlatformWatcherData { hasWebpackCompilerProcess: boolean; nativeFilesWatcher: choki.FSWatcher; } export class PrepareController extends EventEmitter { private watchersData: IDictionary<IDictionary<IPlatformWatcherData>> = {}; private isInitialPrepareReady = false; private persistedData: IFilesChangeEventData[] = []; private webpackCompilerHandler: any = null; constructor( private $platformController: IPlatformController, public $hooksService: IHooksService, private $fs: IFileSystem, private $logger: ILogger, private $mobileHelper: Mobile.IMobileHelper, private $nodeModulesDependenciesBuilder: INodeModulesDependenciesBuilder, private $platformsDataService: IPlatformsDataService, private $pluginsService: IPluginsService, private $prepareNativePlatformService: IPrepareNativePlatformService, private $projectChangesService: IProjectChangesService, private $projectDataService: IProjectDataService, private $webpackCompilerService: IWebpackCompilerService, private $watchIgnoreListService: IWatchIgnoreListService, private $analyticsService: IAnalyticsService, private $markingModeService: IMarkingModeService, private $projectConfigService: IProjectConfigService ) { super(); } public async prepare(prepareData: IPrepareData): Promise<IPrepareResultData> { const projectData = this.$projectDataService.getProjectData( prepareData.projectDir ); if (this.$mobileHelper.isAndroidPlatform(prepareData.platform)) { await this.$markingModeService.handleMarkingModeFullDeprecation({ projectDir: projectData.projectDir, }); } await this.$pluginsService.ensureAllDependenciesAreInstalled(projectData); return this.prepareCore(prepareData, projectData); } public async stopWatchers( projectDir: string, platform: string ): Promise<void> { const platformLowerCase = platform.toLowerCase(); if ( this.watchersData && this.watchersData[projectDir] && this.watchersData[projectDir][platformLowerCase] && this.watchersData[projectDir][platformLowerCase].nativeFilesWatcher ) { await this.watchersData[projectDir][ platformLowerCase ].nativeFilesWatcher.close(); this.watchersData[projectDir][ platformLowerCase ].nativeFilesWatcher = null; } if ( this.watchersData && this.watchersData[projectDir] && this.watchersData[projectDir][platformLowerCase] && this.watchersData[projectDir][platformLowerCase].hasWebpackCompilerProcess ) { await this.$webpackCompilerService.stopWebpackCompiler(platformLowerCase); this.$webpackCompilerService.removeListener( WEBPACK_COMPILATION_COMPLETE, this.webpackCompilerHandler ); this.watchersData[projectDir][ platformLowerCase ].hasWebpackCompilerProcess = false; } } @performanceLog() @hook("prepare") private async prepareCore( prepareData: IPrepareData, projectData: IProjectData ): Promise<IPrepareResultData> { await this.$platformController.addPlatformIfNeeded(prepareData); await this.trackRuntimeVersion(prepareData.platform, projectData); this.$logger.info("Preparing project..."); // we need to mark the ~/package.json (used by core modules) // as external for us to be able to write the config to it // in writeRuntimePackageJson() below, because otherwise // webpack will inline it into the bundle/vendor chunks prepareData.env = prepareData.env || {}; prepareData.env.externals = prepareData.env.externals || []; prepareData.env.externals.push("~/package.json"); prepareData.env.externals.push("package.json"); if (this.$mobileHelper.isAndroidPlatform(prepareData.platform)) { await this.$projectConfigService.writeLegacyNSConfigIfNeeded( projectData.projectDir, this.$projectDataService.getRuntimePackage( projectData.projectDir, prepareData.platform as SupportedPlatform ) ); } let result = null; const platformData = this.$platformsDataService.getPlatformData( prepareData.platform, projectData ); if (prepareData.watch) { result = await this.startWatchersWithPrepare( platformData, projectData, prepareData ); } else { await this.$webpackCompilerService.compileWithoutWatch( platformData, projectData, prepareData ); const hasNativeChanges = await this.$prepareNativePlatformService.prepareNativePlatform( platformData, projectData, prepareData ); result = { hasNativeChanges, platform: prepareData.platform.toLowerCase(), }; } await this.writeRuntimePackageJson(projectData, platformData); await this.$projectChangesService.savePrepareInfo( platformData, projectData, prepareData ); this.$logger.info( `Project successfully prepared (${prepareData.platform.toLowerCase()})` ); return result; } @hook("watch") private async startWatchersWithPrepare( platformData: IPlatformData, projectData: IProjectData, prepareData: IPrepareData ): Promise<IPrepareResultData> { if (!this.watchersData[projectData.projectDir]) { this.watchersData[projectData.projectDir] = {}; } if ( !this.watchersData[projectData.projectDir][ platformData.platformNameLowerCase ] ) { this.watchersData[projectData.projectDir][ platformData.platformNameLowerCase ] = { nativeFilesWatcher: null, hasWebpackCompilerProcess: false, }; } await this.startJSWatcherWithPrepare( platformData, projectData, prepareData ); // -> start watcher + initial compilation const hasNativeChanges = await this.startNativeWatcherWithPrepare( platformData, projectData, prepareData ); // -> start watcher + initial prepare const result = { platform: platformData.platformNameLowerCase, hasNativeChanges, }; const hasPersistedDataWithNativeChanges = this.persistedData.find( (data) => data.platform === result.platform && data.hasNativeChanges ); if (hasPersistedDataWithNativeChanges) { result.hasNativeChanges = true; } // TODO: Do not persist this in `this` context. Also it should be per platform. this.isInitialPrepareReady = true; if (this.persistedData && this.persistedData.length) { this.emitPrepareEvent({ files: [], staleFiles: [], hasOnlyHotUpdateFiles: false, hasNativeChanges: result.hasNativeChanges, hmrData: null, platform: platformData.platformNameLowerCase, }); } return result; } private async startJSWatcherWithPrepare( platformData: IPlatformData, projectData: IProjectData, prepareData: IPrepareData ): Promise<void> { if ( !this.watchersData[projectData.projectDir][ platformData.platformNameLowerCase ].hasWebpackCompilerProcess ) { const handler = (data: any) => { if ( data.platform.toLowerCase() === platformData.platformNameLowerCase ) { this.emitPrepareEvent({ ...data, hasNativeChanges: false }); } }; this.webpackCompilerHandler = handler.bind(this); this.$webpackCompilerService.on( WEBPACK_COMPILATION_COMPLETE, this.webpackCompilerHandler ); this.watchersData[projectData.projectDir][ platformData.platformNameLowerCase ].hasWebpackCompilerProcess = true; await this.$webpackCompilerService.compileWithWatch( platformData, projectData, prepareData ); } } private async startNativeWatcherWithPrepare( platformData: IPlatformData, projectData: IProjectData, prepareData: IPrepareData ): Promise<boolean> { let newNativeWatchStarted = false; let hasNativeChanges = false; if (prepareData.watchNative) { newNativeWatchStarted = await this.startNativeWatcher( platformData, projectData ); } if (newNativeWatchStarted) { hasNativeChanges = await this.$prepareNativePlatformService.prepareNativePlatform( platformData, projectData, prepareData ); } return hasNativeChanges; } private async startNativeWatcher( platformData: IPlatformData, projectData: IProjectData ): Promise<boolean> { if ( this.watchersData[projectData.projectDir][ platformData.platformNameLowerCase ].nativeFilesWatcher ) { return false; } const patterns = await this.getWatcherPatterns(platformData, projectData); const watcherOptions: choki.WatchOptions = { ignoreInitial: true, cwd: projectData.projectDir, awaitWriteFinish: { pollInterval: 100, stabilityThreshold: 500, }, ignored: ["**/.*", ".*"], // hidden files }; const watcher = choki .watch(patterns, watcherOptions) .on("all", async (event: string, filePath: string) => { filePath = path.join(projectData.projectDir, filePath); if (this.$watchIgnoreListService.isFileInIgnoreList(filePath)) { this.$watchIgnoreListService.removeFileFromIgnoreList(filePath); } else { this.$logger.info(`Chokidar raised event ${event} for ${filePath}.`); await this.writeRuntimePackageJson(projectData, platformData); this.emitPrepareEvent({ files: [], staleFiles: [], hasOnlyHotUpdateFiles: false, hmrData: null, hasNativeChanges: true, platform: platformData.platformNameLowerCase, }); } }); this.watchersData[projectData.projectDir][ platformData.platformNameLowerCase ].nativeFilesWatcher = watcher; return true; } @hook("watchPatterns") public async getWatcherPatterns( platformData: IPlatformData, projectData: IProjectData ): Promise<string[]> { const dependencies = this.$nodeModulesDependenciesBuilder .getProductionDependencies(projectData.projectDir, projectData.ignoredDependencies) .filter((dep) => dep.nativescript); const pluginsNativeDirectories = dependencies.map((dep) => path.join( dep.directory, PLATFORMS_DIR_NAME, platformData.platformNameLowerCase ) ); const pluginsPackageJsonFiles = dependencies.map((dep) => path.join(dep.directory, PACKAGE_JSON_FILE_NAME) ); const patterns = [ path.join(projectData.projectDir, PACKAGE_JSON_FILE_NAME), path.join(projectData.projectDir, CONFIG_FILE_NAME_JS), path.join(projectData.projectDir, CONFIG_FILE_NAME_TS), path.join(projectData.getAppDirectoryPath(), PACKAGE_JSON_FILE_NAME), path.join( projectData.getAppResourcesRelativeDirectoryPath(), platformData.normalizedPlatformName ), ] .concat(pluginsNativeDirectories) .concat(pluginsPackageJsonFiles); return patterns; } public async writeRuntimePackageJson( projectData: IProjectData, platformData: IPlatformData ) { const configInfo = this.$projectConfigService.detectProjectConfigs( projectData.projectDir ); if (configInfo.usingNSConfig) { return; } this.$logger.info( "Updating runtime package.json with configuration values..." ); const nsConfig = this.$projectConfigService.readConfig( projectData.projectDir ); const packageData: any = { ..._.pick(projectData.packageJsonData, ["name"]), ...nsConfig, main: "bundle", }; if ( platformData.platformNameLowerCase === "ios" && packageData.ios && packageData.ios.discardUncaughtJsExceptions ) { packageData.discardUncaughtJsExceptions = packageData.ios.discardUncaughtJsExceptions; } if ( platformData.platformNameLowerCase === "android" && packageData.android && packageData.android.discardUncaughtJsExceptions ) { packageData.discardUncaughtJsExceptions = packageData.android.discardUncaughtJsExceptions; } let packagePath: string; if (platformData.platformNameLowerCase === "ios") { packagePath = path.join( platformData.projectRoot, projectData.projectName, "app", "package.json" ); } else { packagePath = path.join( platformData.projectRoot, "app", "src", "main", "assets", "app", "package.json" ); } try { // this will read the package.json that is already emitted by // the GenerateNativeScriptEntryPointsPlugin webpack plugin const emittedPackageData = this.$fs.readJson(packagePath); // since ns7 we only care about the main key from the emitted // package.json, the rest is coming from the new config. if (emittedPackageData?.main) { packageData.main = emittedPackageData.main; } } catch (error) { this.$logger.trace( "Failed to read emitted package.json. Error is: ", error ); } this.$fs.writeJson(packagePath, packageData); } private emitPrepareEvent(filesChangeEventData: IFilesChangeEventData) { if (this.isInitialPrepareReady) { this.emit(PREPARE_READY_EVENT_NAME, filesChangeEventData); } else { this.persistedData.push(filesChangeEventData); } } @cache() private async trackRuntimeVersion( platform: string, projectData: IProjectData ): Promise<void> { const { version } = this.$projectDataService.getRuntimePackage( projectData.projectDir, platform as SupportedPlatform ); if (!version) { this.$logger.trace( `Unable to get runtime version for project directory: ${projectData.projectDir} and platform ${platform}.` ); return; } await this.$analyticsService.trackEventActionInGoogleAnalytics({ action: TrackActionNames.UsingRuntimeVersion, additionalData: `${platform.toLowerCase()}${AnalyticsEventLabelDelimiter}${version}`, }); } } injector.register("prepareController", PrepareController);
the_stack
import * as promisify from '@google-cloud/promisify'; import * as assert from 'assert'; import {before, beforeEach, describe, it} from 'mocha'; import * as proxyquire from 'proxyquire'; import {PassThrough, Readable} from 'stream'; import {CallOptions} from 'google-gax'; import {PreciseDate} from '@google-cloud/precise-date'; let promisified = false; const fakePromisify = Object.assign({}, promisify, { // eslint-disable-next-line @typescript-eslint/no-explicit-any promisifyAll(klass: Function, options: any) { if (klass.name === 'Cluster') { promisified = true; assert.deepStrictEqual(options.exclude, ['backup']); } }, }); class FakeBackup { calledWith_: Array<{}>; // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(...args: any[]) { this.calledWith_ = Array.from(args); } } describe('Bigtable/Cluster', () => { const CLUSTER_ID = 'my-cluster'; const PROJECT_ID = 'grape-spaceship-123'; const INSTANCE = { name: `projects/${PROJECT_ID}/instances/i`, bigtable: {projectId: PROJECT_ID}, }; const CLUSTER_NAME = `${INSTANCE.name}/clusters/${CLUSTER_ID}`; // eslint-disable-next-line @typescript-eslint/no-explicit-any let Cluster: any; // eslint-disable-next-line @typescript-eslint/no-explicit-any let cluster: any; before(() => { Cluster = proxyquire('../src/cluster.js', { '@google-cloud/promisify': fakePromisify, './backup.js': {Backup: FakeBackup}, }).Cluster; }); beforeEach(() => { cluster = new Cluster(INSTANCE, CLUSTER_ID); }); describe('instantiation', () => { it('should promisify all the things', () => { assert(promisified); }); it('should localize Bigtable instance', () => { assert.strictEqual(cluster.bigtable, INSTANCE.bigtable); }); it('should localize Instance instance', () => { assert.strictEqual(cluster.instance, INSTANCE); }); it('should expand id into full resource path', () => { assert.strictEqual(cluster.name, CLUSTER_NAME); }); it('should leave full cluster names unaltered', () => { const cluster = new Cluster(INSTANCE, CLUSTER_ID); assert.strictEqual(cluster.name, CLUSTER_NAME); }); it('should localize the id from the name', () => { assert.strictEqual(cluster.id, CLUSTER_ID); }); it('should leave full cluster names unaltered and localize the id from the name', () => { const cluster = new Cluster(INSTANCE, CLUSTER_NAME); assert.strictEqual(cluster.name, CLUSTER_NAME); assert.strictEqual(cluster.id, CLUSTER_ID); }); it('should throw if cluster id in wrong format', () => { const id = `clusters/${CLUSTER_ID}`; assert.throws(() => { new Cluster(INSTANCE, id); }, Error); }); }); describe('getLocation_', () => { const LOCATION = 'us-central1-b'; it('should format the location name', () => { const expected = `projects/${PROJECT_ID}/locations/${LOCATION}`; const formatted = Cluster.getLocation_(PROJECT_ID, LOCATION); assert.strictEqual(formatted, expected); }); it('should format the location name for project name with /', () => { const PROJECT_NAME = 'projects/grape-spaceship-123'; const expected = `projects/${PROJECT_NAME.split( '/' ).pop()}/locations/${LOCATION}`; const formatted = Cluster.getLocation_(PROJECT_NAME, LOCATION); assert.strictEqual(formatted, expected); }); it('should not re-format a complete location', () => { const complete = `projects/p/locations/${LOCATION}`; const formatted = Cluster.getLocation_(PROJECT_ID, complete); assert.strictEqual(formatted, complete); }); }); describe('getStorageType_', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const types: any = { unspecified: 0, ssd: 1, hdd: 2, }; it('should default to unspecified', () => { assert.strictEqual(Cluster.getStorageType_(), types.unspecified); }); it('should lowercase a type', () => { assert.strictEqual(Cluster.getStorageType_('SSD'), types.ssd); }); Object.keys(types).forEach(type => { it('should get the storage type for "' + type + '"', () => { assert.strictEqual(Cluster.getStorageType_(type), types[type]); }); }); }); describe('backup', () => { it('should return a Backup object', () => { const backupId = 'backup-id'; const backup = cluster.backup(backupId); assert(backup instanceof FakeBackup); // eslint-disable-next-line @typescript-eslint/no-explicit-any const args = (backup as any).calledWith_; assert.strictEqual(args[0], cluster); assert.strictEqual(args[1], backupId); }); }); describe('create', () => { it('should call createCluster from instance', done => { const options = {}; cluster.instance.createCluster = ( id: string, options_: {}, callback: Function ) => { assert.strictEqual(id, cluster.id); assert.strictEqual(options_, options); callback(); // done() }; cluster.create(options, done); }); it('should not require options', done => { cluster.instance.createCluster = ( id: string, options: {}, callback: Function ) => { assert.deepStrictEqual(options, {}); callback(); // done() }; cluster.create(done); }); }); describe('createBackup', () => { it('should throw if backup id not provided', () => { assert.throws(() => { cluster.createBackup(); }, /An id is required to create a backup\./); }); it('should throw if config is not provided', () => { assert.throws(() => { cluster.createBackup('id'); }, /A configuration object is required\./); }); it('should throw if a source table is not provided', () => { assert.throws(() => { cluster.createBackup('id', {}); }, /A source table is required to backup\./); }); it('should accept table as a string', done => { const table = 'table-name'; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.reqOpts.backup.sourceTable, table); done(); }; cluster.createBackup( 'id', { table, }, assert.ifError ); }); it('should accept table as a Table object', done => { const table = { name: 'table-name', }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.reqOpts.backup.sourceTable, table.name); done(); }; cluster.createBackup( 'id', { table, }, assert.ifError ); }); it('should not include table in request options', done => { const table = 'table-name'; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(typeof config.reqOpts.backup.table, 'undefined'); done(); }; cluster.createBackup( 'id', { table, }, assert.ifError ); }); it('should convert a Date expireTime to a struct', done => { const expireTime = new Date(); // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.deepStrictEqual( config.reqOpts.backup.expireTime, new PreciseDate(expireTime).toStruct() ); done(); }; cluster.createBackup( 'id', { table: 'table-id', expireTime, }, assert.ifError ); }); it('should send correct request', done => { const backupId = 'backup-id'; const table = 'table-name'; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.client, 'BigtableTableAdminClient'); assert.strictEqual(config.method, 'createBackup'); assert.deepStrictEqual(config.reqOpts, { parent: cluster.name, backupId, backup: { sourceTable: table, configProperty: true, }, }); assert.strictEqual(typeof config.gaxOpts, 'undefined'); done(); }; cluster.createBackup( backupId, { table, configProperty: true, }, assert.ifError ); }); it('should accept gaxOptions', done => { const table = 'table-name'; const gaxOptions = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; cluster.createBackup( 'id', { table, gaxOptions, }, assert.ifError ); }); it('should not include gaxOptions in request options', done => { const table = 'table-name'; const gaxOptions = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(typeof config.reqOpts.gaxOptions, 'undefined'); done(); }; cluster.createBackup( 'id', { table, gaxOptions, }, assert.ifError ); }); it('should execute callback with error and original args', done => { const error = new Error('Error.'); const args = [{}, {}, {}]; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any, callback: Function) => { callback(error, ...args); }; cluster.createBackup( 'id', { table: 'table-name', }, (err: Error, backup: {}, ..._args: Array<{}>) => { assert.strictEqual(err, error); assert.strictEqual(backup, undefined); assert.deepStrictEqual(Array.from(_args), args); done(); } ); }); it('should execute callback with Backup and original args', done => { const id = 'backup-id'; const backupInstance = {}; const args = [{}, {}, {}]; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any, callback: Function) => { callback(null, ...args); }; cluster.backup = (_id: string) => { assert.strictEqual(_id, id); return backupInstance; }; cluster.createBackup( id, { table: 'table-name', }, (err: Error, backup: {}, ..._args: Array<{}>) => { assert.ifError(err); assert.strictEqual(backup, backupInstance); assert.deepStrictEqual(Array.from(_args), args); done(); } ); }); }); describe('delete', () => { it('should make the correct request', done => { // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any, callback: Function) => { assert.strictEqual(config.client, 'BigtableInstanceAdminClient'); assert.strictEqual(config.method, 'deleteCluster'); assert.deepStrictEqual(config.reqOpts, { name: cluster.name, }); assert.deepStrictEqual(config.gaxOpts, {}); callback(); // done() }; cluster.delete(done); }); it('should accept gaxOptions', done => { const gaxOptions = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; cluster.delete(gaxOptions, assert.ifError); }); }); describe('exists', () => { it('should not require gaxOptions', done => { cluster.getMetadata = (gaxOptions: CallOptions) => { assert.deepStrictEqual(gaxOptions, {}); done(); }; cluster.exists(assert.ifError); }); it('should pass gaxOptions to getMetadata', done => { const gaxOptions = {}; cluster.getMetadata = (gaxOptions_: CallOptions) => { assert.strictEqual(gaxOptions_, gaxOptions); done(); }; cluster.exists(gaxOptions, assert.ifError); }); it('should return false if error code is 5', done => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const error: any = new Error('Error.'); error.code = 5; cluster.getMetadata = (gaxOptions: CallOptions, callback: Function) => { callback(error); }; cluster.exists((err: Error, exists: boolean) => { assert.ifError(err); assert.strictEqual(exists, false); done(); }); }); it('should return error if code is not 5', done => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const error: any = new Error('Error.'); error.code = 'NOT-5'; cluster.getMetadata = (_: CallOptions, callback: Function) => { callback(error); }; cluster.exists((err: Error) => { assert.strictEqual(err, error); done(); }); }); it('should return true if no error', done => { cluster.getMetadata = (gaxOptions: CallOptions, callback: Function) => { callback(null, {}); }; cluster.exists((err: Error, exists: boolean) => { assert.ifError(err); assert.strictEqual(exists, true); done(); }); }); }); describe('get', () => { it('should call getMetadata', done => { const gaxOptions = {}; cluster.getMetadata = (gaxOptions_: {}) => { assert.strictEqual(gaxOptions_, gaxOptions); done(); }; cluster.get(gaxOptions, assert.ifError); }); it('should not require gaxOptions', done => { cluster.getMetadata = (gaxOptions: CallOptions) => { assert.deepStrictEqual(gaxOptions, {}); done(); }; cluster.get(assert.ifError); }); it('should return an error from getMetadata', done => { const error = new Error('Error.'); cluster.getMetadata = (gaxOptions: CallOptions, callback: Function) => { callback(error); }; cluster.get((err: Error) => { assert.strictEqual(err, error); done(); }); }); it('should return self and API response', done => { const metadata = {}; cluster.getMetadata = (gaxOptions: CallOptions, callback: Function) => { callback(null, metadata); }; cluster.get((err: Error, cluster_: {}, metadata_: {}) => { assert.ifError(err); assert.strictEqual(cluster_, cluster); assert.strictEqual(metadata_, metadata); done(); }); }); }); describe('getBackups', () => { it('should send the correct request', done => { const options = {a: 'b'}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.client, 'BigtableTableAdminClient'); assert.strictEqual(config.method, 'listBackups'); assert.deepStrictEqual(config.reqOpts, { parent: cluster.name, pageSize: undefined, pageToken: undefined, ...options, }); assert.deepStrictEqual(config.gaxOpts, {}); done(); }; cluster.getBackups(options, assert.ifError); }); it('should locate pagination settings from gaxOptions', done => { const options = { gaxOptions: { pageSize: 'size', pageToken: 'token', }, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual( config.reqOpts.pageSize, options.gaxOptions.pageSize ); assert.strictEqual( config.reqOpts.pageToken, options.gaxOptions.pageToken ); done(); }; cluster.getBackups(options, assert.ifError); }); it('should prefer pageSize and pageToken from options over gaxOptions', done => { const options = { pageSize: 'size-good', pageToken: 'token-good', gaxOptions: { pageSize: 'size-bad', pageToken: 'token-bad', }, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.reqOpts.pageSize, options.pageSize); assert.strictEqual(config.reqOpts.pageToken, options.pageToken); done(); }; cluster.getBackups(options, assert.ifError); }); it('should remove extraneous pagination settings from request', done => { const options = { gaxOptions: { pageSize: 'size', pageToken: 'token', }, autoPaginate: true, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(typeof config.gaxOpts.pageSize, 'undefined'); assert.strictEqual(typeof config.gaxOpts.pageToken, 'undefined'); assert.strictEqual(typeof config.reqOpts.autoPaginate, 'undefined'); done(); }; cluster.getBackups(options, assert.ifError); }); it('should accept gaxOptions', done => { const options = { gaxOptions: {a: 'b'}, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(typeof config.reqOpts.gaxOptions, 'undefined'); assert.deepStrictEqual(config.gaxOpts, options.gaxOptions); done(); }; cluster.getBackups(options, assert.ifError); }); it('should not send gaxOptions as request options', done => { const options = { gaxOptions: {a: 'b'}, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert(Object.keys(options.gaxOptions).every(k => !config.reqOpts[k])); done(); }; cluster.getBackups(options, assert.ifError); }); it('should set autoPaginate from options', done => { const options = { autoPaginate: true, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.gaxOpts.autoPaginate, options.autoPaginate); done(); }; cluster.getBackups(options, assert.ifError); }); it('should prefer autoPaginate from gaxOpts', done => { const options = { autoPaginate: false, gaxOptions: { autoPaginate: true, }, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.gaxOpts.autoPaginate, true); done(); }; cluster.getBackups(options, assert.ifError); }); it('should execute callback with error and correct response arguments', done => { const error = new Error('Error.'); const apiResponse = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any, callback: Function) => { callback(error, [], null, apiResponse); }; cluster.getBackups( (err: Error, backups: [], nextQuery: {}, apiResp: {}) => { assert.strictEqual(err, error); assert.deepStrictEqual(backups, []); assert.strictEqual(nextQuery, null); assert.strictEqual(apiResp, apiResponse); done(); } ); }); it('should execute callback with Backup instances', done => { const rawBackup = {name: 'long/formatted/name', a: 'b'}; const backupInstance = {}; cluster.backup = (id: string) => { assert.strictEqual(id, rawBackup.name.split('/').pop()); return backupInstance; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any, callback: Function) => { callback(null, [rawBackup]); }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.getBackups((err: Error, backups: any[]) => { assert.ifError(err); assert.deepStrictEqual(backups, [backupInstance]); // eslint-disable-next-line @typescript-eslint/no-explicit-any assert.strictEqual((backups[0] as any)!.metadata, rawBackup); done(); }); }); it('should create Backup from correct cluster when using - as an id', done => { cluster.id = '-'; const clusterId = 'cluster-id'; const backupId = 'backup-id'; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any, callback: Function) => { callback(null, [ { name: `projects/project-id/clusters/${clusterId}/backups/${backupId}`, }, ]); }; cluster.instance.cluster = (id: string) => { assert.strictEqual(id, clusterId); return { backup: (id: string) => { assert.strictEqual(id, backupId); setImmediate(done); return {}; }, }; }; cluster.getBackups(assert.ifError); }); it('should execute callback with prepared nextQuery', done => { const options = {pageToken: '1'}; const nextQuery = {pageToken: '2'}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any, callback: Function) => { callback(null, [], nextQuery); }; cluster.getBackups(options, (err: Error, backups: [], _nextQuery: {}) => { assert.ifError(err); assert.deepStrictEqual(_nextQuery, nextQuery); done(); }); }); }); describe('getBackupsStream', () => { it('should make correct request', done => { const options = {a: 'b'}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.client, 'BigtableTableAdminClient'); assert.strictEqual(config.method, 'listBackupsStream'); assert.deepStrictEqual(config.reqOpts, { parent: cluster.name, ...options, }); assert.strictEqual(typeof config.gaxOpts, 'undefined'); setImmediate(done); return new PassThrough(); }; cluster.getBackupsStream(options); }); it('should accept gaxOptions', done => { const options = {gaxOptions: {}}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.gaxOpts, options.gaxOptions); setImmediate(done); return new PassThrough(); }; cluster.getBackupsStream(options); }); it('should not include gaxOptions in reqOpts', done => { const options = {gaxOptions: {a: 'b'}}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert(Object.keys(options.gaxOptions).every(k => !config.reqOpts[k])); setImmediate(done); return new PassThrough(); }; cluster.getBackupsStream(options); }); it('should transform response backups into Backup objects', done => { const rawBackup = {name: 'long/formatted/name', a: 'b'}; const backupInstance = {}; const requestStream = new Readable({ objectMode: true, read() { this.push(rawBackup); this.push(null); }, }); cluster.backup = (id: string) => { assert.strictEqual(id, rawBackup.name.split('/').pop()); return backupInstance; }; cluster.bigtable.request = () => requestStream; cluster .getBackupsStream() .on('error', done) // eslint-disable-next-line @typescript-eslint/no-explicit-any .on('data', (backup: any) => { assert.strictEqual(backup, backupInstance); // eslint-disable-next-line @typescript-eslint/no-explicit-any assert.strictEqual((backup as any).metadata, rawBackup); done(); }); }); it('should create Backup from correct cluster when using - as an id', done => { cluster.id = '-'; const clusterId = 'cluster-id'; const backupId = 'backup-id'; const requestStream = new Readable({ objectMode: true, read() { this.push({ name: `projects/project-id/clusters/${clusterId}/backups/${backupId}`, }); this.push(null); }, }); cluster.instance.cluster = (id: string) => { assert.strictEqual(id, clusterId); return { backup: (id: string) => { assert.strictEqual(id, backupId); setImmediate(done); return {}; }, }; }; cluster.bigtable.request = () => requestStream; cluster.getBackupsStream().on('error', done); }); }); describe('getMetadata', () => { it('should make correct request', done => { // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.client, 'BigtableInstanceAdminClient'); assert.strictEqual(config.method, 'getCluster'); assert.deepStrictEqual(config.reqOpts, { name: cluster.name, }); assert.deepStrictEqual(config.gaxOpts, {}); done(); }; cluster.getMetadata(assert.ifError); }); it('should accept gaxOptions', done => { const gaxOptions = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; cluster.getMetadata(gaxOptions, assert.ifError); }); it('should update metadata', done => { const metadata = {}; cluster.bigtable.request = (config: {}, callback: Function) => { callback(null, metadata); }; cluster.getMetadata(() => { assert.strictEqual(cluster.metadata, metadata); done(); }); }); it('should execute callback with original arguments', done => { const args = [{}, {}]; cluster.bigtable.request = (config: {}, callback: Function) => { callback(...args); }; cluster.getMetadata((...argsies: Array<{}>) => { assert.deepStrictEqual([].slice.call(argsies), args); done(); }); }); }); describe('setMetadata', () => { it('should provide the proper request options', done => { // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any, callback: Function) => { assert.strictEqual(config.client, 'BigtableInstanceAdminClient'); assert.strictEqual(config.method, 'updateCluster'); assert.strictEqual(config.reqOpts.name, CLUSTER_NAME); callback(); // done() }; cluster.setMetadata({}, done); }); it('should respect the nodes option', done => { const options = { nodes: 3, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.reqOpts.serveNodes, options.nodes); done(); }; cluster.setMetadata(options, assert.ifError); }); it('should accept and pass user provided input through', done => { const options = { nodes: 3, location: 'us-west2-b', defaultStorageType: 'exellent_type', }; const expectedReqOpts = Object.assign( {}, {name: CLUSTER_NAME, serveNodes: options.nodes}, options ); delete expectedReqOpts.nodes; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.deepStrictEqual(config.reqOpts, expectedReqOpts); done(); }; cluster.setMetadata(options, assert.ifError); }); it('should respect the gaxOptions', done => { const options = { nodes: 3, }; const gaxOptions = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any cluster.bigtable.request = (config: any) => { assert.strictEqual(config.reqOpts.serveNodes, options.nodes); assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; cluster.setMetadata(options, gaxOptions, assert.ifError); }); it('should execute callback with all arguments', done => { const args = [{}, {}]; cluster.bigtable.request = (config: {}, callback: Function) => { callback(...args); }; cluster.setMetadata({}, (...argsies: Array<{}>) => { assert.deepStrictEqual([].slice.call(argsies), args); done(); }); }); }); });
the_stack
import * as cdk from '@aws-cdk/core'; import * as cfn_parse from '@aws-cdk/core/lib/cfn-parse'; /** * Properties for defining a `AWS::EC2::CapacityReservation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html * @external */ export interface CfnCapacityReservationProps { /** * `AWS::EC2::CapacityReservation.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-availabilityzone * @external */ readonly availabilityZone: string; /** * `AWS::EC2::CapacityReservation.InstanceCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-instancecount * @external */ readonly instanceCount: number; /** * `AWS::EC2::CapacityReservation.InstancePlatform`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-instanceplatform * @external */ readonly instancePlatform: string; /** * `AWS::EC2::CapacityReservation.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-instancetype * @external */ readonly instanceType: string; /** * `AWS::EC2::CapacityReservation.EbsOptimized`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-ebsoptimized * @external */ readonly ebsOptimized?: boolean | cdk.IResolvable; /** * `AWS::EC2::CapacityReservation.EndDate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-enddate * @external */ readonly endDate?: string; /** * `AWS::EC2::CapacityReservation.EndDateType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-enddatetype * @external */ readonly endDateType?: string; /** * `AWS::EC2::CapacityReservation.EphemeralStorage`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-ephemeralstorage * @external */ readonly ephemeralStorage?: boolean | cdk.IResolvable; /** * `AWS::EC2::CapacityReservation.InstanceMatchCriteria`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-instancematchcriteria * @external */ readonly instanceMatchCriteria?: string; /** * `AWS::EC2::CapacityReservation.TagSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-tagspecifications * @external */ readonly tagSpecifications?: Array<CfnCapacityReservation.TagSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::CapacityReservation.Tenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-tenancy * @external */ readonly tenancy?: string; } /** * A CloudFormation `AWS::EC2::CapacityReservation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html * @external * @cloudformationResource AWS::EC2::CapacityReservation */ export declare class CfnCapacityReservation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::CapacityReservation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnCapacityReservation; /** * @external * @cloudformationAttribute AvailabilityZone */ readonly attrAvailabilityZone: string; /** * @external * @cloudformationAttribute AvailableInstanceCount */ readonly attrAvailableInstanceCount: number; /** * @external * @cloudformationAttribute InstanceType */ readonly attrInstanceType: string; /** * @external * @cloudformationAttribute Tenancy */ readonly attrTenancy: string; /** * @external * @cloudformationAttribute TotalInstanceCount */ readonly attrTotalInstanceCount: number; /** * `AWS::EC2::CapacityReservation.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-availabilityzone * @external */ availabilityZone: string; /** * `AWS::EC2::CapacityReservation.InstanceCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-instancecount * @external */ instanceCount: number; /** * `AWS::EC2::CapacityReservation.InstancePlatform`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-instanceplatform * @external */ instancePlatform: string; /** * `AWS::EC2::CapacityReservation.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-instancetype * @external */ instanceType: string; /** * `AWS::EC2::CapacityReservation.EbsOptimized`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-ebsoptimized * @external */ ebsOptimized: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::CapacityReservation.EndDate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-enddate * @external */ endDate: string | undefined; /** * `AWS::EC2::CapacityReservation.EndDateType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-enddatetype * @external */ endDateType: string | undefined; /** * `AWS::EC2::CapacityReservation.EphemeralStorage`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-ephemeralstorage * @external */ ephemeralStorage: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::CapacityReservation.InstanceMatchCriteria`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-instancematchcriteria * @external */ instanceMatchCriteria: string | undefined; /** * `AWS::EC2::CapacityReservation.TagSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-tagspecifications * @external */ tagSpecifications: Array<CfnCapacityReservation.TagSpecificationProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::CapacityReservation.Tenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html#cfn-ec2-capacityreservation-tenancy * @external */ tenancy: string | undefined; /** * Create a new `AWS::EC2::CapacityReservation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnCapacityReservationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::CapacityReservation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-capacityreservation.html * @external * @cloudformationResource AWS::EC2::CapacityReservation */ export declare namespace CfnCapacityReservation { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-capacityreservation-tagspecification.html * @external */ interface TagSpecificationProperty { /** * `CfnCapacityReservation.TagSpecificationProperty.ResourceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-capacityreservation-tagspecification.html#cfn-ec2-capacityreservation-tagspecification-resourcetype * @external */ readonly resourceType?: string; /** * `CfnCapacityReservation.TagSpecificationProperty.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-capacityreservation-tagspecification.html#cfn-ec2-capacityreservation-tagspecification-tags * @external */ readonly tags?: cdk.CfnTag[]; } } /** * Properties for defining a `AWS::EC2::CarrierGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-carriergateway.html * @external */ export interface CfnCarrierGatewayProps { /** * `AWS::EC2::CarrierGateway.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-carriergateway.html#cfn-ec2-carriergateway-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::CarrierGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-carriergateway.html#cfn-ec2-carriergateway-tags * @external */ readonly tags?: CfnCarrierGateway.TagsProperty; } /** * A CloudFormation `AWS::EC2::CarrierGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-carriergateway.html * @external * @cloudformationResource AWS::EC2::CarrierGateway */ export declare class CfnCarrierGateway extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::CarrierGateway"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnCarrierGateway; /** * @external * @cloudformationAttribute CarrierGatewayId */ readonly attrCarrierGatewayId: string; /** * @external * @cloudformationAttribute OwnerId */ readonly attrOwnerId: string; /** * @external * @cloudformationAttribute State */ readonly attrState: string; /** * `AWS::EC2::CarrierGateway.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-carriergateway.html#cfn-ec2-carriergateway-vpcid * @external */ vpcId: string; /** * `AWS::EC2::CarrierGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-carriergateway.html#cfn-ec2-carriergateway-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::CarrierGateway`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnCarrierGatewayProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::CarrierGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-carriergateway.html * @external * @cloudformationResource AWS::EC2::CarrierGateway */ export declare namespace CfnCarrierGateway { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-carriergateway-tags.html * @external */ interface TagsProperty { /** * `CfnCarrierGateway.TagsProperty.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-carriergateway-tags.html#cfn-ec2-carriergateway-tags-tags * @external */ readonly tags?: cdk.CfnTag[]; } } /** * Properties for defining a `AWS::EC2::ClientVpnAuthorizationRule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html * @external */ export interface CfnClientVpnAuthorizationRuleProps { /** * `AWS::EC2::ClientVpnAuthorizationRule.ClientVpnEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-clientvpnendpointid * @external */ readonly clientVpnEndpointId: string; /** * `AWS::EC2::ClientVpnAuthorizationRule.TargetNetworkCidr`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-targetnetworkcidr * @external */ readonly targetNetworkCidr: string; /** * `AWS::EC2::ClientVpnAuthorizationRule.AccessGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-accessgroupid * @external */ readonly accessGroupId?: string; /** * `AWS::EC2::ClientVpnAuthorizationRule.AuthorizeAllGroups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-authorizeallgroups * @external */ readonly authorizeAllGroups?: boolean | cdk.IResolvable; /** * `AWS::EC2::ClientVpnAuthorizationRule.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-description * @external */ readonly description?: string; } /** * A CloudFormation `AWS::EC2::ClientVpnAuthorizationRule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html * @external * @cloudformationResource AWS::EC2::ClientVpnAuthorizationRule */ export declare class CfnClientVpnAuthorizationRule extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::ClientVpnAuthorizationRule"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnClientVpnAuthorizationRule; /** * `AWS::EC2::ClientVpnAuthorizationRule.ClientVpnEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-clientvpnendpointid * @external */ clientVpnEndpointId: string; /** * `AWS::EC2::ClientVpnAuthorizationRule.TargetNetworkCidr`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-targetnetworkcidr * @external */ targetNetworkCidr: string; /** * `AWS::EC2::ClientVpnAuthorizationRule.AccessGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-accessgroupid * @external */ accessGroupId: string | undefined; /** * `AWS::EC2::ClientVpnAuthorizationRule.AuthorizeAllGroups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-authorizeallgroups * @external */ authorizeAllGroups: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::ClientVpnAuthorizationRule.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnauthorizationrule.html#cfn-ec2-clientvpnauthorizationrule-description * @external */ description: string | undefined; /** * Create a new `AWS::EC2::ClientVpnAuthorizationRule`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnClientVpnAuthorizationRuleProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external */ export interface CfnClientVpnEndpointProps { /** * `AWS::EC2::ClientVpnEndpoint.AuthenticationOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-authenticationoptions * @external */ readonly authenticationOptions: Array<CfnClientVpnEndpoint.ClientAuthenticationRequestProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::ClientVpnEndpoint.ClientCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-clientcidrblock * @external */ readonly clientCidrBlock: string; /** * `AWS::EC2::ClientVpnEndpoint.ConnectionLogOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-connectionlogoptions * @external */ readonly connectionLogOptions: CfnClientVpnEndpoint.ConnectionLogOptionsProperty | cdk.IResolvable; /** * `AWS::EC2::ClientVpnEndpoint.ServerCertificateArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-servercertificatearn * @external */ readonly serverCertificateArn: string; /** * `AWS::EC2::ClientVpnEndpoint.ClientConnectOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-clientconnectoptions * @external */ readonly clientConnectOptions?: CfnClientVpnEndpoint.ClientConnectOptionsProperty | cdk.IResolvable; /** * `AWS::EC2::ClientVpnEndpoint.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-description * @external */ readonly description?: string; /** * `AWS::EC2::ClientVpnEndpoint.DnsServers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-dnsservers * @external */ readonly dnsServers?: string[]; /** * `AWS::EC2::ClientVpnEndpoint.SecurityGroupIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-securitygroupids * @external */ readonly securityGroupIds?: string[]; /** * `AWS::EC2::ClientVpnEndpoint.SelfServicePortal`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-selfserviceportal * @external */ readonly selfServicePortal?: string; /** * `AWS::EC2::ClientVpnEndpoint.SplitTunnel`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-splittunnel * @external */ readonly splitTunnel?: boolean | cdk.IResolvable; /** * `AWS::EC2::ClientVpnEndpoint.TagSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-tagspecifications * @external */ readonly tagSpecifications?: Array<CfnClientVpnEndpoint.TagSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::ClientVpnEndpoint.TransportProtocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-transportprotocol * @external */ readonly transportProtocol?: string; /** * `AWS::EC2::ClientVpnEndpoint.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-vpcid * @external */ readonly vpcId?: string; /** * `AWS::EC2::ClientVpnEndpoint.VpnPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-vpnport * @external */ readonly vpnPort?: number; } /** * A CloudFormation `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external * @cloudformationResource AWS::EC2::ClientVpnEndpoint */ export declare class CfnClientVpnEndpoint extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::ClientVpnEndpoint"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnClientVpnEndpoint; /** * `AWS::EC2::ClientVpnEndpoint.AuthenticationOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-authenticationoptions * @external */ authenticationOptions: Array<CfnClientVpnEndpoint.ClientAuthenticationRequestProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::ClientVpnEndpoint.ClientCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-clientcidrblock * @external */ clientCidrBlock: string; /** * `AWS::EC2::ClientVpnEndpoint.ConnectionLogOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-connectionlogoptions * @external */ connectionLogOptions: CfnClientVpnEndpoint.ConnectionLogOptionsProperty | cdk.IResolvable; /** * `AWS::EC2::ClientVpnEndpoint.ServerCertificateArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-servercertificatearn * @external */ serverCertificateArn: string; /** * `AWS::EC2::ClientVpnEndpoint.ClientConnectOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-clientconnectoptions * @external */ clientConnectOptions: CfnClientVpnEndpoint.ClientConnectOptionsProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::ClientVpnEndpoint.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-description * @external */ description: string | undefined; /** * `AWS::EC2::ClientVpnEndpoint.DnsServers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-dnsservers * @external */ dnsServers: string[] | undefined; /** * `AWS::EC2::ClientVpnEndpoint.SecurityGroupIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-securitygroupids * @external */ securityGroupIds: string[] | undefined; /** * `AWS::EC2::ClientVpnEndpoint.SelfServicePortal`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-selfserviceportal * @external */ selfServicePortal: string | undefined; /** * `AWS::EC2::ClientVpnEndpoint.SplitTunnel`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-splittunnel * @external */ splitTunnel: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::ClientVpnEndpoint.TagSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-tagspecifications * @external */ tagSpecifications: Array<CfnClientVpnEndpoint.TagSpecificationProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::ClientVpnEndpoint.TransportProtocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-transportprotocol * @external */ transportProtocol: string | undefined; /** * `AWS::EC2::ClientVpnEndpoint.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-vpcid * @external */ vpcId: string | undefined; /** * `AWS::EC2::ClientVpnEndpoint.VpnPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html#cfn-ec2-clientvpnendpoint-vpnport * @external */ vpnPort: number | undefined; /** * Create a new `AWS::EC2::ClientVpnEndpoint`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnClientVpnEndpointProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external * @cloudformationResource AWS::EC2::ClientVpnEndpoint */ export declare namespace CfnClientVpnEndpoint { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-certificateauthenticationrequest.html * @external */ interface CertificateAuthenticationRequestProperty { /** * `CfnClientVpnEndpoint.CertificateAuthenticationRequestProperty.ClientRootCertificateChainArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-certificateauthenticationrequest.html#cfn-ec2-clientvpnendpoint-certificateauthenticationrequest-clientrootcertificatechainarn * @external */ readonly clientRootCertificateChainArn: string; } } /** * A CloudFormation `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external * @cloudformationResource AWS::EC2::ClientVpnEndpoint */ export declare namespace CfnClientVpnEndpoint { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-clientauthenticationrequest.html * @external */ interface ClientAuthenticationRequestProperty { /** * `CfnClientVpnEndpoint.ClientAuthenticationRequestProperty.ActiveDirectory`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-clientauthenticationrequest.html#cfn-ec2-clientvpnendpoint-clientauthenticationrequest-activedirectory * @external */ readonly activeDirectory?: CfnClientVpnEndpoint.DirectoryServiceAuthenticationRequestProperty | cdk.IResolvable; /** * `CfnClientVpnEndpoint.ClientAuthenticationRequestProperty.FederatedAuthentication`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-clientauthenticationrequest.html#cfn-ec2-clientvpnendpoint-clientauthenticationrequest-federatedauthentication * @external */ readonly federatedAuthentication?: CfnClientVpnEndpoint.FederatedAuthenticationRequestProperty | cdk.IResolvable; /** * `CfnClientVpnEndpoint.ClientAuthenticationRequestProperty.MutualAuthentication`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-clientauthenticationrequest.html#cfn-ec2-clientvpnendpoint-clientauthenticationrequest-mutualauthentication * @external */ readonly mutualAuthentication?: CfnClientVpnEndpoint.CertificateAuthenticationRequestProperty | cdk.IResolvable; /** * `CfnClientVpnEndpoint.ClientAuthenticationRequestProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-clientauthenticationrequest.html#cfn-ec2-clientvpnendpoint-clientauthenticationrequest-type * @external */ readonly type: string; } } /** * A CloudFormation `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external * @cloudformationResource AWS::EC2::ClientVpnEndpoint */ export declare namespace CfnClientVpnEndpoint { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-clientconnectoptions.html * @external */ interface ClientConnectOptionsProperty { /** * `CfnClientVpnEndpoint.ClientConnectOptionsProperty.Enabled`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-clientconnectoptions.html#cfn-ec2-clientvpnendpoint-clientconnectoptions-enabled * @external */ readonly enabled: boolean | cdk.IResolvable; /** * `CfnClientVpnEndpoint.ClientConnectOptionsProperty.LambdaFunctionArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-clientconnectoptions.html#cfn-ec2-clientvpnendpoint-clientconnectoptions-lambdafunctionarn * @external */ readonly lambdaFunctionArn?: string; } } /** * A CloudFormation `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external * @cloudformationResource AWS::EC2::ClientVpnEndpoint */ export declare namespace CfnClientVpnEndpoint { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-connectionlogoptions.html * @external */ interface ConnectionLogOptionsProperty { /** * `CfnClientVpnEndpoint.ConnectionLogOptionsProperty.CloudwatchLogGroup`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-connectionlogoptions.html#cfn-ec2-clientvpnendpoint-connectionlogoptions-cloudwatchloggroup * @external */ readonly cloudwatchLogGroup?: string; /** * `CfnClientVpnEndpoint.ConnectionLogOptionsProperty.CloudwatchLogStream`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-connectionlogoptions.html#cfn-ec2-clientvpnendpoint-connectionlogoptions-cloudwatchlogstream * @external */ readonly cloudwatchLogStream?: string; /** * `CfnClientVpnEndpoint.ConnectionLogOptionsProperty.Enabled`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-connectionlogoptions.html#cfn-ec2-clientvpnendpoint-connectionlogoptions-enabled * @external */ readonly enabled: boolean | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external * @cloudformationResource AWS::EC2::ClientVpnEndpoint */ export declare namespace CfnClientVpnEndpoint { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-directoryserviceauthenticationrequest.html * @external */ interface DirectoryServiceAuthenticationRequestProperty { /** * `CfnClientVpnEndpoint.DirectoryServiceAuthenticationRequestProperty.DirectoryId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-directoryserviceauthenticationrequest.html#cfn-ec2-clientvpnendpoint-directoryserviceauthenticationrequest-directoryid * @external */ readonly directoryId: string; } } /** * A CloudFormation `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external * @cloudformationResource AWS::EC2::ClientVpnEndpoint */ export declare namespace CfnClientVpnEndpoint { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-federatedauthenticationrequest.html * @external */ interface FederatedAuthenticationRequestProperty { /** * `CfnClientVpnEndpoint.FederatedAuthenticationRequestProperty.SAMLProviderArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-federatedauthenticationrequest.html#cfn-ec2-clientvpnendpoint-federatedauthenticationrequest-samlproviderarn * @external */ readonly samlProviderArn: string; /** * `CfnClientVpnEndpoint.FederatedAuthenticationRequestProperty.SelfServiceSAMLProviderArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-federatedauthenticationrequest.html#cfn-ec2-clientvpnendpoint-federatedauthenticationrequest-selfservicesamlproviderarn * @external */ readonly selfServiceSamlProviderArn?: string; } } /** * A CloudFormation `AWS::EC2::ClientVpnEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnendpoint.html * @external * @cloudformationResource AWS::EC2::ClientVpnEndpoint */ export declare namespace CfnClientVpnEndpoint { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-tagspecification.html * @external */ interface TagSpecificationProperty { /** * `CfnClientVpnEndpoint.TagSpecificationProperty.ResourceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-tagspecification.html#cfn-ec2-clientvpnendpoint-tagspecification-resourcetype * @external */ readonly resourceType: string; /** * `CfnClientVpnEndpoint.TagSpecificationProperty.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-clientvpnendpoint-tagspecification.html#cfn-ec2-clientvpnendpoint-tagspecification-tags * @external */ readonly tags: cdk.CfnTag[]; } } /** * Properties for defining a `AWS::EC2::ClientVpnRoute`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html * @external */ export interface CfnClientVpnRouteProps { /** * `AWS::EC2::ClientVpnRoute.ClientVpnEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html#cfn-ec2-clientvpnroute-clientvpnendpointid * @external */ readonly clientVpnEndpointId: string; /** * `AWS::EC2::ClientVpnRoute.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html#cfn-ec2-clientvpnroute-destinationcidrblock * @external */ readonly destinationCidrBlock: string; /** * `AWS::EC2::ClientVpnRoute.TargetVpcSubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html#cfn-ec2-clientvpnroute-targetvpcsubnetid * @external */ readonly targetVpcSubnetId: string; /** * `AWS::EC2::ClientVpnRoute.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html#cfn-ec2-clientvpnroute-description * @external */ readonly description?: string; } /** * A CloudFormation `AWS::EC2::ClientVpnRoute`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html * @external * @cloudformationResource AWS::EC2::ClientVpnRoute */ export declare class CfnClientVpnRoute extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::ClientVpnRoute"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnClientVpnRoute; /** * `AWS::EC2::ClientVpnRoute.ClientVpnEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html#cfn-ec2-clientvpnroute-clientvpnendpointid * @external */ clientVpnEndpointId: string; /** * `AWS::EC2::ClientVpnRoute.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html#cfn-ec2-clientvpnroute-destinationcidrblock * @external */ destinationCidrBlock: string; /** * `AWS::EC2::ClientVpnRoute.TargetVpcSubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html#cfn-ec2-clientvpnroute-targetvpcsubnetid * @external */ targetVpcSubnetId: string; /** * `AWS::EC2::ClientVpnRoute.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpnroute.html#cfn-ec2-clientvpnroute-description * @external */ description: string | undefined; /** * Create a new `AWS::EC2::ClientVpnRoute`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnClientVpnRouteProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::ClientVpnTargetNetworkAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpntargetnetworkassociation.html * @external */ export interface CfnClientVpnTargetNetworkAssociationProps { /** * `AWS::EC2::ClientVpnTargetNetworkAssociation.ClientVpnEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpntargetnetworkassociation.html#cfn-ec2-clientvpntargetnetworkassociation-clientvpnendpointid * @external */ readonly clientVpnEndpointId: string; /** * `AWS::EC2::ClientVpnTargetNetworkAssociation.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpntargetnetworkassociation.html#cfn-ec2-clientvpntargetnetworkassociation-subnetid * @external */ readonly subnetId: string; } /** * A CloudFormation `AWS::EC2::ClientVpnTargetNetworkAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpntargetnetworkassociation.html * @external * @cloudformationResource AWS::EC2::ClientVpnTargetNetworkAssociation */ export declare class CfnClientVpnTargetNetworkAssociation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::ClientVpnTargetNetworkAssociation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnClientVpnTargetNetworkAssociation; /** * `AWS::EC2::ClientVpnTargetNetworkAssociation.ClientVpnEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpntargetnetworkassociation.html#cfn-ec2-clientvpntargetnetworkassociation-clientvpnendpointid * @external */ clientVpnEndpointId: string; /** * `AWS::EC2::ClientVpnTargetNetworkAssociation.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-clientvpntargetnetworkassociation.html#cfn-ec2-clientvpntargetnetworkassociation-subnetid * @external */ subnetId: string; /** * Create a new `AWS::EC2::ClientVpnTargetNetworkAssociation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnClientVpnTargetNetworkAssociationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::CustomerGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html * @external */ export interface CfnCustomerGatewayProps { /** * `AWS::EC2::CustomerGateway.BgpAsn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-bgpasn * @external */ readonly bgpAsn: number; /** * `AWS::EC2::CustomerGateway.IpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-ipaddress * @external */ readonly ipAddress: string; /** * `AWS::EC2::CustomerGateway.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-type * @external */ readonly type: string; /** * `AWS::EC2::CustomerGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::CustomerGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html * @external * @cloudformationResource AWS::EC2::CustomerGateway */ export declare class CfnCustomerGateway extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::CustomerGateway"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnCustomerGateway; /** * `AWS::EC2::CustomerGateway.BgpAsn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-bgpasn * @external */ bgpAsn: number; /** * `AWS::EC2::CustomerGateway.IpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-ipaddress * @external */ ipAddress: string; /** * `AWS::EC2::CustomerGateway.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-type * @external */ type: string; /** * `AWS::EC2::CustomerGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::CustomerGateway`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnCustomerGatewayProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::DHCPOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html * @external */ export interface CfnDHCPOptionsProps { /** * `AWS::EC2::DHCPOptions.DomainName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-domainname * @external */ readonly domainName?: string; /** * `AWS::EC2::DHCPOptions.DomainNameServers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-domainnameservers * @external */ readonly domainNameServers?: string[]; /** * `AWS::EC2::DHCPOptions.NetbiosNameServers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-netbiosnameservers * @external */ readonly netbiosNameServers?: string[]; /** * `AWS::EC2::DHCPOptions.NetbiosNodeType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-netbiosnodetype * @external */ readonly netbiosNodeType?: number; /** * `AWS::EC2::DHCPOptions.NtpServers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-ntpservers * @external */ readonly ntpServers?: string[]; /** * `AWS::EC2::DHCPOptions.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::DHCPOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html * @external * @cloudformationResource AWS::EC2::DHCPOptions */ export declare class CfnDHCPOptions extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::DHCPOptions"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnDHCPOptions; /** * `AWS::EC2::DHCPOptions.DomainName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-domainname * @external */ domainName: string | undefined; /** * `AWS::EC2::DHCPOptions.DomainNameServers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-domainnameservers * @external */ domainNameServers: string[] | undefined; /** * `AWS::EC2::DHCPOptions.NetbiosNameServers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-netbiosnameservers * @external */ netbiosNameServers: string[] | undefined; /** * `AWS::EC2::DHCPOptions.NetbiosNodeType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-netbiosnodetype * @external */ netbiosNodeType: number | undefined; /** * `AWS::EC2::DHCPOptions.NtpServers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-ntpservers * @external */ ntpServers: string[] | undefined; /** * `AWS::EC2::DHCPOptions.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::DHCPOptions`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnDHCPOptionsProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external */ export interface CfnEC2FleetProps { /** * `AWS::EC2::EC2Fleet.LaunchTemplateConfigs`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-launchtemplateconfigs * @external */ readonly launchTemplateConfigs: Array<CfnEC2Fleet.FleetLaunchTemplateConfigRequestProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.TargetCapacitySpecification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-targetcapacityspecification * @external */ readonly targetCapacitySpecification: CfnEC2Fleet.TargetCapacitySpecificationRequestProperty | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.ExcessCapacityTerminationPolicy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-excesscapacityterminationpolicy * @external */ readonly excessCapacityTerminationPolicy?: string; /** * `AWS::EC2::EC2Fleet.OnDemandOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-ondemandoptions * @external */ readonly onDemandOptions?: CfnEC2Fleet.OnDemandOptionsRequestProperty | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.ReplaceUnhealthyInstances`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-replaceunhealthyinstances * @external */ readonly replaceUnhealthyInstances?: boolean | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.SpotOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-spotoptions * @external */ readonly spotOptions?: CfnEC2Fleet.SpotOptionsRequestProperty | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.TagSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-tagspecifications * @external */ readonly tagSpecifications?: Array<CfnEC2Fleet.TagSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.TerminateInstancesWithExpiration`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-terminateinstanceswithexpiration * @external */ readonly terminateInstancesWithExpiration?: boolean | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-type * @external */ readonly type?: string; /** * `AWS::EC2::EC2Fleet.ValidFrom`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-validfrom * @external */ readonly validFrom?: string; /** * `AWS::EC2::EC2Fleet.ValidUntil`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-validuntil * @external */ readonly validUntil?: string; } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare class CfnEC2Fleet extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::EC2Fleet"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnEC2Fleet; /** * `AWS::EC2::EC2Fleet.LaunchTemplateConfigs`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-launchtemplateconfigs * @external */ launchTemplateConfigs: Array<CfnEC2Fleet.FleetLaunchTemplateConfigRequestProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.TargetCapacitySpecification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-targetcapacityspecification * @external */ targetCapacitySpecification: CfnEC2Fleet.TargetCapacitySpecificationRequestProperty | cdk.IResolvable; /** * `AWS::EC2::EC2Fleet.ExcessCapacityTerminationPolicy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-excesscapacityterminationpolicy * @external */ excessCapacityTerminationPolicy: string | undefined; /** * `AWS::EC2::EC2Fleet.OnDemandOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-ondemandoptions * @external */ onDemandOptions: CfnEC2Fleet.OnDemandOptionsRequestProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::EC2Fleet.ReplaceUnhealthyInstances`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-replaceunhealthyinstances * @external */ replaceUnhealthyInstances: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::EC2Fleet.SpotOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-spotoptions * @external */ spotOptions: CfnEC2Fleet.SpotOptionsRequestProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::EC2Fleet.TagSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-tagspecifications * @external */ tagSpecifications: Array<CfnEC2Fleet.TagSpecificationProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::EC2Fleet.TerminateInstancesWithExpiration`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-terminateinstanceswithexpiration * @external */ terminateInstancesWithExpiration: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::EC2Fleet.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-type * @external */ type: string | undefined; /** * `AWS::EC2::EC2Fleet.ValidFrom`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-validfrom * @external */ validFrom: string | undefined; /** * `AWS::EC2::EC2Fleet.ValidUntil`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-validuntil * @external */ validUntil: string | undefined; /** * Create a new `AWS::EC2::EC2Fleet`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnEC2FleetProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-capacityreservationoptionsrequest.html * @external */ interface CapacityReservationOptionsRequestProperty { /** * `CfnEC2Fleet.CapacityReservationOptionsRequestProperty.UsageStrategy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-capacityreservationoptionsrequest.html#cfn-ec2-ec2fleet-capacityreservationoptionsrequest-usagestrategy * @external */ readonly usageStrategy?: string; } } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateconfigrequest.html * @external */ interface FleetLaunchTemplateConfigRequestProperty { /** * `CfnEC2Fleet.FleetLaunchTemplateConfigRequestProperty.LaunchTemplateSpecification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateconfigrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateconfigrequest-launchtemplatespecification * @external */ readonly launchTemplateSpecification?: CfnEC2Fleet.FleetLaunchTemplateSpecificationRequestProperty | cdk.IResolvable; /** * `CfnEC2Fleet.FleetLaunchTemplateConfigRequestProperty.Overrides`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateconfigrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateconfigrequest-overrides * @external */ readonly overrides?: Array<CfnEC2Fleet.FleetLaunchTemplateOverridesRequestProperty | cdk.IResolvable> | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html * @external */ interface FleetLaunchTemplateOverridesRequestProperty { /** * `CfnEC2Fleet.FleetLaunchTemplateOverridesRequestProperty.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-availabilityzone * @external */ readonly availabilityZone?: string; /** * `CfnEC2Fleet.FleetLaunchTemplateOverridesRequestProperty.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-instancetype * @external */ readonly instanceType?: string; /** * `CfnEC2Fleet.FleetLaunchTemplateOverridesRequestProperty.MaxPrice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-maxprice * @external */ readonly maxPrice?: string; /** * `CfnEC2Fleet.FleetLaunchTemplateOverridesRequestProperty.Placement`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-placement * @external */ readonly placement?: CfnEC2Fleet.PlacementProperty | cdk.IResolvable; /** * `CfnEC2Fleet.FleetLaunchTemplateOverridesRequestProperty.Priority`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-priority * @external */ readonly priority?: number; /** * `CfnEC2Fleet.FleetLaunchTemplateOverridesRequestProperty.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-subnetid * @external */ readonly subnetId?: string; /** * `CfnEC2Fleet.FleetLaunchTemplateOverridesRequestProperty.WeightedCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-weightedcapacity * @external */ readonly weightedCapacity?: number; } } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest.html * @external */ interface FleetLaunchTemplateSpecificationRequestProperty { /** * `CfnEC2Fleet.FleetLaunchTemplateSpecificationRequestProperty.LaunchTemplateId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest-launchtemplateid * @external */ readonly launchTemplateId?: string; /** * `CfnEC2Fleet.FleetLaunchTemplateSpecificationRequestProperty.LaunchTemplateName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest-launchtemplatename * @external */ readonly launchTemplateName?: string; /** * `CfnEC2Fleet.FleetLaunchTemplateSpecificationRequestProperty.Version`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest-version * @external */ readonly version?: string; } } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html * @external */ interface OnDemandOptionsRequestProperty { /** * `CfnEC2Fleet.OnDemandOptionsRequestProperty.AllocationStrategy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-allocationstrategy * @external */ readonly allocationStrategy?: string; /** * `CfnEC2Fleet.OnDemandOptionsRequestProperty.CapacityReservationOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-capacityreservationoptions * @external */ readonly capacityReservationOptions?: CfnEC2Fleet.CapacityReservationOptionsRequestProperty | cdk.IResolvable; /** * `CfnEC2Fleet.OnDemandOptionsRequestProperty.MaxTotalPrice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-maxtotalprice * @external */ readonly maxTotalPrice?: string; /** * `CfnEC2Fleet.OnDemandOptionsRequestProperty.MinTargetCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-mintargetcapacity * @external */ readonly minTargetCapacity?: number; /** * `CfnEC2Fleet.OnDemandOptionsRequestProperty.SingleAvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-singleavailabilityzone * @external */ readonly singleAvailabilityZone?: boolean | cdk.IResolvable; /** * `CfnEC2Fleet.OnDemandOptionsRequestProperty.SingleInstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-singleinstancetype * @external */ readonly singleInstanceType?: boolean | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html * @external */ interface PlacementProperty { /** * `CfnEC2Fleet.PlacementProperty.Affinity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html#cfn-ec2-ec2fleet-placement-affinity * @external */ readonly affinity?: string; /** * `CfnEC2Fleet.PlacementProperty.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html#cfn-ec2-ec2fleet-placement-availabilityzone * @external */ readonly availabilityZone?: string; /** * `CfnEC2Fleet.PlacementProperty.GroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html#cfn-ec2-ec2fleet-placement-groupname * @external */ readonly groupName?: string; /** * `CfnEC2Fleet.PlacementProperty.HostId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html#cfn-ec2-ec2fleet-placement-hostid * @external */ readonly hostId?: string; /** * `CfnEC2Fleet.PlacementProperty.HostResourceGroupArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html#cfn-ec2-ec2fleet-placement-hostresourcegrouparn * @external */ readonly hostResourceGroupArn?: string; /** * `CfnEC2Fleet.PlacementProperty.PartitionNumber`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html#cfn-ec2-ec2fleet-placement-partitionnumber * @external */ readonly partitionNumber?: number; /** * `CfnEC2Fleet.PlacementProperty.SpreadDomain`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html#cfn-ec2-ec2fleet-placement-spreaddomain * @external */ readonly spreadDomain?: string; /** * `CfnEC2Fleet.PlacementProperty.Tenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-placement.html#cfn-ec2-ec2fleet-placement-tenancy * @external */ readonly tenancy?: string; } } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html * @external */ interface SpotOptionsRequestProperty { /** * `CfnEC2Fleet.SpotOptionsRequestProperty.AllocationStrategy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-allocationstrategy * @external */ readonly allocationStrategy?: string; /** * `CfnEC2Fleet.SpotOptionsRequestProperty.InstanceInterruptionBehavior`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-instanceinterruptionbehavior * @external */ readonly instanceInterruptionBehavior?: string; /** * `CfnEC2Fleet.SpotOptionsRequestProperty.InstancePoolsToUseCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-instancepoolstousecount * @external */ readonly instancePoolsToUseCount?: number; /** * `CfnEC2Fleet.SpotOptionsRequestProperty.MaxTotalPrice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-maxtotalprice * @external */ readonly maxTotalPrice?: string; /** * `CfnEC2Fleet.SpotOptionsRequestProperty.MinTargetCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-mintargetcapacity * @external */ readonly minTargetCapacity?: number; /** * `CfnEC2Fleet.SpotOptionsRequestProperty.SingleAvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-singleavailabilityzone * @external */ readonly singleAvailabilityZone?: boolean | cdk.IResolvable; /** * `CfnEC2Fleet.SpotOptionsRequestProperty.SingleInstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-singleinstancetype * @external */ readonly singleInstanceType?: boolean | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagspecification.html * @external */ interface TagSpecificationProperty { /** * `CfnEC2Fleet.TagSpecificationProperty.ResourceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagspecification.html#cfn-ec2-ec2fleet-tagspecification-resourcetype * @external */ readonly resourceType?: string; /** * `CfnEC2Fleet.TagSpecificationProperty.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagspecification.html#cfn-ec2-ec2fleet-tagspecification-tags * @external */ readonly tags?: cdk.CfnTag[]; } } /** * A CloudFormation `AWS::EC2::EC2Fleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html * @external * @cloudformationResource AWS::EC2::EC2Fleet */ export declare namespace CfnEC2Fleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html * @external */ interface TargetCapacitySpecificationRequestProperty { /** * `CfnEC2Fleet.TargetCapacitySpecificationRequestProperty.DefaultTargetCapacityType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html#cfn-ec2-ec2fleet-targetcapacityspecificationrequest-defaulttargetcapacitytype * @external */ readonly defaultTargetCapacityType?: string; /** * `CfnEC2Fleet.TargetCapacitySpecificationRequestProperty.OnDemandTargetCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html#cfn-ec2-ec2fleet-targetcapacityspecificationrequest-ondemandtargetcapacity * @external */ readonly onDemandTargetCapacity?: number; /** * `CfnEC2Fleet.TargetCapacitySpecificationRequestProperty.SpotTargetCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html#cfn-ec2-ec2fleet-targetcapacityspecificationrequest-spottargetcapacity * @external */ readonly spotTargetCapacity?: number; /** * `CfnEC2Fleet.TargetCapacitySpecificationRequestProperty.TotalTargetCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html#cfn-ec2-ec2fleet-targetcapacityspecificationrequest-totaltargetcapacity * @external */ readonly totalTargetCapacity: number; } } /** * Properties for defining a `AWS::EC2::EIP`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html * @external */ export interface CfnEIPProps { /** * `AWS::EC2::EIP.Domain`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-domain * @external */ readonly domain?: string; /** * `AWS::EC2::EIP.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-instanceid * @external */ readonly instanceId?: string; /** * `AWS::EC2::EIP.PublicIpv4Pool`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-publicipv4pool * @external */ readonly publicIpv4Pool?: string; /** * `AWS::EC2::EIP.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::EIP`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html * @external * @cloudformationResource AWS::EC2::EIP */ export declare class CfnEIP extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::EIP"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnEIP; /** * @external * @cloudformationAttribute AllocationId */ readonly attrAllocationId: string; /** * `AWS::EC2::EIP.Domain`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-domain * @external */ domain: string | undefined; /** * `AWS::EC2::EIP.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-instanceid * @external */ instanceId: string | undefined; /** * `AWS::EC2::EIP.PublicIpv4Pool`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-publicipv4pool * @external */ publicIpv4Pool: string | undefined; /** * `AWS::EC2::EIP.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::EIP`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnEIPProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::EIPAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html * @external */ export interface CfnEIPAssociationProps { /** * `AWS::EC2::EIPAssociation.AllocationId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-allocationid * @external */ readonly allocationId?: string; /** * `AWS::EC2::EIPAssociation.EIP`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-eip * @external */ readonly eip?: string; /** * `AWS::EC2::EIPAssociation.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-instanceid * @external */ readonly instanceId?: string; /** * `AWS::EC2::EIPAssociation.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-networkinterfaceid * @external */ readonly networkInterfaceId?: string; /** * `AWS::EC2::EIPAssociation.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-PrivateIpAddress * @external */ readonly privateIpAddress?: string; } /** * A CloudFormation `AWS::EC2::EIPAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html * @external * @cloudformationResource AWS::EC2::EIPAssociation */ export declare class CfnEIPAssociation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::EIPAssociation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnEIPAssociation; /** * `AWS::EC2::EIPAssociation.AllocationId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-allocationid * @external */ allocationId: string | undefined; /** * `AWS::EC2::EIPAssociation.EIP`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-eip * @external */ eip: string | undefined; /** * `AWS::EC2::EIPAssociation.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-instanceid * @external */ instanceId: string | undefined; /** * `AWS::EC2::EIPAssociation.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-networkinterfaceid * @external */ networkInterfaceId: string | undefined; /** * `AWS::EC2::EIPAssociation.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-PrivateIpAddress * @external */ privateIpAddress: string | undefined; /** * Create a new `AWS::EC2::EIPAssociation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnEIPAssociationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::EgressOnlyInternetGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-egressonlyinternetgateway.html * @external */ export interface CfnEgressOnlyInternetGatewayProps { /** * `AWS::EC2::EgressOnlyInternetGateway.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-egressonlyinternetgateway.html#cfn-ec2-egressonlyinternetgateway-vpcid * @external */ readonly vpcId: string; } /** * A CloudFormation `AWS::EC2::EgressOnlyInternetGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-egressonlyinternetgateway.html * @external * @cloudformationResource AWS::EC2::EgressOnlyInternetGateway */ export declare class CfnEgressOnlyInternetGateway extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::EgressOnlyInternetGateway"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnEgressOnlyInternetGateway; /** * `AWS::EC2::EgressOnlyInternetGateway.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-egressonlyinternetgateway.html#cfn-ec2-egressonlyinternetgateway-vpcid * @external */ vpcId: string; /** * Create a new `AWS::EC2::EgressOnlyInternetGateway`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnEgressOnlyInternetGatewayProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::FlowLog`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html * @external */ export interface CfnFlowLogProps { /** * `AWS::EC2::FlowLog.ResourceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-resourceid * @external */ readonly resourceId: string; /** * `AWS::EC2::FlowLog.ResourceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-resourcetype * @external */ readonly resourceType: string; /** * `AWS::EC2::FlowLog.TrafficType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-traffictype * @external */ readonly trafficType: string; /** * `AWS::EC2::FlowLog.DeliverLogsPermissionArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-deliverlogspermissionarn * @external */ readonly deliverLogsPermissionArn?: string; /** * `AWS::EC2::FlowLog.LogDestination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-logdestination * @external */ readonly logDestination?: string; /** * `AWS::EC2::FlowLog.LogDestinationType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-logdestinationtype * @external */ readonly logDestinationType?: string; /** * `AWS::EC2::FlowLog.LogFormat`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-logformat * @external */ readonly logFormat?: string; /** * `AWS::EC2::FlowLog.LogGroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-loggroupname * @external */ readonly logGroupName?: string; /** * `AWS::EC2::FlowLog.MaxAggregationInterval`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-maxaggregationinterval * @external */ readonly maxAggregationInterval?: number; /** * `AWS::EC2::FlowLog.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::FlowLog`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html * @external * @cloudformationResource AWS::EC2::FlowLog */ export declare class CfnFlowLog extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::FlowLog"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnFlowLog; /** * @external * @cloudformationAttribute Id */ readonly attrId: string; /** * `AWS::EC2::FlowLog.ResourceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-resourceid * @external */ resourceId: string; /** * `AWS::EC2::FlowLog.ResourceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-resourcetype * @external */ resourceType: string; /** * `AWS::EC2::FlowLog.TrafficType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-traffictype * @external */ trafficType: string; /** * `AWS::EC2::FlowLog.DeliverLogsPermissionArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-deliverlogspermissionarn * @external */ deliverLogsPermissionArn: string | undefined; /** * `AWS::EC2::FlowLog.LogDestination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-logdestination * @external */ logDestination: string | undefined; /** * `AWS::EC2::FlowLog.LogDestinationType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-logdestinationtype * @external */ logDestinationType: string | undefined; /** * `AWS::EC2::FlowLog.LogFormat`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-logformat * @external */ logFormat: string | undefined; /** * `AWS::EC2::FlowLog.LogGroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-loggroupname * @external */ logGroupName: string | undefined; /** * `AWS::EC2::FlowLog.MaxAggregationInterval`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-maxaggregationinterval * @external */ maxAggregationInterval: number | undefined; /** * `AWS::EC2::FlowLog.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::FlowLog`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnFlowLogProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::GatewayRouteTableAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-gatewayroutetableassociation.html * @external */ export interface CfnGatewayRouteTableAssociationProps { /** * `AWS::EC2::GatewayRouteTableAssociation.GatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-gatewayroutetableassociation.html#cfn-ec2-gatewayroutetableassociation-gatewayid * @external */ readonly gatewayId: string; /** * `AWS::EC2::GatewayRouteTableAssociation.RouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-gatewayroutetableassociation.html#cfn-ec2-gatewayroutetableassociation-routetableid * @external */ readonly routeTableId: string; } /** * A CloudFormation `AWS::EC2::GatewayRouteTableAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-gatewayroutetableassociation.html * @external * @cloudformationResource AWS::EC2::GatewayRouteTableAssociation */ export declare class CfnGatewayRouteTableAssociation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::GatewayRouteTableAssociation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnGatewayRouteTableAssociation; /** * @external * @cloudformationAttribute AssociationId */ readonly attrAssociationId: string; /** * `AWS::EC2::GatewayRouteTableAssociation.GatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-gatewayroutetableassociation.html#cfn-ec2-gatewayroutetableassociation-gatewayid * @external */ gatewayId: string; /** * `AWS::EC2::GatewayRouteTableAssociation.RouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-gatewayroutetableassociation.html#cfn-ec2-gatewayroutetableassociation-routetableid * @external */ routeTableId: string; /** * Create a new `AWS::EC2::GatewayRouteTableAssociation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnGatewayRouteTableAssociationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::Host`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html * @external */ export interface CfnHostProps { /** * `AWS::EC2::Host.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-availabilityzone * @external */ readonly availabilityZone: string; /** * `AWS::EC2::Host.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-instancetype * @external */ readonly instanceType: string; /** * `AWS::EC2::Host.AutoPlacement`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-autoplacement * @external */ readonly autoPlacement?: string; /** * `AWS::EC2::Host.HostRecovery`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-hostrecovery * @external */ readonly hostRecovery?: string; } /** * A CloudFormation `AWS::EC2::Host`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html * @external * @cloudformationResource AWS::EC2::Host */ export declare class CfnHost extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::Host"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnHost; /** * `AWS::EC2::Host.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-availabilityzone * @external */ availabilityZone: string; /** * `AWS::EC2::Host.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-instancetype * @external */ instanceType: string; /** * `AWS::EC2::Host.AutoPlacement`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-autoplacement * @external */ autoPlacement: string | undefined; /** * `AWS::EC2::Host.HostRecovery`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-hostrecovery * @external */ hostRecovery: string | undefined; /** * Create a new `AWS::EC2::Host`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnHostProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external */ export interface CfnInstanceProps { /** * `AWS::EC2::Instance.AdditionalInfo`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-additionalinfo * @external */ readonly additionalInfo?: string; /** * `AWS::EC2::Instance.Affinity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-affinity * @external */ readonly affinity?: string; /** * `AWS::EC2::Instance.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-availabilityzone * @external */ readonly availabilityZone?: string; /** * `AWS::EC2::Instance.BlockDeviceMappings`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-blockdevicemappings * @external */ readonly blockDeviceMappings?: Array<CfnInstance.BlockDeviceMappingProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::Instance.CpuOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-cpuoptions * @external */ readonly cpuOptions?: CfnInstance.CpuOptionsProperty | cdk.IResolvable; /** * `AWS::EC2::Instance.CreditSpecification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-creditspecification * @external */ readonly creditSpecification?: CfnInstance.CreditSpecificationProperty | cdk.IResolvable; /** * `AWS::EC2::Instance.DisableApiTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-disableapitermination * @external */ readonly disableApiTermination?: boolean | cdk.IResolvable; /** * `AWS::EC2::Instance.EbsOptimized`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ebsoptimized * @external */ readonly ebsOptimized?: boolean | cdk.IResolvable; /** * `AWS::EC2::Instance.ElasticGpuSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-elasticgpuspecifications * @external */ readonly elasticGpuSpecifications?: Array<CfnInstance.ElasticGpuSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::Instance.ElasticInferenceAccelerators`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-elasticinferenceaccelerators * @external */ readonly elasticInferenceAccelerators?: Array<CfnInstance.ElasticInferenceAcceleratorProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::Instance.HibernationOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-hibernationoptions * @external */ readonly hibernationOptions?: CfnInstance.HibernationOptionsProperty | cdk.IResolvable; /** * `AWS::EC2::Instance.HostId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-hostid * @external */ readonly hostId?: string; /** * `AWS::EC2::Instance.HostResourceGroupArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-hostresourcegrouparn * @external */ readonly hostResourceGroupArn?: string; /** * `AWS::EC2::Instance.IamInstanceProfile`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-iaminstanceprofile * @external */ readonly iamInstanceProfile?: string; /** * `AWS::EC2::Instance.ImageId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-imageid * @external */ readonly imageId?: string; /** * `AWS::EC2::Instance.InstanceInitiatedShutdownBehavior`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-instanceinitiatedshutdownbehavior * @external */ readonly instanceInitiatedShutdownBehavior?: string; /** * `AWS::EC2::Instance.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-instancetype * @external */ readonly instanceType?: string; /** * `AWS::EC2::Instance.Ipv6AddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ipv6addresscount * @external */ readonly ipv6AddressCount?: number; /** * `AWS::EC2::Instance.Ipv6Addresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ipv6addresses * @external */ readonly ipv6Addresses?: Array<CfnInstance.InstanceIpv6AddressProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::Instance.KernelId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-kernelid * @external */ readonly kernelId?: string; /** * `AWS::EC2::Instance.KeyName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-keyname * @external */ readonly keyName?: string; /** * `AWS::EC2::Instance.LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-launchtemplate * @external */ readonly launchTemplate?: CfnInstance.LaunchTemplateSpecificationProperty | cdk.IResolvable; /** * `AWS::EC2::Instance.LicenseSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-licensespecifications * @external */ readonly licenseSpecifications?: Array<CfnInstance.LicenseSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::Instance.Monitoring`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-monitoring * @external */ readonly monitoring?: boolean | cdk.IResolvable; /** * `AWS::EC2::Instance.NetworkInterfaces`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-networkinterfaces * @external */ readonly networkInterfaces?: Array<CfnInstance.NetworkInterfaceProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::Instance.PlacementGroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-placementgroupname * @external */ readonly placementGroupName?: string; /** * `AWS::EC2::Instance.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-privateipaddress * @external */ readonly privateIpAddress?: string; /** * `AWS::EC2::Instance.RamdiskId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ramdiskid * @external */ readonly ramdiskId?: string; /** * `AWS::EC2::Instance.SecurityGroupIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-securitygroupids * @external */ readonly securityGroupIds?: string[]; /** * `AWS::EC2::Instance.SecurityGroups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-securitygroups * @external */ readonly securityGroups?: string[]; /** * `AWS::EC2::Instance.SourceDestCheck`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-sourcedestcheck * @external */ readonly sourceDestCheck?: boolean | cdk.IResolvable; /** * `AWS::EC2::Instance.SsmAssociations`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ssmassociations * @external */ readonly ssmAssociations?: Array<CfnInstance.SsmAssociationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::Instance.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-subnetid * @external */ readonly subnetId?: string; /** * `AWS::EC2::Instance.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-tags * @external */ readonly tags?: cdk.CfnTag[]; /** * `AWS::EC2::Instance.Tenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-tenancy * @external */ readonly tenancy?: string; /** * `AWS::EC2::Instance.UserData`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-userdata * @external */ readonly userData?: string; /** * `AWS::EC2::Instance.Volumes`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-volumes * @external */ readonly volumes?: Array<CfnInstance.VolumeProperty | cdk.IResolvable> | cdk.IResolvable; } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare class CfnInstance extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::Instance"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnInstance; /** * @external * @cloudformationAttribute AvailabilityZone */ readonly attrAvailabilityZone: string; /** * @external * @cloudformationAttribute PrivateDnsName */ readonly attrPrivateDnsName: string; /** * @external * @cloudformationAttribute PrivateIp */ readonly attrPrivateIp: string; /** * @external * @cloudformationAttribute PublicDnsName */ readonly attrPublicDnsName: string; /** * @external * @cloudformationAttribute PublicIp */ readonly attrPublicIp: string; /** * `AWS::EC2::Instance.AdditionalInfo`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-additionalinfo * @external */ additionalInfo: string | undefined; /** * `AWS::EC2::Instance.Affinity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-affinity * @external */ affinity: string | undefined; /** * `AWS::EC2::Instance.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-availabilityzone * @external */ availabilityZone: string | undefined; /** * `AWS::EC2::Instance.BlockDeviceMappings`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-blockdevicemappings * @external */ blockDeviceMappings: Array<CfnInstance.BlockDeviceMappingProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.CpuOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-cpuoptions * @external */ cpuOptions: CfnInstance.CpuOptionsProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.CreditSpecification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-creditspecification * @external */ creditSpecification: CfnInstance.CreditSpecificationProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.DisableApiTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-disableapitermination * @external */ disableApiTermination: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.EbsOptimized`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ebsoptimized * @external */ ebsOptimized: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.ElasticGpuSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-elasticgpuspecifications * @external */ elasticGpuSpecifications: Array<CfnInstance.ElasticGpuSpecificationProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.ElasticInferenceAccelerators`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-elasticinferenceaccelerators * @external */ elasticInferenceAccelerators: Array<CfnInstance.ElasticInferenceAcceleratorProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.HibernationOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-hibernationoptions * @external */ hibernationOptions: CfnInstance.HibernationOptionsProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.HostId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-hostid * @external */ hostId: string | undefined; /** * `AWS::EC2::Instance.HostResourceGroupArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-hostresourcegrouparn * @external */ hostResourceGroupArn: string | undefined; /** * `AWS::EC2::Instance.IamInstanceProfile`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-iaminstanceprofile * @external */ iamInstanceProfile: string | undefined; /** * `AWS::EC2::Instance.ImageId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-imageid * @external */ imageId: string | undefined; /** * `AWS::EC2::Instance.InstanceInitiatedShutdownBehavior`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-instanceinitiatedshutdownbehavior * @external */ instanceInitiatedShutdownBehavior: string | undefined; /** * `AWS::EC2::Instance.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-instancetype * @external */ instanceType: string | undefined; /** * `AWS::EC2::Instance.Ipv6AddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ipv6addresscount * @external */ ipv6AddressCount: number | undefined; /** * `AWS::EC2::Instance.Ipv6Addresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ipv6addresses * @external */ ipv6Addresses: Array<CfnInstance.InstanceIpv6AddressProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.KernelId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-kernelid * @external */ kernelId: string | undefined; /** * `AWS::EC2::Instance.KeyName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-keyname * @external */ keyName: string | undefined; /** * `AWS::EC2::Instance.LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-launchtemplate * @external */ launchTemplate: CfnInstance.LaunchTemplateSpecificationProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.LicenseSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-licensespecifications * @external */ licenseSpecifications: Array<CfnInstance.LicenseSpecificationProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.Monitoring`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-monitoring * @external */ monitoring: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.NetworkInterfaces`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-networkinterfaces * @external */ networkInterfaces: Array<CfnInstance.NetworkInterfaceProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.PlacementGroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-placementgroupname * @external */ placementGroupName: string | undefined; /** * `AWS::EC2::Instance.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-privateipaddress * @external */ privateIpAddress: string | undefined; /** * `AWS::EC2::Instance.RamdiskId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ramdiskid * @external */ ramdiskId: string | undefined; /** * `AWS::EC2::Instance.SecurityGroupIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-securitygroupids * @external */ securityGroupIds: string[] | undefined; /** * `AWS::EC2::Instance.SecurityGroups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-securitygroups * @external */ securityGroups: string[] | undefined; /** * `AWS::EC2::Instance.SourceDestCheck`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-sourcedestcheck * @external */ sourceDestCheck: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.SsmAssociations`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ssmassociations * @external */ ssmAssociations: Array<CfnInstance.SsmAssociationProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::Instance.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-subnetid * @external */ subnetId: string | undefined; /** * `AWS::EC2::Instance.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-tags * @external */ readonly tags: cdk.TagManager; /** * `AWS::EC2::Instance.Tenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-tenancy * @external */ tenancy: string | undefined; /** * `AWS::EC2::Instance.UserData`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-userdata * @external */ userData: string | undefined; /** * `AWS::EC2::Instance.Volumes`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-volumes * @external */ volumes: Array<CfnInstance.VolumeProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * Create a new `AWS::EC2::Instance`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnInstanceProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations-associationparameters.html * @external */ interface AssociationParameterProperty { /** * `CfnInstance.AssociationParameterProperty.Key`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations-associationparameters.html#cfn-ec2-instance-ssmassociations-associationparameters-key * @external */ readonly key: string; /** * `CfnInstance.AssociationParameterProperty.Value`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations-associationparameters.html#cfn-ec2-instance-ssmassociations-associationparameters-value * @external */ readonly value: string[]; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html * @external */ interface BlockDeviceMappingProperty { /** * `CfnInstance.BlockDeviceMappingProperty.DeviceName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html#cfn-ec2-blockdev-mapping-devicename * @external */ readonly deviceName: string; /** * `CfnInstance.BlockDeviceMappingProperty.Ebs`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html#cfn-ec2-blockdev-mapping-ebs * @external */ readonly ebs?: CfnInstance.EbsProperty | cdk.IResolvable; /** * `CfnInstance.BlockDeviceMappingProperty.NoDevice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html#cfn-ec2-blockdev-mapping-nodevice * @external */ readonly noDevice?: CfnInstance.NoDeviceProperty | cdk.IResolvable; /** * `CfnInstance.BlockDeviceMappingProperty.VirtualName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html#cfn-ec2-blockdev-mapping-virtualname * @external */ readonly virtualName?: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-cpuoptions.html * @external */ interface CpuOptionsProperty { /** * `CfnInstance.CpuOptionsProperty.CoreCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-cpuoptions.html#cfn-ec2-instance-cpuoptions-corecount * @external */ readonly coreCount?: number; /** * `CfnInstance.CpuOptionsProperty.ThreadsPerCore`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-cpuoptions.html#cfn-ec2-instance-cpuoptions-threadspercore * @external */ readonly threadsPerCore?: number; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-creditspecification.html * @external */ interface CreditSpecificationProperty { /** * `CfnInstance.CreditSpecificationProperty.CPUCredits`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-creditspecification.html#cfn-ec2-instance-creditspecification-cpucredits * @external */ readonly cpuCredits?: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html * @external */ interface EbsProperty { /** * `CfnInstance.EbsProperty.DeleteOnTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-deleteontermination * @external */ readonly deleteOnTermination?: boolean | cdk.IResolvable; /** * `CfnInstance.EbsProperty.Encrypted`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-encrypted * @external */ readonly encrypted?: boolean | cdk.IResolvable; /** * `CfnInstance.EbsProperty.Iops`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-iops * @external */ readonly iops?: number; /** * `CfnInstance.EbsProperty.KmsKeyId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-instance-ebs-kmskeyid * @external */ readonly kmsKeyId?: string; /** * `CfnInstance.EbsProperty.SnapshotId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-snapshotid * @external */ readonly snapshotId?: string; /** * `CfnInstance.EbsProperty.VolumeSize`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-volumesize * @external */ readonly volumeSize?: number; /** * `CfnInstance.EbsProperty.VolumeType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-volumetype * @external */ readonly volumeType?: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-elasticgpuspecification.html * @external */ interface ElasticGpuSpecificationProperty { /** * `CfnInstance.ElasticGpuSpecificationProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-elasticgpuspecification.html#cfn-ec2-instance-elasticgpuspecification-type * @external */ readonly type: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-elasticinferenceaccelerator.html * @external */ interface ElasticInferenceAcceleratorProperty { /** * `CfnInstance.ElasticInferenceAcceleratorProperty.Count`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-elasticinferenceaccelerator.html#cfn-ec2-instance-elasticinferenceaccelerator-count * @external */ readonly count?: number; /** * `CfnInstance.ElasticInferenceAcceleratorProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-elasticinferenceaccelerator.html#cfn-ec2-instance-elasticinferenceaccelerator-type * @external */ readonly type: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-hibernationoptions.html * @external */ interface HibernationOptionsProperty { /** * `CfnInstance.HibernationOptionsProperty.Configured`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-hibernationoptions.html#cfn-ec2-instance-hibernationoptions-configured * @external */ readonly configured?: boolean | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-instanceipv6address.html * @external */ interface InstanceIpv6AddressProperty { /** * `CfnInstance.InstanceIpv6AddressProperty.Ipv6Address`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-instanceipv6address.html#cfn-ec2-instance-instanceipv6address-ipv6address * @external */ readonly ipv6Address: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-launchtemplatespecification.html * @external */ interface LaunchTemplateSpecificationProperty { /** * `CfnInstance.LaunchTemplateSpecificationProperty.LaunchTemplateId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-launchtemplatespecification.html#cfn-ec2-instance-launchtemplatespecification-launchtemplateid * @external */ readonly launchTemplateId?: string; /** * `CfnInstance.LaunchTemplateSpecificationProperty.LaunchTemplateName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-launchtemplatespecification.html#cfn-ec2-instance-launchtemplatespecification-launchtemplatename * @external */ readonly launchTemplateName?: string; /** * `CfnInstance.LaunchTemplateSpecificationProperty.Version`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-launchtemplatespecification.html#cfn-ec2-instance-launchtemplatespecification-version * @external */ readonly version: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-licensespecification.html * @external */ interface LicenseSpecificationProperty { /** * `CfnInstance.LicenseSpecificationProperty.LicenseConfigurationArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-licensespecification.html#cfn-ec2-instance-licensespecification-licenseconfigurationarn * @external */ readonly licenseConfigurationArn: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html * @external */ interface NetworkInterfaceProperty { /** * `CfnInstance.NetworkInterfaceProperty.AssociatePublicIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-associatepubip * @external */ readonly associatePublicIpAddress?: boolean | cdk.IResolvable; /** * `CfnInstance.NetworkInterfaceProperty.DeleteOnTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-delete * @external */ readonly deleteOnTermination?: boolean | cdk.IResolvable; /** * `CfnInstance.NetworkInterfaceProperty.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-description * @external */ readonly description?: string; /** * `CfnInstance.NetworkInterfaceProperty.DeviceIndex`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-deviceindex * @external */ readonly deviceIndex: string; /** * `CfnInstance.NetworkInterfaceProperty.GroupSet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-groupset * @external */ readonly groupSet?: string[]; /** * `CfnInstance.NetworkInterfaceProperty.Ipv6AddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#cfn-ec2-instance-networkinterface-ipv6addresscount * @external */ readonly ipv6AddressCount?: number; /** * `CfnInstance.NetworkInterfaceProperty.Ipv6Addresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#cfn-ec2-instance-networkinterface-ipv6addresses * @external */ readonly ipv6Addresses?: Array<CfnInstance.InstanceIpv6AddressProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnInstance.NetworkInterfaceProperty.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-network-iface * @external */ readonly networkInterfaceId?: string; /** * `CfnInstance.NetworkInterfaceProperty.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-privateipaddress * @external */ readonly privateIpAddress?: string; /** * `CfnInstance.NetworkInterfaceProperty.PrivateIpAddresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-privateipaddresses * @external */ readonly privateIpAddresses?: Array<CfnInstance.PrivateIpAddressSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnInstance.NetworkInterfaceProperty.SecondaryPrivateIpAddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-secondprivateip * @external */ readonly secondaryPrivateIpAddressCount?: number; /** * `CfnInstance.NetworkInterfaceProperty.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-subnetid * @external */ readonly subnetId?: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-nodevice.html * @external */ interface NoDeviceProperty { } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html * @external */ interface PrivateIpAddressSpecificationProperty { /** * `CfnInstance.PrivateIpAddressSpecificationProperty.Primary`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-primary * @external */ readonly primary: boolean | cdk.IResolvable; /** * `CfnInstance.PrivateIpAddressSpecificationProperty.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-privateipaddress * @external */ readonly privateIpAddress: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations.html * @external */ interface SsmAssociationProperty { /** * `CfnInstance.SsmAssociationProperty.AssociationParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations.html#cfn-ec2-instance-ssmassociations-associationparameters * @external */ readonly associationParameters?: Array<CfnInstance.AssociationParameterProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnInstance.SsmAssociationProperty.DocumentName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations.html#cfn-ec2-instance-ssmassociations-documentname * @external */ readonly documentName: string; } } /** * A CloudFormation `AWS::EC2::Instance`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html * @external * @cloudformationResource AWS::EC2::Instance */ export declare namespace CfnInstance { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-mount-point.html * @external */ interface VolumeProperty { /** * `CfnInstance.VolumeProperty.Device`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-mount-point.html#cfn-ec2-mountpoint-device * @external */ readonly device: string; /** * `CfnInstance.VolumeProperty.VolumeId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-mount-point.html#cfn-ec2-mountpoint-volumeid * @external */ readonly volumeId: string; } } /** * Properties for defining a `AWS::EC2::InternetGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html * @external */ export interface CfnInternetGatewayProps { /** * `AWS::EC2::InternetGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html#cfn-ec2-internetgateway-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::InternetGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html * @external * @cloudformationResource AWS::EC2::InternetGateway */ export declare class CfnInternetGateway extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::InternetGateway"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnInternetGateway; /** * `AWS::EC2::InternetGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html#cfn-ec2-internetgateway-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::InternetGateway`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnInternetGatewayProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external */ export interface CfnLaunchTemplateProps { /** * `AWS::EC2::LaunchTemplate.LaunchTemplateData`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html#cfn-ec2-launchtemplate-launchtemplatedata * @external */ readonly launchTemplateData?: CfnLaunchTemplate.LaunchTemplateDataProperty | cdk.IResolvable; /** * `AWS::EC2::LaunchTemplate.LaunchTemplateName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html#cfn-ec2-launchtemplate-launchtemplatename * @external */ readonly launchTemplateName?: string; } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare class CfnLaunchTemplate extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::LaunchTemplate"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnLaunchTemplate; /** * @external * @cloudformationAttribute DefaultVersionNumber */ readonly attrDefaultVersionNumber: string; /** * @external * @cloudformationAttribute LatestVersionNumber */ readonly attrLatestVersionNumber: string; /** * `AWS::EC2::LaunchTemplate.LaunchTemplateData`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html#cfn-ec2-launchtemplate-launchtemplatedata * @external */ launchTemplateData: CfnLaunchTemplate.LaunchTemplateDataProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::LaunchTemplate.LaunchTemplateName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html#cfn-ec2-launchtemplate-launchtemplatename * @external */ launchTemplateName: string | undefined; /** * Create a new `AWS::EC2::LaunchTemplate`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnLaunchTemplateProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html * @external */ interface BlockDeviceMappingProperty { /** * `CfnLaunchTemplate.BlockDeviceMappingProperty.DeviceName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html#cfn-ec2-launchtemplate-blockdevicemapping-devicename * @external */ readonly deviceName?: string; /** * `CfnLaunchTemplate.BlockDeviceMappingProperty.Ebs`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs * @external */ readonly ebs?: CfnLaunchTemplate.EbsProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.BlockDeviceMappingProperty.NoDevice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html#cfn-ec2-launchtemplate-blockdevicemapping-nodevice * @external */ readonly noDevice?: string; /** * `CfnLaunchTemplate.BlockDeviceMappingProperty.VirtualName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html#cfn-ec2-launchtemplate-blockdevicemapping-virtualname * @external */ readonly virtualName?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification.html * @external */ interface CapacityReservationSpecificationProperty { /** * `CfnLaunchTemplate.CapacityReservationSpecificationProperty.CapacityReservationPreference`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification.html#cfn-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification-capacityreservationpreference * @external */ readonly capacityReservationPreference?: string; /** * `CfnLaunchTemplate.CapacityReservationSpecificationProperty.CapacityReservationTarget`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification.html#cfn-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification-capacityreservationtarget * @external */ readonly capacityReservationTarget?: CfnLaunchTemplate.CapacityReservationTargetProperty | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-capacityreservationtarget.html * @external */ interface CapacityReservationTargetProperty { /** * `CfnLaunchTemplate.CapacityReservationTargetProperty.CapacityReservationId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-capacityreservationtarget.html#cfn-ec2-launchtemplate-capacityreservationtarget-capacityreservationid * @external */ readonly capacityReservationId?: string; /** * `CfnLaunchTemplate.CapacityReservationTargetProperty.CapacityReservationResourceGroupArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-capacityreservationtarget.html#cfn-ec2-launchtemplate-capacityreservationtarget-capacityreservationresourcegrouparn * @external */ readonly capacityReservationResourceGroupArn?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-cpuoptions.html * @external */ interface CpuOptionsProperty { /** * `CfnLaunchTemplate.CpuOptionsProperty.CoreCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-cpuoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-cpuoptions-corecount * @external */ readonly coreCount?: number; /** * `CfnLaunchTemplate.CpuOptionsProperty.ThreadsPerCore`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-cpuoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-cpuoptions-threadspercore * @external */ readonly threadsPerCore?: number; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-creditspecification.html * @external */ interface CreditSpecificationProperty { /** * `CfnLaunchTemplate.CreditSpecificationProperty.CpuCredits`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-creditspecification.html#cfn-ec2-launchtemplate-launchtemplatedata-creditspecification-cpucredits * @external */ readonly cpuCredits?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html * @external */ interface EbsProperty { /** * `CfnLaunchTemplate.EbsProperty.DeleteOnTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-deleteontermination * @external */ readonly deleteOnTermination?: boolean | cdk.IResolvable; /** * `CfnLaunchTemplate.EbsProperty.Encrypted`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-encrypted * @external */ readonly encrypted?: boolean | cdk.IResolvable; /** * `CfnLaunchTemplate.EbsProperty.Iops`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-iops * @external */ readonly iops?: number; /** * `CfnLaunchTemplate.EbsProperty.KmsKeyId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-kmskeyid * @external */ readonly kmsKeyId?: string; /** * `CfnLaunchTemplate.EbsProperty.SnapshotId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-snapshotid * @external */ readonly snapshotId?: string; /** * `CfnLaunchTemplate.EbsProperty.VolumeSize`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-volumesize * @external */ readonly volumeSize?: number; /** * `CfnLaunchTemplate.EbsProperty.VolumeType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-volumetype * @external */ readonly volumeType?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-elasticgpuspecification.html * @external */ interface ElasticGpuSpecificationProperty { /** * `CfnLaunchTemplate.ElasticGpuSpecificationProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-elasticgpuspecification.html#cfn-ec2-launchtemplate-elasticgpuspecification-type * @external */ readonly type?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-hibernationoptions.html * @external */ interface HibernationOptionsProperty { /** * `CfnLaunchTemplate.HibernationOptionsProperty.Configured`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-hibernationoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-hibernationoptions-configured * @external */ readonly configured?: boolean | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile.html * @external */ interface IamInstanceProfileProperty { /** * `CfnLaunchTemplate.IamInstanceProfileProperty.Arn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile.html#cfn-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile-arn * @external */ readonly arn?: string; /** * `CfnLaunchTemplate.IamInstanceProfileProperty.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile.html#cfn-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile-name * @external */ readonly name?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions.html * @external */ interface InstanceMarketOptionsProperty { /** * `CfnLaunchTemplate.InstanceMarketOptionsProperty.MarketType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-markettype * @external */ readonly marketType?: string; /** * `CfnLaunchTemplate.InstanceMarketOptionsProperty.SpotOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions * @external */ readonly spotOptions?: CfnLaunchTemplate.SpotOptionsProperty | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-ipv6add.html * @external */ interface Ipv6AddProperty { /** * `CfnLaunchTemplate.Ipv6AddProperty.Ipv6Address`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-ipv6add.html#cfn-ec2-launchtemplate-ipv6add-ipv6address * @external */ readonly ipv6Address?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html * @external */ interface LaunchTemplateDataProperty { /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.BlockDeviceMappings`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-blockdevicemappings * @external */ readonly blockDeviceMappings?: Array<CfnLaunchTemplate.BlockDeviceMappingProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.CapacityReservationSpecification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification * @external */ readonly capacityReservationSpecification?: CfnLaunchTemplate.CapacityReservationSpecificationProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.CpuOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-cpuoptions * @external */ readonly cpuOptions?: CfnLaunchTemplate.CpuOptionsProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.CreditSpecification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-creditspecification * @external */ readonly creditSpecification?: CfnLaunchTemplate.CreditSpecificationProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.DisableApiTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-disableapitermination * @external */ readonly disableApiTermination?: boolean | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.EbsOptimized`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-ebsoptimized * @external */ readonly ebsOptimized?: boolean | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.ElasticGpuSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-elasticgpuspecifications * @external */ readonly elasticGpuSpecifications?: Array<CfnLaunchTemplate.ElasticGpuSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.ElasticInferenceAccelerators`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-elasticinferenceaccelerators * @external */ readonly elasticInferenceAccelerators?: Array<CfnLaunchTemplate.LaunchTemplateElasticInferenceAcceleratorProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.HibernationOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-hibernationoptions * @external */ readonly hibernationOptions?: CfnLaunchTemplate.HibernationOptionsProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.IamInstanceProfile`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile * @external */ readonly iamInstanceProfile?: CfnLaunchTemplate.IamInstanceProfileProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.ImageId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-imageid * @external */ readonly imageId?: string; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.InstanceInitiatedShutdownBehavior`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-instanceinitiatedshutdownbehavior * @external */ readonly instanceInitiatedShutdownBehavior?: string; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.InstanceMarketOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions * @external */ readonly instanceMarketOptions?: CfnLaunchTemplate.InstanceMarketOptionsProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-instancetype * @external */ readonly instanceType?: string; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.KernelId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-kernelid * @external */ readonly kernelId?: string; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.KeyName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-keyname * @external */ readonly keyName?: string; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.LicenseSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-licensespecifications * @external */ readonly licenseSpecifications?: Array<CfnLaunchTemplate.LicenseSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.MetadataOptions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-metadataoptions * @external */ readonly metadataOptions?: CfnLaunchTemplate.MetadataOptionsProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.Monitoring`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-monitoring * @external */ readonly monitoring?: CfnLaunchTemplate.MonitoringProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.NetworkInterfaces`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-networkinterfaces * @external */ readonly networkInterfaces?: Array<CfnLaunchTemplate.NetworkInterfaceProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.Placement`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-placement * @external */ readonly placement?: CfnLaunchTemplate.PlacementProperty | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.RamDiskId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-ramdiskid * @external */ readonly ramDiskId?: string; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.SecurityGroupIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-securitygroupids * @external */ readonly securityGroupIds?: string[]; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.SecurityGroups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-securitygroups * @external */ readonly securityGroups?: string[]; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.TagSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-tagspecifications * @external */ readonly tagSpecifications?: Array<CfnLaunchTemplate.TagSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnLaunchTemplate.LaunchTemplateDataProperty.UserData`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-userdata * @external */ readonly userData?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator.html * @external */ interface LaunchTemplateElasticInferenceAcceleratorProperty { /** * `CfnLaunchTemplate.LaunchTemplateElasticInferenceAcceleratorProperty.Count`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator.html#cfn-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator-count * @external */ readonly count?: number; /** * `CfnLaunchTemplate.LaunchTemplateElasticInferenceAcceleratorProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator.html#cfn-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator-type * @external */ readonly type?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-licensespecification.html * @external */ interface LicenseSpecificationProperty { /** * `CfnLaunchTemplate.LicenseSpecificationProperty.LicenseConfigurationArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-licensespecification.html#cfn-ec2-launchtemplate-licensespecification-licenseconfigurationarn * @external */ readonly licenseConfigurationArn?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-metadataoptions.html * @external */ interface MetadataOptionsProperty { /** * `CfnLaunchTemplate.MetadataOptionsProperty.HttpEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-metadataoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-metadataoptions-httpendpoint * @external */ readonly httpEndpoint?: string; /** * `CfnLaunchTemplate.MetadataOptionsProperty.HttpPutResponseHopLimit`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-metadataoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-metadataoptions-httpputresponsehoplimit * @external */ readonly httpPutResponseHopLimit?: number; /** * `CfnLaunchTemplate.MetadataOptionsProperty.HttpTokens`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-metadataoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-metadataoptions-httptokens * @external */ readonly httpTokens?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-monitoring.html * @external */ interface MonitoringProperty { /** * `CfnLaunchTemplate.MonitoringProperty.Enabled`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-monitoring.html#cfn-ec2-launchtemplate-launchtemplatedata-monitoring-enabled * @external */ readonly enabled?: boolean | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html * @external */ interface NetworkInterfaceProperty { /** * `CfnLaunchTemplate.NetworkInterfaceProperty.AssociateCarrierIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-associatecarrieripaddress * @external */ readonly associateCarrierIpAddress?: boolean | cdk.IResolvable; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.AssociatePublicIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-associatepublicipaddress * @external */ readonly associatePublicIpAddress?: boolean | cdk.IResolvable; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.DeleteOnTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-deleteontermination * @external */ readonly deleteOnTermination?: boolean | cdk.IResolvable; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-description * @external */ readonly description?: string; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.DeviceIndex`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-deviceindex * @external */ readonly deviceIndex?: number; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.Groups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-groups * @external */ readonly groups?: string[]; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.InterfaceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-interfacetype * @external */ readonly interfaceType?: string; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.Ipv6AddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-ipv6addresscount * @external */ readonly ipv6AddressCount?: number; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.Ipv6Addresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-ipv6addresses * @external */ readonly ipv6Addresses?: Array<CfnLaunchTemplate.Ipv6AddProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.NetworkCardIndex`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-networkcardindex * @external */ readonly networkCardIndex?: number; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-networkinterfaceid * @external */ readonly networkInterfaceId?: string; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-privateipaddress * @external */ readonly privateIpAddress?: string; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.PrivateIpAddresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-privateipaddresses * @external */ readonly privateIpAddresses?: Array<CfnLaunchTemplate.PrivateIpAddProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.SecondaryPrivateIpAddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-secondaryprivateipaddresscount * @external */ readonly secondaryPrivateIpAddressCount?: number; /** * `CfnLaunchTemplate.NetworkInterfaceProperty.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-subnetid * @external */ readonly subnetId?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html * @external */ interface PlacementProperty { /** * `CfnLaunchTemplate.PlacementProperty.Affinity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-affinity * @external */ readonly affinity?: string; /** * `CfnLaunchTemplate.PlacementProperty.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-availabilityzone * @external */ readonly availabilityZone?: string; /** * `CfnLaunchTemplate.PlacementProperty.GroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-groupname * @external */ readonly groupName?: string; /** * `CfnLaunchTemplate.PlacementProperty.HostId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-hostid * @external */ readonly hostId?: string; /** * `CfnLaunchTemplate.PlacementProperty.HostResourceGroupArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-hostresourcegrouparn * @external */ readonly hostResourceGroupArn?: string; /** * `CfnLaunchTemplate.PlacementProperty.PartitionNumber`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-partitionnumber * @external */ readonly partitionNumber?: number; /** * `CfnLaunchTemplate.PlacementProperty.SpreadDomain`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-spreaddomain * @external */ readonly spreadDomain?: string; /** * `CfnLaunchTemplate.PlacementProperty.Tenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-tenancy * @external */ readonly tenancy?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-privateipadd.html * @external */ interface PrivateIpAddProperty { /** * `CfnLaunchTemplate.PrivateIpAddProperty.Primary`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-privateipadd.html#cfn-ec2-launchtemplate-privateipadd-primary * @external */ readonly primary?: boolean | cdk.IResolvable; /** * `CfnLaunchTemplate.PrivateIpAddProperty.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-privateipadd.html#cfn-ec2-launchtemplate-privateipadd-privateipaddress * @external */ readonly privateIpAddress?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html * @external */ interface SpotOptionsProperty { /** * `CfnLaunchTemplate.SpotOptionsProperty.BlockDurationMinutes`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-blockdurationminutes * @external */ readonly blockDurationMinutes?: number; /** * `CfnLaunchTemplate.SpotOptionsProperty.InstanceInterruptionBehavior`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-instanceinterruptionbehavior * @external */ readonly instanceInterruptionBehavior?: string; /** * `CfnLaunchTemplate.SpotOptionsProperty.MaxPrice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-maxprice * @external */ readonly maxPrice?: string; /** * `CfnLaunchTemplate.SpotOptionsProperty.SpotInstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-spotinstancetype * @external */ readonly spotInstanceType?: string; /** * `CfnLaunchTemplate.SpotOptionsProperty.ValidUntil`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-validuntil * @external */ readonly validUntil?: string; } } /** * A CloudFormation `AWS::EC2::LaunchTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html * @external * @cloudformationResource AWS::EC2::LaunchTemplate */ export declare namespace CfnLaunchTemplate { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-tagspecification.html * @external */ interface TagSpecificationProperty { /** * `CfnLaunchTemplate.TagSpecificationProperty.ResourceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-tagspecification.html#cfn-ec2-launchtemplate-tagspecification-resourcetype * @external */ readonly resourceType?: string; /** * `CfnLaunchTemplate.TagSpecificationProperty.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-tagspecification.html#cfn-ec2-launchtemplate-tagspecification-tags * @external */ readonly tags?: cdk.CfnTag[]; } } /** * Properties for defining a `AWS::EC2::LocalGatewayRoute`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroute.html * @external */ export interface CfnLocalGatewayRouteProps { /** * `AWS::EC2::LocalGatewayRoute.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroute.html#cfn-ec2-localgatewayroute-destinationcidrblock * @external */ readonly destinationCidrBlock: string; /** * `AWS::EC2::LocalGatewayRoute.LocalGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroute.html#cfn-ec2-localgatewayroute-localgatewayroutetableid * @external */ readonly localGatewayRouteTableId: string; /** * `AWS::EC2::LocalGatewayRoute.LocalGatewayVirtualInterfaceGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroute.html#cfn-ec2-localgatewayroute-localgatewayvirtualinterfacegroupid * @external */ readonly localGatewayVirtualInterfaceGroupId: string; } /** * A CloudFormation `AWS::EC2::LocalGatewayRoute`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroute.html * @external * @cloudformationResource AWS::EC2::LocalGatewayRoute */ export declare class CfnLocalGatewayRoute extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::LocalGatewayRoute"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnLocalGatewayRoute; /** * @external * @cloudformationAttribute State */ readonly attrState: string; /** * @external * @cloudformationAttribute Type */ readonly attrType: string; /** * `AWS::EC2::LocalGatewayRoute.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroute.html#cfn-ec2-localgatewayroute-destinationcidrblock * @external */ destinationCidrBlock: string; /** * `AWS::EC2::LocalGatewayRoute.LocalGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroute.html#cfn-ec2-localgatewayroute-localgatewayroutetableid * @external */ localGatewayRouteTableId: string; /** * `AWS::EC2::LocalGatewayRoute.LocalGatewayVirtualInterfaceGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroute.html#cfn-ec2-localgatewayroute-localgatewayvirtualinterfacegroupid * @external */ localGatewayVirtualInterfaceGroupId: string; /** * Create a new `AWS::EC2::LocalGatewayRoute`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnLocalGatewayRouteProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::LocalGatewayRouteTableVPCAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html * @external */ export interface CfnLocalGatewayRouteTableVPCAssociationProps { /** * `AWS::EC2::LocalGatewayRouteTableVPCAssociation.LocalGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html#cfn-ec2-localgatewayroutetablevpcassociation-localgatewayroutetableid * @external */ readonly localGatewayRouteTableId: string; /** * `AWS::EC2::LocalGatewayRouteTableVPCAssociation.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html#cfn-ec2-localgatewayroutetablevpcassociation-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::LocalGatewayRouteTableVPCAssociation.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html#cfn-ec2-localgatewayroutetablevpcassociation-tags * @external */ readonly tags?: CfnLocalGatewayRouteTableVPCAssociation.TagsProperty; } /** * A CloudFormation `AWS::EC2::LocalGatewayRouteTableVPCAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html * @external * @cloudformationResource AWS::EC2::LocalGatewayRouteTableVPCAssociation */ export declare class CfnLocalGatewayRouteTableVPCAssociation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::LocalGatewayRouteTableVPCAssociation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnLocalGatewayRouteTableVPCAssociation; /** * @external * @cloudformationAttribute LocalGatewayId */ readonly attrLocalGatewayId: string; /** * @external * @cloudformationAttribute LocalGatewayRouteTableVpcAssociationId */ readonly attrLocalGatewayRouteTableVpcAssociationId: string; /** * @external * @cloudformationAttribute State */ readonly attrState: string; /** * `AWS::EC2::LocalGatewayRouteTableVPCAssociation.LocalGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html#cfn-ec2-localgatewayroutetablevpcassociation-localgatewayroutetableid * @external */ localGatewayRouteTableId: string; /** * `AWS::EC2::LocalGatewayRouteTableVPCAssociation.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html#cfn-ec2-localgatewayroutetablevpcassociation-vpcid * @external */ vpcId: string; /** * `AWS::EC2::LocalGatewayRouteTableVPCAssociation.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html#cfn-ec2-localgatewayroutetablevpcassociation-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::LocalGatewayRouteTableVPCAssociation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnLocalGatewayRouteTableVPCAssociationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::LocalGatewayRouteTableVPCAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-localgatewayroutetablevpcassociation.html * @external * @cloudformationResource AWS::EC2::LocalGatewayRouteTableVPCAssociation */ export declare namespace CfnLocalGatewayRouteTableVPCAssociation { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-localgatewayroutetablevpcassociation-tags.html * @external */ interface TagsProperty { /** * `CfnLocalGatewayRouteTableVPCAssociation.TagsProperty.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-localgatewayroutetablevpcassociation-tags.html#cfn-ec2-localgatewayroutetablevpcassociation-tags-tags * @external */ readonly tags?: cdk.CfnTag[]; } } /** * Properties for defining a `AWS::EC2::NatGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html * @external */ export interface CfnNatGatewayProps { /** * `AWS::EC2::NatGateway.AllocationId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-allocationid * @external */ readonly allocationId: string; /** * `AWS::EC2::NatGateway.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-subnetid * @external */ readonly subnetId: string; /** * `AWS::EC2::NatGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::NatGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html * @external * @cloudformationResource AWS::EC2::NatGateway */ export declare class CfnNatGateway extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::NatGateway"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnNatGateway; /** * `AWS::EC2::NatGateway.AllocationId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-allocationid * @external */ allocationId: string; /** * `AWS::EC2::NatGateway.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-subnetid * @external */ subnetId: string; /** * `AWS::EC2::NatGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::NatGateway`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnNatGatewayProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::NetworkAcl`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html * @external */ export interface CfnNetworkAclProps { /** * `AWS::EC2::NetworkAcl.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html#cfn-ec2-networkacl-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::NetworkAcl.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html#cfn-ec2-networkacl-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::NetworkAcl`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html * @external * @cloudformationResource AWS::EC2::NetworkAcl */ export declare class CfnNetworkAcl extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::NetworkAcl"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnNetworkAcl; /** * `AWS::EC2::NetworkAcl.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html#cfn-ec2-networkacl-vpcid * @external */ vpcId: string; /** * `AWS::EC2::NetworkAcl.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html#cfn-ec2-networkacl-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::NetworkAcl`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnNetworkAclProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::NetworkAclEntry`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html * @external */ export interface CfnNetworkAclEntryProps { /** * `AWS::EC2::NetworkAclEntry.NetworkAclId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-networkaclid * @external */ readonly networkAclId: string; /** * `AWS::EC2::NetworkAclEntry.Protocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-protocol * @external */ readonly protocol: number; /** * `AWS::EC2::NetworkAclEntry.RuleAction`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-ruleaction * @external */ readonly ruleAction: string; /** * `AWS::EC2::NetworkAclEntry.RuleNumber`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-rulenumber * @external */ readonly ruleNumber: number; /** * `AWS::EC2::NetworkAclEntry.CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-cidrblock * @external */ readonly cidrBlock?: string; /** * `AWS::EC2::NetworkAclEntry.Egress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-egress * @external */ readonly egress?: boolean | cdk.IResolvable; /** * `AWS::EC2::NetworkAclEntry.Icmp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-icmp * @external */ readonly icmp?: CfnNetworkAclEntry.IcmpProperty | cdk.IResolvable; /** * `AWS::EC2::NetworkAclEntry.Ipv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-ipv6cidrblock * @external */ readonly ipv6CidrBlock?: string; /** * `AWS::EC2::NetworkAclEntry.PortRange`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-portrange * @external */ readonly portRange?: CfnNetworkAclEntry.PortRangeProperty | cdk.IResolvable; } /** * A CloudFormation `AWS::EC2::NetworkAclEntry`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html * @external * @cloudformationResource AWS::EC2::NetworkAclEntry */ export declare class CfnNetworkAclEntry extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::NetworkAclEntry"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnNetworkAclEntry; /** * `AWS::EC2::NetworkAclEntry.NetworkAclId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-networkaclid * @external */ networkAclId: string; /** * `AWS::EC2::NetworkAclEntry.Protocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-protocol * @external */ protocol: number; /** * `AWS::EC2::NetworkAclEntry.RuleAction`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-ruleaction * @external */ ruleAction: string; /** * `AWS::EC2::NetworkAclEntry.RuleNumber`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-rulenumber * @external */ ruleNumber: number; /** * `AWS::EC2::NetworkAclEntry.CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-cidrblock * @external */ cidrBlock: string | undefined; /** * `AWS::EC2::NetworkAclEntry.Egress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-egress * @external */ egress: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::NetworkAclEntry.Icmp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-icmp * @external */ icmp: CfnNetworkAclEntry.IcmpProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::NetworkAclEntry.Ipv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-ipv6cidrblock * @external */ ipv6CidrBlock: string | undefined; /** * `AWS::EC2::NetworkAclEntry.PortRange`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-portrange * @external */ portRange: CfnNetworkAclEntry.PortRangeProperty | cdk.IResolvable | undefined; /** * Create a new `AWS::EC2::NetworkAclEntry`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnNetworkAclEntryProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::NetworkAclEntry`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html * @external * @cloudformationResource AWS::EC2::NetworkAclEntry */ export declare namespace CfnNetworkAclEntry { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-icmp.html * @external */ interface IcmpProperty { /** * `CfnNetworkAclEntry.IcmpProperty.Code`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-icmp.html#cfn-ec2-networkaclentry-icmp-code * @external */ readonly code?: number; /** * `CfnNetworkAclEntry.IcmpProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-icmp.html#cfn-ec2-networkaclentry-icmp-type * @external */ readonly type?: number; } } /** * A CloudFormation `AWS::EC2::NetworkAclEntry`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html * @external * @cloudformationResource AWS::EC2::NetworkAclEntry */ export declare namespace CfnNetworkAclEntry { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-portrange.html * @external */ interface PortRangeProperty { /** * `CfnNetworkAclEntry.PortRangeProperty.From`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-portrange.html#cfn-ec2-networkaclentry-portrange-from * @external */ readonly from?: number; /** * `CfnNetworkAclEntry.PortRangeProperty.To`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-portrange.html#cfn-ec2-networkaclentry-portrange-to * @external */ readonly to?: number; } } /** * Properties for defining a `AWS::EC2::NetworkInterface`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html * @external */ export interface CfnNetworkInterfaceProps { /** * `AWS::EC2::NetworkInterface.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-subnetid * @external */ readonly subnetId: string; /** * `AWS::EC2::NetworkInterface.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-description * @external */ readonly description?: string; /** * `AWS::EC2::NetworkInterface.GroupSet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-groupset * @external */ readonly groupSet?: string[]; /** * `AWS::EC2::NetworkInterface.InterfaceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-interfacetype * @external */ readonly interfaceType?: string; /** * `AWS::EC2::NetworkInterface.Ipv6AddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-ipv6addresscount * @external */ readonly ipv6AddressCount?: number; /** * `AWS::EC2::NetworkInterface.Ipv6Addresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-ipv6addresses * @external */ readonly ipv6Addresses?: Array<CfnNetworkInterface.InstanceIpv6AddressProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::NetworkInterface.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-privateipaddress * @external */ readonly privateIpAddress?: string; /** * `AWS::EC2::NetworkInterface.PrivateIpAddresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-privateipaddresses * @external */ readonly privateIpAddresses?: Array<CfnNetworkInterface.PrivateIpAddressSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::NetworkInterface.SecondaryPrivateIpAddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-secondaryprivateipcount * @external */ readonly secondaryPrivateIpAddressCount?: number; /** * `AWS::EC2::NetworkInterface.SourceDestCheck`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-sourcedestcheck * @external */ readonly sourceDestCheck?: boolean | cdk.IResolvable; /** * `AWS::EC2::NetworkInterface.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::NetworkInterface`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html * @external * @cloudformationResource AWS::EC2::NetworkInterface */ export declare class CfnNetworkInterface extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::NetworkInterface"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnNetworkInterface; /** * @external * @cloudformationAttribute PrimaryPrivateIpAddress */ readonly attrPrimaryPrivateIpAddress: string; /** * @external * @cloudformationAttribute SecondaryPrivateIpAddresses */ readonly attrSecondaryPrivateIpAddresses: string[]; /** * `AWS::EC2::NetworkInterface.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-subnetid * @external */ subnetId: string; /** * `AWS::EC2::NetworkInterface.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-description * @external */ description: string | undefined; /** * `AWS::EC2::NetworkInterface.GroupSet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-groupset * @external */ groupSet: string[] | undefined; /** * `AWS::EC2::NetworkInterface.InterfaceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-interfacetype * @external */ interfaceType: string | undefined; /** * `AWS::EC2::NetworkInterface.Ipv6AddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-ipv6addresscount * @external */ ipv6AddressCount: number | undefined; /** * `AWS::EC2::NetworkInterface.Ipv6Addresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-ipv6addresses * @external */ ipv6Addresses: Array<CfnNetworkInterface.InstanceIpv6AddressProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::NetworkInterface.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-privateipaddress * @external */ privateIpAddress: string | undefined; /** * `AWS::EC2::NetworkInterface.PrivateIpAddresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-privateipaddresses * @external */ privateIpAddresses: Array<CfnNetworkInterface.PrivateIpAddressSpecificationProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::NetworkInterface.SecondaryPrivateIpAddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-secondaryprivateipcount * @external */ secondaryPrivateIpAddressCount: number | undefined; /** * `AWS::EC2::NetworkInterface.SourceDestCheck`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-sourcedestcheck * @external */ sourceDestCheck: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::NetworkInterface.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::NetworkInterface`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnNetworkInterfaceProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::NetworkInterface`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html * @external * @cloudformationResource AWS::EC2::NetworkInterface */ export declare namespace CfnNetworkInterface { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkinterface-instanceipv6address.html * @external */ interface InstanceIpv6AddressProperty { /** * `CfnNetworkInterface.InstanceIpv6AddressProperty.Ipv6Address`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkinterface-instanceipv6address.html#cfn-ec2-networkinterface-instanceipv6address-ipv6address * @external */ readonly ipv6Address: string; } } /** * A CloudFormation `AWS::EC2::NetworkInterface`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html * @external * @cloudformationResource AWS::EC2::NetworkInterface */ export declare namespace CfnNetworkInterface { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html * @external */ interface PrivateIpAddressSpecificationProperty { /** * `CfnNetworkInterface.PrivateIpAddressSpecificationProperty.Primary`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-primary * @external */ readonly primary: boolean | cdk.IResolvable; /** * `CfnNetworkInterface.PrivateIpAddressSpecificationProperty.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-privateipaddress * @external */ readonly privateIpAddress: string; } } /** * Properties for defining a `AWS::EC2::NetworkInterfaceAttachment`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html * @external */ export interface CfnNetworkInterfaceAttachmentProps { /** * `AWS::EC2::NetworkInterfaceAttachment.DeviceIndex`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-deviceindex * @external */ readonly deviceIndex: string; /** * `AWS::EC2::NetworkInterfaceAttachment.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-instanceid * @external */ readonly instanceId: string; /** * `AWS::EC2::NetworkInterfaceAttachment.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-networkinterfaceid * @external */ readonly networkInterfaceId: string; /** * `AWS::EC2::NetworkInterfaceAttachment.DeleteOnTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-deleteonterm * @external */ readonly deleteOnTermination?: boolean | cdk.IResolvable; } /** * A CloudFormation `AWS::EC2::NetworkInterfaceAttachment`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html * @external * @cloudformationResource AWS::EC2::NetworkInterfaceAttachment */ export declare class CfnNetworkInterfaceAttachment extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::NetworkInterfaceAttachment"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnNetworkInterfaceAttachment; /** * `AWS::EC2::NetworkInterfaceAttachment.DeviceIndex`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-deviceindex * @external */ deviceIndex: string; /** * `AWS::EC2::NetworkInterfaceAttachment.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-instanceid * @external */ instanceId: string; /** * `AWS::EC2::NetworkInterfaceAttachment.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-networkinterfaceid * @external */ networkInterfaceId: string; /** * `AWS::EC2::NetworkInterfaceAttachment.DeleteOnTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-deleteonterm * @external */ deleteOnTermination: boolean | cdk.IResolvable | undefined; /** * Create a new `AWS::EC2::NetworkInterfaceAttachment`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnNetworkInterfaceAttachmentProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::NetworkInterfacePermission`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html * @external */ export interface CfnNetworkInterfacePermissionProps { /** * `AWS::EC2::NetworkInterfacePermission.AwsAccountId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-awsaccountid * @external */ readonly awsAccountId: string; /** * `AWS::EC2::NetworkInterfacePermission.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-networkinterfaceid * @external */ readonly networkInterfaceId: string; /** * `AWS::EC2::NetworkInterfacePermission.Permission`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-permission * @external */ readonly permission: string; } /** * A CloudFormation `AWS::EC2::NetworkInterfacePermission`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html * @external * @cloudformationResource AWS::EC2::NetworkInterfacePermission */ export declare class CfnNetworkInterfacePermission extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::NetworkInterfacePermission"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnNetworkInterfacePermission; /** * `AWS::EC2::NetworkInterfacePermission.AwsAccountId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-awsaccountid * @external */ awsAccountId: string; /** * `AWS::EC2::NetworkInterfacePermission.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-networkinterfaceid * @external */ networkInterfaceId: string; /** * `AWS::EC2::NetworkInterfacePermission.Permission`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-permission * @external */ permission: string; /** * Create a new `AWS::EC2::NetworkInterfacePermission`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnNetworkInterfacePermissionProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::PlacementGroup`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-placementgroup.html * @external */ export interface CfnPlacementGroupProps { /** * `AWS::EC2::PlacementGroup.Strategy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-placementgroup.html#cfn-ec2-placementgroup-strategy * @external */ readonly strategy?: string; } /** * A CloudFormation `AWS::EC2::PlacementGroup`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-placementgroup.html * @external * @cloudformationResource AWS::EC2::PlacementGroup */ export declare class CfnPlacementGroup extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::PlacementGroup"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnPlacementGroup; /** * `AWS::EC2::PlacementGroup.Strategy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-placementgroup.html#cfn-ec2-placementgroup-strategy * @external */ strategy: string | undefined; /** * Create a new `AWS::EC2::PlacementGroup`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnPlacementGroupProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::PrefixList`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html * @external */ export interface CfnPrefixListProps { /** * `AWS::EC2::PrefixList.AddressFamily`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-addressfamily * @external */ readonly addressFamily: string; /** * `AWS::EC2::PrefixList.MaxEntries`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-maxentries * @external */ readonly maxEntries: number; /** * `AWS::EC2::PrefixList.PrefixListName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-prefixlistname * @external */ readonly prefixListName: string; /** * `AWS::EC2::PrefixList.Entries`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-entries * @external */ readonly entries?: Array<CfnPrefixList.EntryProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::PrefixList.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::PrefixList`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html * @external * @cloudformationResource AWS::EC2::PrefixList */ export declare class CfnPrefixList extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::PrefixList"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnPrefixList; /** * @external * @cloudformationAttribute Arn */ readonly attrArn: string; /** * @external * @cloudformationAttribute OwnerId */ readonly attrOwnerId: string; /** * @external * @cloudformationAttribute PrefixListId */ readonly attrPrefixListId: string; /** * @external * @cloudformationAttribute Version */ readonly attrVersion: number; /** * `AWS::EC2::PrefixList.AddressFamily`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-addressfamily * @external */ addressFamily: string; /** * `AWS::EC2::PrefixList.MaxEntries`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-maxentries * @external */ maxEntries: number; /** * `AWS::EC2::PrefixList.PrefixListName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-prefixlistname * @external */ prefixListName: string; /** * `AWS::EC2::PrefixList.Entries`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-entries * @external */ entries: Array<CfnPrefixList.EntryProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::PrefixList.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html#cfn-ec2-prefixlist-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::PrefixList`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnPrefixListProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::PrefixList`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html * @external * @cloudformationResource AWS::EC2::PrefixList */ export declare namespace CfnPrefixList { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-prefixlist-entry.html * @external */ interface EntryProperty { /** * `CfnPrefixList.EntryProperty.Cidr`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-prefixlist-entry.html#cfn-ec2-prefixlist-entry-cidr * @external */ readonly cidr: string; /** * `CfnPrefixList.EntryProperty.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-prefixlist-entry.html#cfn-ec2-prefixlist-entry-description * @external */ readonly description?: string; } } /** * Properties for defining a `AWS::EC2::Route`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html * @external */ export interface CfnRouteProps { /** * `AWS::EC2::Route.RouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-routetableid * @external */ readonly routeTableId: string; /** * `AWS::EC2::Route.CarrierGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-carriergatewayid * @external */ readonly carrierGatewayId?: string; /** * `AWS::EC2::Route.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationcidrblock * @external */ readonly destinationCidrBlock?: string; /** * `AWS::EC2::Route.DestinationIpv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationipv6cidrblock * @external */ readonly destinationIpv6CidrBlock?: string; /** * `AWS::EC2::Route.EgressOnlyInternetGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-egressonlyinternetgatewayid * @external */ readonly egressOnlyInternetGatewayId?: string; /** * `AWS::EC2::Route.GatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-gatewayid * @external */ readonly gatewayId?: string; /** * `AWS::EC2::Route.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-instanceid * @external */ readonly instanceId?: string; /** * `AWS::EC2::Route.LocalGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-localgatewayid * @external */ readonly localGatewayId?: string; /** * `AWS::EC2::Route.NatGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-natgatewayid * @external */ readonly natGatewayId?: string; /** * `AWS::EC2::Route.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-networkinterfaceid * @external */ readonly networkInterfaceId?: string; /** * `AWS::EC2::Route.TransitGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-transitgatewayid * @external */ readonly transitGatewayId?: string; /** * `AWS::EC2::Route.VpcEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcendpointid * @external */ readonly vpcEndpointId?: string; /** * `AWS::EC2::Route.VpcPeeringConnectionId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcpeeringconnectionid * @external */ readonly vpcPeeringConnectionId?: string; } /** * A CloudFormation `AWS::EC2::Route`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html * @external * @cloudformationResource AWS::EC2::Route */ export declare class CfnRoute extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::Route"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnRoute; /** * `AWS::EC2::Route.RouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-routetableid * @external */ routeTableId: string; /** * `AWS::EC2::Route.CarrierGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-carriergatewayid * @external */ carrierGatewayId: string | undefined; /** * `AWS::EC2::Route.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationcidrblock * @external */ destinationCidrBlock: string | undefined; /** * `AWS::EC2::Route.DestinationIpv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationipv6cidrblock * @external */ destinationIpv6CidrBlock: string | undefined; /** * `AWS::EC2::Route.EgressOnlyInternetGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-egressonlyinternetgatewayid * @external */ egressOnlyInternetGatewayId: string | undefined; /** * `AWS::EC2::Route.GatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-gatewayid * @external */ gatewayId: string | undefined; /** * `AWS::EC2::Route.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-instanceid * @external */ instanceId: string | undefined; /** * `AWS::EC2::Route.LocalGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-localgatewayid * @external */ localGatewayId: string | undefined; /** * `AWS::EC2::Route.NatGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-natgatewayid * @external */ natGatewayId: string | undefined; /** * `AWS::EC2::Route.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-networkinterfaceid * @external */ networkInterfaceId: string | undefined; /** * `AWS::EC2::Route.TransitGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-transitgatewayid * @external */ transitGatewayId: string | undefined; /** * `AWS::EC2::Route.VpcEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcendpointid * @external */ vpcEndpointId: string | undefined; /** * `AWS::EC2::Route.VpcPeeringConnectionId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcpeeringconnectionid * @external */ vpcPeeringConnectionId: string | undefined; /** * Create a new `AWS::EC2::Route`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnRouteProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::RouteTable`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html * @external */ export interface CfnRouteTableProps { /** * `AWS::EC2::RouteTable.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html#cfn-ec2-routetable-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::RouteTable.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html#cfn-ec2-routetable-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::RouteTable`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html * @external * @cloudformationResource AWS::EC2::RouteTable */ export declare class CfnRouteTable extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::RouteTable"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnRouteTable; /** * `AWS::EC2::RouteTable.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html#cfn-ec2-routetable-vpcid * @external */ vpcId: string; /** * `AWS::EC2::RouteTable.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html#cfn-ec2-routetable-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::RouteTable`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnRouteTableProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::SecurityGroup`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html * @external */ export interface CfnSecurityGroupProps { /** * `AWS::EC2::SecurityGroup.GroupDescription`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-groupdescription * @external */ readonly groupDescription: string; /** * `AWS::EC2::SecurityGroup.GroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-groupname * @external */ readonly groupName?: string; /** * `AWS::EC2::SecurityGroup.SecurityGroupEgress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-securitygroupegress * @external */ readonly securityGroupEgress?: Array<CfnSecurityGroup.EgressProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::SecurityGroup.SecurityGroupIngress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-securitygroupingress * @external */ readonly securityGroupIngress?: Array<CfnSecurityGroup.IngressProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::EC2::SecurityGroup.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-tags * @external */ readonly tags?: cdk.CfnTag[]; /** * `AWS::EC2::SecurityGroup.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-vpcid * @external */ readonly vpcId?: string; } /** * A CloudFormation `AWS::EC2::SecurityGroup`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html * @external * @cloudformationResource AWS::EC2::SecurityGroup */ export declare class CfnSecurityGroup extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::SecurityGroup"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnSecurityGroup; /** * @external * @cloudformationAttribute GroupId */ readonly attrGroupId: string; /** * @external * @cloudformationAttribute VpcId */ readonly attrVpcId: string; /** * `AWS::EC2::SecurityGroup.GroupDescription`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-groupdescription * @external */ groupDescription: string; /** * `AWS::EC2::SecurityGroup.GroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-groupname * @external */ groupName: string | undefined; /** * `AWS::EC2::SecurityGroup.SecurityGroupEgress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-securitygroupegress * @external */ securityGroupEgress: Array<CfnSecurityGroup.EgressProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::SecurityGroup.SecurityGroupIngress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-securitygroupingress * @external */ securityGroupIngress: Array<CfnSecurityGroup.IngressProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::EC2::SecurityGroup.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-tags * @external */ readonly tags: cdk.TagManager; /** * `AWS::EC2::SecurityGroup.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-vpcid * @external */ vpcId: string | undefined; /** * Create a new `AWS::EC2::SecurityGroup`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnSecurityGroupProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::SecurityGroup`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html * @external * @cloudformationResource AWS::EC2::SecurityGroup */ export declare namespace CfnSecurityGroup { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html * @external */ interface EgressProperty { /** * `CfnSecurityGroup.EgressProperty.CidrIp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-cidrip * @external */ readonly cidrIp?: string; /** * `CfnSecurityGroup.EgressProperty.CidrIpv6`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-cidripv6 * @external */ readonly cidrIpv6?: string; /** * `CfnSecurityGroup.EgressProperty.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-description * @external */ readonly description?: string; /** * `CfnSecurityGroup.EgressProperty.DestinationPrefixListId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-destinationprefixlistid * @external */ readonly destinationPrefixListId?: string; /** * `CfnSecurityGroup.EgressProperty.DestinationSecurityGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-destsecgroupid * @external */ readonly destinationSecurityGroupId?: string; /** * `CfnSecurityGroup.EgressProperty.FromPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-fromport * @external */ readonly fromPort?: number; /** * `CfnSecurityGroup.EgressProperty.IpProtocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-ipprotocol * @external */ readonly ipProtocol: string; /** * `CfnSecurityGroup.EgressProperty.ToPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-toport * @external */ readonly toPort?: number; } } /** * A CloudFormation `AWS::EC2::SecurityGroup`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html * @external * @cloudformationResource AWS::EC2::SecurityGroup */ export declare namespace CfnSecurityGroup { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html * @external */ interface IngressProperty { /** * `CfnSecurityGroup.IngressProperty.CidrIp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-cidrip * @external */ readonly cidrIp?: string; /** * `CfnSecurityGroup.IngressProperty.CidrIpv6`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-cidripv6 * @external */ readonly cidrIpv6?: string; /** * `CfnSecurityGroup.IngressProperty.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-description * @external */ readonly description?: string; /** * `CfnSecurityGroup.IngressProperty.FromPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-fromport * @external */ readonly fromPort?: number; /** * `CfnSecurityGroup.IngressProperty.IpProtocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-ipprotocol * @external */ readonly ipProtocol: string; /** * `CfnSecurityGroup.IngressProperty.SourcePrefixListId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-securitygroup-ingress-sourceprefixlistid * @external */ readonly sourcePrefixListId?: string; /** * `CfnSecurityGroup.IngressProperty.SourceSecurityGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-sourcesecuritygroupid * @external */ readonly sourceSecurityGroupId?: string; /** * `CfnSecurityGroup.IngressProperty.SourceSecurityGroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-sourcesecuritygroupname * @external */ readonly sourceSecurityGroupName?: string; /** * `CfnSecurityGroup.IngressProperty.SourceSecurityGroupOwnerId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-sourcesecuritygroupownerid * @external */ readonly sourceSecurityGroupOwnerId?: string; /** * `CfnSecurityGroup.IngressProperty.ToPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-toport * @external */ readonly toPort?: number; } } /** * Properties for defining a `AWS::EC2::SecurityGroupEgress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html * @external */ export interface CfnSecurityGroupEgressProps { /** * `AWS::EC2::SecurityGroupEgress.GroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-groupid * @external */ readonly groupId: string; /** * `AWS::EC2::SecurityGroupEgress.IpProtocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-ipprotocol * @external */ readonly ipProtocol: string; /** * `AWS::EC2::SecurityGroupEgress.CidrIp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-cidrip * @external */ readonly cidrIp?: string; /** * `AWS::EC2::SecurityGroupEgress.CidrIpv6`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-cidripv6 * @external */ readonly cidrIpv6?: string; /** * `AWS::EC2::SecurityGroupEgress.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-description * @external */ readonly description?: string; /** * `AWS::EC2::SecurityGroupEgress.DestinationPrefixListId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-destinationprefixlistid * @external */ readonly destinationPrefixListId?: string; /** * `AWS::EC2::SecurityGroupEgress.DestinationSecurityGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-destinationsecuritygroupid * @external */ readonly destinationSecurityGroupId?: string; /** * `AWS::EC2::SecurityGroupEgress.FromPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-fromport * @external */ readonly fromPort?: number; /** * `AWS::EC2::SecurityGroupEgress.ToPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-toport * @external */ readonly toPort?: number; } /** * A CloudFormation `AWS::EC2::SecurityGroupEgress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html * @external * @cloudformationResource AWS::EC2::SecurityGroupEgress */ export declare class CfnSecurityGroupEgress extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::SecurityGroupEgress"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnSecurityGroupEgress; /** * `AWS::EC2::SecurityGroupEgress.GroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-groupid * @external */ groupId: string; /** * `AWS::EC2::SecurityGroupEgress.IpProtocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-ipprotocol * @external */ ipProtocol: string; /** * `AWS::EC2::SecurityGroupEgress.CidrIp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-cidrip * @external */ cidrIp: string | undefined; /** * `AWS::EC2::SecurityGroupEgress.CidrIpv6`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-cidripv6 * @external */ cidrIpv6: string | undefined; /** * `AWS::EC2::SecurityGroupEgress.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-description * @external */ description: string | undefined; /** * `AWS::EC2::SecurityGroupEgress.DestinationPrefixListId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-destinationprefixlistid * @external */ destinationPrefixListId: string | undefined; /** * `AWS::EC2::SecurityGroupEgress.DestinationSecurityGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-destinationsecuritygroupid * @external */ destinationSecurityGroupId: string | undefined; /** * `AWS::EC2::SecurityGroupEgress.FromPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-fromport * @external */ fromPort: number | undefined; /** * `AWS::EC2::SecurityGroupEgress.ToPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-toport * @external */ toPort: number | undefined; /** * Create a new `AWS::EC2::SecurityGroupEgress`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnSecurityGroupEgressProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::SecurityGroupIngress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html * @external */ export interface CfnSecurityGroupIngressProps { /** * `AWS::EC2::SecurityGroupIngress.IpProtocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-ipprotocol * @external */ readonly ipProtocol: string; /** * `AWS::EC2::SecurityGroupIngress.CidrIp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-cidrip * @external */ readonly cidrIp?: string; /** * `AWS::EC2::SecurityGroupIngress.CidrIpv6`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-cidripv6 * @external */ readonly cidrIpv6?: string; /** * `AWS::EC2::SecurityGroupIngress.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-description * @external */ readonly description?: string; /** * `AWS::EC2::SecurityGroupIngress.FromPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-fromport * @external */ readonly fromPort?: number; /** * `AWS::EC2::SecurityGroupIngress.GroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-groupid * @external */ readonly groupId?: string; /** * `AWS::EC2::SecurityGroupIngress.GroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-groupname * @external */ readonly groupName?: string; /** * `AWS::EC2::SecurityGroupIngress.SourcePrefixListId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-securitygroupingress-sourceprefixlistid * @external */ readonly sourcePrefixListId?: string; /** * `AWS::EC2::SecurityGroupIngress.SourceSecurityGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupid * @external */ readonly sourceSecurityGroupId?: string; /** * `AWS::EC2::SecurityGroupIngress.SourceSecurityGroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupname * @external */ readonly sourceSecurityGroupName?: string; /** * `AWS::EC2::SecurityGroupIngress.SourceSecurityGroupOwnerId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupownerid * @external */ readonly sourceSecurityGroupOwnerId?: string; /** * `AWS::EC2::SecurityGroupIngress.ToPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-toport * @external */ readonly toPort?: number; } /** * A CloudFormation `AWS::EC2::SecurityGroupIngress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html * @external * @cloudformationResource AWS::EC2::SecurityGroupIngress */ export declare class CfnSecurityGroupIngress extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::SecurityGroupIngress"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnSecurityGroupIngress; /** * `AWS::EC2::SecurityGroupIngress.IpProtocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-ipprotocol * @external */ ipProtocol: string; /** * `AWS::EC2::SecurityGroupIngress.CidrIp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-cidrip * @external */ cidrIp: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.CidrIpv6`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-cidripv6 * @external */ cidrIpv6: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-description * @external */ description: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.FromPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-fromport * @external */ fromPort: number | undefined; /** * `AWS::EC2::SecurityGroupIngress.GroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-groupid * @external */ groupId: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.GroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-groupname * @external */ groupName: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.SourcePrefixListId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-securitygroupingress-sourceprefixlistid * @external */ sourcePrefixListId: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.SourceSecurityGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupid * @external */ sourceSecurityGroupId: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.SourceSecurityGroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupname * @external */ sourceSecurityGroupName: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.SourceSecurityGroupOwnerId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupownerid * @external */ sourceSecurityGroupOwnerId: string | undefined; /** * `AWS::EC2::SecurityGroupIngress.ToPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-toport * @external */ toPort: number | undefined; /** * Create a new `AWS::EC2::SecurityGroupIngress`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnSecurityGroupIngressProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external */ export interface CfnSpotFleetProps { /** * `AWS::EC2::SpotFleet.SpotFleetRequestConfigData`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata * @external */ readonly spotFleetRequestConfigData: CfnSpotFleet.SpotFleetRequestConfigDataProperty | cdk.IResolvable; } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare class CfnSpotFleet extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::SpotFleet"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnSpotFleet; /** * `AWS::EC2::SpotFleet.SpotFleetRequestConfigData`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata * @external */ spotFleetRequestConfigData: CfnSpotFleet.SpotFleetRequestConfigDataProperty | cdk.IResolvable; /** * Create a new `AWS::EC2::SpotFleet`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnSpotFleetProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html * @external */ interface BlockDeviceMappingProperty { /** * `CfnSpotFleet.BlockDeviceMappingProperty.DeviceName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemapping-devicename * @external */ readonly deviceName: string; /** * `CfnSpotFleet.BlockDeviceMappingProperty.Ebs`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemapping-ebs * @external */ readonly ebs?: CfnSpotFleet.EbsBlockDeviceProperty | cdk.IResolvable; /** * `CfnSpotFleet.BlockDeviceMappingProperty.NoDevice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemapping-nodevice * @external */ readonly noDevice?: string; /** * `CfnSpotFleet.BlockDeviceMappingProperty.VirtualName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemapping-virtualname * @external */ readonly virtualName?: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-classicloadbalancer.html * @external */ interface ClassicLoadBalancerProperty { /** * `CfnSpotFleet.ClassicLoadBalancerProperty.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-classicloadbalancer.html#cfn-ec2-spotfleet-classicloadbalancer-name * @external */ readonly name: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-classicloadbalancersconfig.html * @external */ interface ClassicLoadBalancersConfigProperty { /** * `CfnSpotFleet.ClassicLoadBalancersConfigProperty.ClassicLoadBalancers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-classicloadbalancersconfig.html#cfn-ec2-spotfleet-classicloadbalancersconfig-classicloadbalancers * @external */ readonly classicLoadBalancers: Array<CfnSpotFleet.ClassicLoadBalancerProperty | cdk.IResolvable> | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html * @external */ interface EbsBlockDeviceProperty { /** * `CfnSpotFleet.EbsBlockDeviceProperty.DeleteOnTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-deleteontermination * @external */ readonly deleteOnTermination?: boolean | cdk.IResolvable; /** * `CfnSpotFleet.EbsBlockDeviceProperty.Encrypted`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-encrypted * @external */ readonly encrypted?: boolean | cdk.IResolvable; /** * `CfnSpotFleet.EbsBlockDeviceProperty.Iops`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-iops * @external */ readonly iops?: number; /** * `CfnSpotFleet.EbsBlockDeviceProperty.SnapshotId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-snapshotid * @external */ readonly snapshotId?: string; /** * `CfnSpotFleet.EbsBlockDeviceProperty.VolumeSize`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-volumesize * @external */ readonly volumeSize?: number; /** * `CfnSpotFleet.EbsBlockDeviceProperty.VolumeType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-volumetype * @external */ readonly volumeType?: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-fleetlaunchtemplatespecification.html * @external */ interface FleetLaunchTemplateSpecificationProperty { /** * `CfnSpotFleet.FleetLaunchTemplateSpecificationProperty.LaunchTemplateId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-fleetlaunchtemplatespecification.html#cfn-ec2-spotfleet-fleetlaunchtemplatespecification-launchtemplateid * @external */ readonly launchTemplateId?: string; /** * `CfnSpotFleet.FleetLaunchTemplateSpecificationProperty.LaunchTemplateName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-fleetlaunchtemplatespecification.html#cfn-ec2-spotfleet-fleetlaunchtemplatespecification-launchtemplatename * @external */ readonly launchTemplateName?: string; /** * `CfnSpotFleet.FleetLaunchTemplateSpecificationProperty.Version`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-fleetlaunchtemplatespecification.html#cfn-ec2-spotfleet-fleetlaunchtemplatespecification-version * @external */ readonly version: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-securitygroups.html * @external */ interface GroupIdentifierProperty { /** * `CfnSpotFleet.GroupIdentifierProperty.GroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-securitygroups.html#cfn-ec2-spotfleet-groupidentifier-groupid * @external */ readonly groupId: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-iaminstanceprofile.html * @external */ interface IamInstanceProfileSpecificationProperty { /** * `CfnSpotFleet.IamInstanceProfileSpecificationProperty.Arn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-iaminstanceprofile.html#cfn-ec2-spotfleet-iaminstanceprofilespecification-arn * @external */ readonly arn?: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-instanceipv6address.html * @external */ interface InstanceIpv6AddressProperty { /** * `CfnSpotFleet.InstanceIpv6AddressProperty.Ipv6Address`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-instanceipv6address.html#cfn-ec2-spotfleet-instanceipv6address-ipv6address * @external */ readonly ipv6Address: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html * @external */ interface InstanceNetworkInterfaceSpecificationProperty { /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.AssociatePublicIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-associatepublicipaddress * @external */ readonly associatePublicIpAddress?: boolean | cdk.IResolvable; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.DeleteOnTermination`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-deleteontermination * @external */ readonly deleteOnTermination?: boolean | cdk.IResolvable; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-description * @external */ readonly description?: string; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.DeviceIndex`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-deviceindex * @external */ readonly deviceIndex?: number; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.Groups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-groups * @external */ readonly groups?: string[]; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.Ipv6AddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-ipv6addresscount * @external */ readonly ipv6AddressCount?: number; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.Ipv6Addresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-ipv6addresses * @external */ readonly ipv6Addresses?: Array<CfnSpotFleet.InstanceIpv6AddressProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-networkinterfaceid * @external */ readonly networkInterfaceId?: string; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.PrivateIpAddresses`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-privateipaddresses * @external */ readonly privateIpAddresses?: Array<CfnSpotFleet.PrivateIpAddressSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.SecondaryPrivateIpAddressCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-secondaryprivateipaddresscount * @external */ readonly secondaryPrivateIpAddressCount?: number; /** * `CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-subnetid * @external */ readonly subnetId?: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateconfig.html * @external */ interface LaunchTemplateConfigProperty { /** * `CfnSpotFleet.LaunchTemplateConfigProperty.LaunchTemplateSpecification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateconfig.html#cfn-ec2-spotfleet-launchtemplateconfig-launchtemplatespecification * @external */ readonly launchTemplateSpecification?: CfnSpotFleet.FleetLaunchTemplateSpecificationProperty | cdk.IResolvable; /** * `CfnSpotFleet.LaunchTemplateConfigProperty.Overrides`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateconfig.html#cfn-ec2-spotfleet-launchtemplateconfig-overrides * @external */ readonly overrides?: Array<CfnSpotFleet.LaunchTemplateOverridesProperty | cdk.IResolvable> | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateoverrides.html * @external */ interface LaunchTemplateOverridesProperty { /** * `CfnSpotFleet.LaunchTemplateOverridesProperty.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateoverrides.html#cfn-ec2-spotfleet-launchtemplateoverrides-availabilityzone * @external */ readonly availabilityZone?: string; /** * `CfnSpotFleet.LaunchTemplateOverridesProperty.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateoverrides.html#cfn-ec2-spotfleet-launchtemplateoverrides-instancetype * @external */ readonly instanceType?: string; /** * `CfnSpotFleet.LaunchTemplateOverridesProperty.SpotPrice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateoverrides.html#cfn-ec2-spotfleet-launchtemplateoverrides-spotprice * @external */ readonly spotPrice?: string; /** * `CfnSpotFleet.LaunchTemplateOverridesProperty.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateoverrides.html#cfn-ec2-spotfleet-launchtemplateoverrides-subnetid * @external */ readonly subnetId?: string; /** * `CfnSpotFleet.LaunchTemplateOverridesProperty.WeightedCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-launchtemplateoverrides.html#cfn-ec2-spotfleet-launchtemplateoverrides-weightedcapacity * @external */ readonly weightedCapacity?: number; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-loadbalancersconfig.html * @external */ interface LoadBalancersConfigProperty { /** * `CfnSpotFleet.LoadBalancersConfigProperty.ClassicLoadBalancersConfig`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-loadbalancersconfig.html#cfn-ec2-spotfleet-loadbalancersconfig-classicloadbalancersconfig * @external */ readonly classicLoadBalancersConfig?: CfnSpotFleet.ClassicLoadBalancersConfigProperty | cdk.IResolvable; /** * `CfnSpotFleet.LoadBalancersConfigProperty.TargetGroupsConfig`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-loadbalancersconfig.html#cfn-ec2-spotfleet-loadbalancersconfig-targetgroupsconfig * @external */ readonly targetGroupsConfig?: CfnSpotFleet.TargetGroupsConfigProperty | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces-privateipaddresses.html * @external */ interface PrivateIpAddressSpecificationProperty { /** * `CfnSpotFleet.PrivateIpAddressSpecificationProperty.Primary`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces-privateipaddresses.html#cfn-ec2-spotfleet-privateipaddressspecification-primary * @external */ readonly primary?: boolean | cdk.IResolvable; /** * `CfnSpotFleet.PrivateIpAddressSpecificationProperty.PrivateIpAddress`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces-privateipaddresses.html#cfn-ec2-spotfleet-privateipaddressspecification-privateipaddress * @external */ readonly privateIpAddress: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html * @external */ interface SpotFleetLaunchSpecificationProperty { /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.BlockDeviceMappings`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-blockdevicemappings * @external */ readonly blockDeviceMappings?: Array<CfnSpotFleet.BlockDeviceMappingProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.EbsOptimized`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-ebsoptimized * @external */ readonly ebsOptimized?: boolean | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.IamInstanceProfile`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-iaminstanceprofile * @external */ readonly iamInstanceProfile?: CfnSpotFleet.IamInstanceProfileSpecificationProperty | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.ImageId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-imageid * @external */ readonly imageId: string; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.InstanceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-instancetype * @external */ readonly instanceType: string; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.KernelId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-kernelid * @external */ readonly kernelId?: string; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.KeyName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-keyname * @external */ readonly keyName?: string; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.Monitoring`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-monitoring * @external */ readonly monitoring?: CfnSpotFleet.SpotFleetMonitoringProperty | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.NetworkInterfaces`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-networkinterfaces * @external */ readonly networkInterfaces?: Array<CfnSpotFleet.InstanceNetworkInterfaceSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.Placement`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-placement * @external */ readonly placement?: CfnSpotFleet.SpotPlacementProperty | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.RamdiskId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-ramdiskid * @external */ readonly ramdiskId?: string; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.SecurityGroups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-securitygroups * @external */ readonly securityGroups?: Array<CfnSpotFleet.GroupIdentifierProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.SpotPrice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-spotprice * @external */ readonly spotPrice?: string; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-subnetid * @external */ readonly subnetId?: string; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.TagSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-tagspecifications * @external */ readonly tagSpecifications?: Array<CfnSpotFleet.SpotFleetTagSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.UserData`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-userdata * @external */ readonly userData?: string; /** * `CfnSpotFleet.SpotFleetLaunchSpecificationProperty.WeightedCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-weightedcapacity * @external */ readonly weightedCapacity?: number; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-monitoring.html * @external */ interface SpotFleetMonitoringProperty { /** * `CfnSpotFleet.SpotFleetMonitoringProperty.Enabled`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-monitoring.html#cfn-ec2-spotfleet-spotfleetmonitoring-enabled * @external */ readonly enabled?: boolean | cdk.IResolvable; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html * @external */ interface SpotFleetRequestConfigDataProperty { /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.AllocationStrategy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-allocationstrategy * @external */ readonly allocationStrategy?: string; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.ExcessCapacityTerminationPolicy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-excesscapacityterminationpolicy * @external */ readonly excessCapacityTerminationPolicy?: string; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.IamFleetRole`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-iamfleetrole * @external */ readonly iamFleetRole: string; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.InstanceInterruptionBehavior`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-instanceinterruptionbehavior * @external */ readonly instanceInterruptionBehavior?: string; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.LaunchSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications * @external */ readonly launchSpecifications?: Array<CfnSpotFleet.SpotFleetLaunchSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.LaunchTemplateConfigs`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-launchtemplateconfigs * @external */ readonly launchTemplateConfigs?: Array<CfnSpotFleet.LaunchTemplateConfigProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.LoadBalancersConfig`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-loadbalancersconfig * @external */ readonly loadBalancersConfig?: CfnSpotFleet.LoadBalancersConfigProperty | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.ReplaceUnhealthyInstances`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-replaceunhealthyinstances * @external */ readonly replaceUnhealthyInstances?: boolean | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.SpotPrice`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-spotprice * @external */ readonly spotPrice?: string; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.TargetCapacity`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-targetcapacity * @external */ readonly targetCapacity: number; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.TerminateInstancesWithExpiration`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-terminateinstanceswithexpiration * @external */ readonly terminateInstancesWithExpiration?: boolean | cdk.IResolvable; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-type * @external */ readonly type?: string; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.ValidFrom`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-validfrom * @external */ readonly validFrom?: string; /** * `CfnSpotFleet.SpotFleetRequestConfigDataProperty.ValidUntil`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-validuntil * @external */ readonly validUntil?: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-tagspecifications.html * @external */ interface SpotFleetTagSpecificationProperty { /** * `CfnSpotFleet.SpotFleetTagSpecificationProperty.ResourceType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-tagspecifications.html#cfn-ec2-spotfleet-spotfleettagspecification-resourcetype * @external */ readonly resourceType?: string; /** * `CfnSpotFleet.SpotFleetTagSpecificationProperty.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-tagspecifications.html#cfn-ec2-spotfleet-tags * @external */ readonly tags?: cdk.CfnTag[]; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html * @external */ interface SpotPlacementProperty { /** * `CfnSpotFleet.SpotPlacementProperty.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html#cfn-ec2-spotfleet-spotplacement-availabilityzone * @external */ readonly availabilityZone?: string; /** * `CfnSpotFleet.SpotPlacementProperty.GroupName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html#cfn-ec2-spotfleet-spotplacement-groupname * @external */ readonly groupName?: string; /** * `CfnSpotFleet.SpotPlacementProperty.Tenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html#cfn-ec2-spotfleet-spotplacement-tenancy * @external */ readonly tenancy?: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-targetgroup.html * @external */ interface TargetGroupProperty { /** * `CfnSpotFleet.TargetGroupProperty.Arn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-targetgroup.html#cfn-ec2-spotfleet-targetgroup-arn * @external */ readonly arn: string; } } /** * A CloudFormation `AWS::EC2::SpotFleet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html * @external * @cloudformationResource AWS::EC2::SpotFleet */ export declare namespace CfnSpotFleet { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-targetgroupsconfig.html * @external */ interface TargetGroupsConfigProperty { /** * `CfnSpotFleet.TargetGroupsConfigProperty.TargetGroups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-targetgroupsconfig.html#cfn-ec2-spotfleet-targetgroupsconfig-targetgroups * @external */ readonly targetGroups: Array<CfnSpotFleet.TargetGroupProperty | cdk.IResolvable> | cdk.IResolvable; } } /** * Properties for defining a `AWS::EC2::Subnet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html * @external */ export interface CfnSubnetProps { /** * `AWS::EC2::Subnet.CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-cidrblock * @external */ readonly cidrBlock: string; /** * `AWS::EC2::Subnet.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-awsec2subnet-prop-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::Subnet.AssignIpv6AddressOnCreation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-assignipv6addressoncreation * @external */ readonly assignIpv6AddressOnCreation?: boolean | cdk.IResolvable; /** * `AWS::EC2::Subnet.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-availabilityzone * @external */ readonly availabilityZone?: string; /** * `AWS::EC2::Subnet.Ipv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-ipv6cidrblock * @external */ readonly ipv6CidrBlock?: string; /** * `AWS::EC2::Subnet.MapPublicIpOnLaunch`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-mappubliciponlaunch * @external */ readonly mapPublicIpOnLaunch?: boolean | cdk.IResolvable; /** * `AWS::EC2::Subnet.OutpostArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-outpostarn * @external */ readonly outpostArn?: string; /** * `AWS::EC2::Subnet.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::Subnet`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html * @external * @cloudformationResource AWS::EC2::Subnet */ export declare class CfnSubnet extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::Subnet"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnSubnet; /** * @external * @cloudformationAttribute AvailabilityZone */ readonly attrAvailabilityZone: string; /** * @external * @cloudformationAttribute Ipv6CidrBlocks */ readonly attrIpv6CidrBlocks: string[]; /** * @external * @cloudformationAttribute NetworkAclAssociationId */ readonly attrNetworkAclAssociationId: string; /** * @external * @cloudformationAttribute OutpostArn */ readonly attrOutpostArn: string; /** * @external * @cloudformationAttribute VpcId */ readonly attrVpcId: string; /** * `AWS::EC2::Subnet.CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-cidrblock * @external */ cidrBlock: string; /** * `AWS::EC2::Subnet.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-awsec2subnet-prop-vpcid * @external */ vpcId: string; /** * `AWS::EC2::Subnet.AssignIpv6AddressOnCreation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-assignipv6addressoncreation * @external */ assignIpv6AddressOnCreation: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Subnet.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-availabilityzone * @external */ availabilityZone: string | undefined; /** * `AWS::EC2::Subnet.Ipv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-ipv6cidrblock * @external */ ipv6CidrBlock: string | undefined; /** * `AWS::EC2::Subnet.MapPublicIpOnLaunch`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-mappubliciponlaunch * @external */ mapPublicIpOnLaunch: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Subnet.OutpostArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-outpostarn * @external */ outpostArn: string | undefined; /** * `AWS::EC2::Subnet.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::Subnet`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnSubnetProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::SubnetCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html * @external */ export interface CfnSubnetCidrBlockProps { /** * `AWS::EC2::SubnetCidrBlock.Ipv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html#cfn-ec2-subnetcidrblock-ipv6cidrblock * @external */ readonly ipv6CidrBlock: string; /** * `AWS::EC2::SubnetCidrBlock.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html#cfn-ec2-subnetcidrblock-subnetid * @external */ readonly subnetId: string; } /** * A CloudFormation `AWS::EC2::SubnetCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html * @external * @cloudformationResource AWS::EC2::SubnetCidrBlock */ export declare class CfnSubnetCidrBlock extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::SubnetCidrBlock"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnSubnetCidrBlock; /** * `AWS::EC2::SubnetCidrBlock.Ipv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html#cfn-ec2-subnetcidrblock-ipv6cidrblock * @external */ ipv6CidrBlock: string; /** * `AWS::EC2::SubnetCidrBlock.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html#cfn-ec2-subnetcidrblock-subnetid * @external */ subnetId: string; /** * Create a new `AWS::EC2::SubnetCidrBlock`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnSubnetCidrBlockProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::SubnetNetworkAclAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html * @external */ export interface CfnSubnetNetworkAclAssociationProps { /** * `AWS::EC2::SubnetNetworkAclAssociation.NetworkAclId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html#cfn-ec2-subnetnetworkaclassociation-networkaclid * @external */ readonly networkAclId: string; /** * `AWS::EC2::SubnetNetworkAclAssociation.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html#cfn-ec2-subnetnetworkaclassociation-associationid * @external */ readonly subnetId: string; } /** * A CloudFormation `AWS::EC2::SubnetNetworkAclAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html * @external * @cloudformationResource AWS::EC2::SubnetNetworkAclAssociation */ export declare class CfnSubnetNetworkAclAssociation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::SubnetNetworkAclAssociation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnSubnetNetworkAclAssociation; /** * @external * @cloudformationAttribute AssociationId */ readonly attrAssociationId: string; /** * `AWS::EC2::SubnetNetworkAclAssociation.NetworkAclId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html#cfn-ec2-subnetnetworkaclassociation-networkaclid * @external */ networkAclId: string; /** * `AWS::EC2::SubnetNetworkAclAssociation.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html#cfn-ec2-subnetnetworkaclassociation-associationid * @external */ subnetId: string; /** * Create a new `AWS::EC2::SubnetNetworkAclAssociation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnSubnetNetworkAclAssociationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::SubnetRouteTableAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html * @external */ export interface CfnSubnetRouteTableAssociationProps { /** * `AWS::EC2::SubnetRouteTableAssociation.RouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html#cfn-ec2-subnetroutetableassociation-routetableid * @external */ readonly routeTableId: string; /** * `AWS::EC2::SubnetRouteTableAssociation.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html#cfn-ec2-subnetroutetableassociation-subnetid * @external */ readonly subnetId: string; } /** * A CloudFormation `AWS::EC2::SubnetRouteTableAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html * @external * @cloudformationResource AWS::EC2::SubnetRouteTableAssociation */ export declare class CfnSubnetRouteTableAssociation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::SubnetRouteTableAssociation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnSubnetRouteTableAssociation; /** * `AWS::EC2::SubnetRouteTableAssociation.RouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html#cfn-ec2-subnetroutetableassociation-routetableid * @external */ routeTableId: string; /** * `AWS::EC2::SubnetRouteTableAssociation.SubnetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html#cfn-ec2-subnetroutetableassociation-subnetid * @external */ subnetId: string; /** * Create a new `AWS::EC2::SubnetRouteTableAssociation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnSubnetRouteTableAssociationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TrafficMirrorFilter`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilter.html * @external */ export interface CfnTrafficMirrorFilterProps { /** * `AWS::EC2::TrafficMirrorFilter.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilter.html#cfn-ec2-trafficmirrorfilter-description * @external */ readonly description?: string; /** * `AWS::EC2::TrafficMirrorFilter.NetworkServices`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilter.html#cfn-ec2-trafficmirrorfilter-networkservices * @external */ readonly networkServices?: string[]; /** * `AWS::EC2::TrafficMirrorFilter.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilter.html#cfn-ec2-trafficmirrorfilter-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::TrafficMirrorFilter`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilter.html * @external * @cloudformationResource AWS::EC2::TrafficMirrorFilter */ export declare class CfnTrafficMirrorFilter extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TrafficMirrorFilter"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTrafficMirrorFilter; /** * `AWS::EC2::TrafficMirrorFilter.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilter.html#cfn-ec2-trafficmirrorfilter-description * @external */ description: string | undefined; /** * `AWS::EC2::TrafficMirrorFilter.NetworkServices`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilter.html#cfn-ec2-trafficmirrorfilter-networkservices * @external */ networkServices: string[] | undefined; /** * `AWS::EC2::TrafficMirrorFilter.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilter.html#cfn-ec2-trafficmirrorfilter-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::TrafficMirrorFilter`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnTrafficMirrorFilterProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TrafficMirrorFilterRule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html * @external */ export interface CfnTrafficMirrorFilterRuleProps { /** * `AWS::EC2::TrafficMirrorFilterRule.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-destinationcidrblock * @external */ readonly destinationCidrBlock: string; /** * `AWS::EC2::TrafficMirrorFilterRule.RuleAction`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-ruleaction * @external */ readonly ruleAction: string; /** * `AWS::EC2::TrafficMirrorFilterRule.RuleNumber`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-rulenumber * @external */ readonly ruleNumber: number; /** * `AWS::EC2::TrafficMirrorFilterRule.SourceCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-sourcecidrblock * @external */ readonly sourceCidrBlock: string; /** * `AWS::EC2::TrafficMirrorFilterRule.TrafficDirection`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-trafficdirection * @external */ readonly trafficDirection: string; /** * `AWS::EC2::TrafficMirrorFilterRule.TrafficMirrorFilterId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-trafficmirrorfilterid * @external */ readonly trafficMirrorFilterId: string; /** * `AWS::EC2::TrafficMirrorFilterRule.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-description * @external */ readonly description?: string; /** * `AWS::EC2::TrafficMirrorFilterRule.DestinationPortRange`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-destinationportrange * @external */ readonly destinationPortRange?: CfnTrafficMirrorFilterRule.TrafficMirrorPortRangeProperty | cdk.IResolvable; /** * `AWS::EC2::TrafficMirrorFilterRule.Protocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-protocol * @external */ readonly protocol?: number; /** * `AWS::EC2::TrafficMirrorFilterRule.SourcePortRange`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-sourceportrange * @external */ readonly sourcePortRange?: CfnTrafficMirrorFilterRule.TrafficMirrorPortRangeProperty | cdk.IResolvable; } /** * A CloudFormation `AWS::EC2::TrafficMirrorFilterRule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html * @external * @cloudformationResource AWS::EC2::TrafficMirrorFilterRule */ export declare class CfnTrafficMirrorFilterRule extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TrafficMirrorFilterRule"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTrafficMirrorFilterRule; /** * `AWS::EC2::TrafficMirrorFilterRule.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-destinationcidrblock * @external */ destinationCidrBlock: string; /** * `AWS::EC2::TrafficMirrorFilterRule.RuleAction`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-ruleaction * @external */ ruleAction: string; /** * `AWS::EC2::TrafficMirrorFilterRule.RuleNumber`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-rulenumber * @external */ ruleNumber: number; /** * `AWS::EC2::TrafficMirrorFilterRule.SourceCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-sourcecidrblock * @external */ sourceCidrBlock: string; /** * `AWS::EC2::TrafficMirrorFilterRule.TrafficDirection`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-trafficdirection * @external */ trafficDirection: string; /** * `AWS::EC2::TrafficMirrorFilterRule.TrafficMirrorFilterId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-trafficmirrorfilterid * @external */ trafficMirrorFilterId: string; /** * `AWS::EC2::TrafficMirrorFilterRule.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-description * @external */ description: string | undefined; /** * `AWS::EC2::TrafficMirrorFilterRule.DestinationPortRange`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-destinationportrange * @external */ destinationPortRange: CfnTrafficMirrorFilterRule.TrafficMirrorPortRangeProperty | cdk.IResolvable | undefined; /** * `AWS::EC2::TrafficMirrorFilterRule.Protocol`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-protocol * @external */ protocol: number | undefined; /** * `AWS::EC2::TrafficMirrorFilterRule.SourcePortRange`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html#cfn-ec2-trafficmirrorfilterrule-sourceportrange * @external */ sourcePortRange: CfnTrafficMirrorFilterRule.TrafficMirrorPortRangeProperty | cdk.IResolvable | undefined; /** * Create a new `AWS::EC2::TrafficMirrorFilterRule`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnTrafficMirrorFilterRuleProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::TrafficMirrorFilterRule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorfilterrule.html * @external * @cloudformationResource AWS::EC2::TrafficMirrorFilterRule */ export declare namespace CfnTrafficMirrorFilterRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-trafficmirrorfilterrule-trafficmirrorportrange.html * @external */ interface TrafficMirrorPortRangeProperty { /** * `CfnTrafficMirrorFilterRule.TrafficMirrorPortRangeProperty.FromPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-trafficmirrorfilterrule-trafficmirrorportrange.html#cfn-ec2-trafficmirrorfilterrule-trafficmirrorportrange-fromport * @external */ readonly fromPort: number; /** * `CfnTrafficMirrorFilterRule.TrafficMirrorPortRangeProperty.ToPort`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-trafficmirrorfilterrule-trafficmirrorportrange.html#cfn-ec2-trafficmirrorfilterrule-trafficmirrorportrange-toport * @external */ readonly toPort: number; } } /** * Properties for defining a `AWS::EC2::TrafficMirrorSession`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html * @external */ export interface CfnTrafficMirrorSessionProps { /** * `AWS::EC2::TrafficMirrorSession.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-networkinterfaceid * @external */ readonly networkInterfaceId: string; /** * `AWS::EC2::TrafficMirrorSession.SessionNumber`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-sessionnumber * @external */ readonly sessionNumber: number; /** * `AWS::EC2::TrafficMirrorSession.TrafficMirrorFilterId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-trafficmirrorfilterid * @external */ readonly trafficMirrorFilterId: string; /** * `AWS::EC2::TrafficMirrorSession.TrafficMirrorTargetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-trafficmirrortargetid * @external */ readonly trafficMirrorTargetId: string; /** * `AWS::EC2::TrafficMirrorSession.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-description * @external */ readonly description?: string; /** * `AWS::EC2::TrafficMirrorSession.PacketLength`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-packetlength * @external */ readonly packetLength?: number; /** * `AWS::EC2::TrafficMirrorSession.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-tags * @external */ readonly tags?: cdk.CfnTag[]; /** * `AWS::EC2::TrafficMirrorSession.VirtualNetworkId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-virtualnetworkid * @external */ readonly virtualNetworkId?: number; } /** * A CloudFormation `AWS::EC2::TrafficMirrorSession`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html * @external * @cloudformationResource AWS::EC2::TrafficMirrorSession */ export declare class CfnTrafficMirrorSession extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TrafficMirrorSession"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTrafficMirrorSession; /** * `AWS::EC2::TrafficMirrorSession.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-networkinterfaceid * @external */ networkInterfaceId: string; /** * `AWS::EC2::TrafficMirrorSession.SessionNumber`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-sessionnumber * @external */ sessionNumber: number; /** * `AWS::EC2::TrafficMirrorSession.TrafficMirrorFilterId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-trafficmirrorfilterid * @external */ trafficMirrorFilterId: string; /** * `AWS::EC2::TrafficMirrorSession.TrafficMirrorTargetId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-trafficmirrortargetid * @external */ trafficMirrorTargetId: string; /** * `AWS::EC2::TrafficMirrorSession.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-description * @external */ description: string | undefined; /** * `AWS::EC2::TrafficMirrorSession.PacketLength`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-packetlength * @external */ packetLength: number | undefined; /** * `AWS::EC2::TrafficMirrorSession.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-tags * @external */ readonly tags: cdk.TagManager; /** * `AWS::EC2::TrafficMirrorSession.VirtualNetworkId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrorsession.html#cfn-ec2-trafficmirrorsession-virtualnetworkid * @external */ virtualNetworkId: number | undefined; /** * Create a new `AWS::EC2::TrafficMirrorSession`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnTrafficMirrorSessionProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TrafficMirrorTarget`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html * @external */ export interface CfnTrafficMirrorTargetProps { /** * `AWS::EC2::TrafficMirrorTarget.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html#cfn-ec2-trafficmirrortarget-description * @external */ readonly description?: string; /** * `AWS::EC2::TrafficMirrorTarget.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html#cfn-ec2-trafficmirrortarget-networkinterfaceid * @external */ readonly networkInterfaceId?: string; /** * `AWS::EC2::TrafficMirrorTarget.NetworkLoadBalancerArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html#cfn-ec2-trafficmirrortarget-networkloadbalancerarn * @external */ readonly networkLoadBalancerArn?: string; /** * `AWS::EC2::TrafficMirrorTarget.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html#cfn-ec2-trafficmirrortarget-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::TrafficMirrorTarget`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html * @external * @cloudformationResource AWS::EC2::TrafficMirrorTarget */ export declare class CfnTrafficMirrorTarget extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TrafficMirrorTarget"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTrafficMirrorTarget; /** * `AWS::EC2::TrafficMirrorTarget.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html#cfn-ec2-trafficmirrortarget-description * @external */ description: string | undefined; /** * `AWS::EC2::TrafficMirrorTarget.NetworkInterfaceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html#cfn-ec2-trafficmirrortarget-networkinterfaceid * @external */ networkInterfaceId: string | undefined; /** * `AWS::EC2::TrafficMirrorTarget.NetworkLoadBalancerArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html#cfn-ec2-trafficmirrortarget-networkloadbalancerarn * @external */ networkLoadBalancerArn: string | undefined; /** * `AWS::EC2::TrafficMirrorTarget.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trafficmirrortarget.html#cfn-ec2-trafficmirrortarget-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::TrafficMirrorTarget`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnTrafficMirrorTargetProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TransitGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html * @external */ export interface CfnTransitGatewayProps { /** * `AWS::EC2::TransitGateway.AmazonSideAsn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-amazonsideasn * @external */ readonly amazonSideAsn?: number; /** * `AWS::EC2::TransitGateway.AutoAcceptSharedAttachments`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-autoacceptsharedattachments * @external */ readonly autoAcceptSharedAttachments?: string; /** * `AWS::EC2::TransitGateway.DefaultRouteTableAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-defaultroutetableassociation * @external */ readonly defaultRouteTableAssociation?: string; /** * `AWS::EC2::TransitGateway.DefaultRouteTablePropagation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-defaultroutetablepropagation * @external */ readonly defaultRouteTablePropagation?: string; /** * `AWS::EC2::TransitGateway.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-description * @external */ readonly description?: string; /** * `AWS::EC2::TransitGateway.DnsSupport`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-dnssupport * @external */ readonly dnsSupport?: string; /** * `AWS::EC2::TransitGateway.MulticastSupport`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-multicastsupport * @external */ readonly multicastSupport?: string; /** * `AWS::EC2::TransitGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-tags * @external */ readonly tags?: cdk.CfnTag[]; /** * `AWS::EC2::TransitGateway.VpnEcmpSupport`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-vpnecmpsupport * @external */ readonly vpnEcmpSupport?: string; } /** * A CloudFormation `AWS::EC2::TransitGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html * @external * @cloudformationResource AWS::EC2::TransitGateway */ export declare class CfnTransitGateway extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TransitGateway"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTransitGateway; /** * `AWS::EC2::TransitGateway.AmazonSideAsn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-amazonsideasn * @external */ amazonSideAsn: number | undefined; /** * `AWS::EC2::TransitGateway.AutoAcceptSharedAttachments`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-autoacceptsharedattachments * @external */ autoAcceptSharedAttachments: string | undefined; /** * `AWS::EC2::TransitGateway.DefaultRouteTableAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-defaultroutetableassociation * @external */ defaultRouteTableAssociation: string | undefined; /** * `AWS::EC2::TransitGateway.DefaultRouteTablePropagation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-defaultroutetablepropagation * @external */ defaultRouteTablePropagation: string | undefined; /** * `AWS::EC2::TransitGateway.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-description * @external */ description: string | undefined; /** * `AWS::EC2::TransitGateway.DnsSupport`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-dnssupport * @external */ dnsSupport: string | undefined; /** * `AWS::EC2::TransitGateway.MulticastSupport`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-multicastsupport * @external */ multicastSupport: string | undefined; /** * `AWS::EC2::TransitGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-tags * @external */ readonly tags: cdk.TagManager; /** * `AWS::EC2::TransitGateway.VpnEcmpSupport`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html#cfn-ec2-transitgateway-vpnecmpsupport * @external */ vpnEcmpSupport: string | undefined; /** * Create a new `AWS::EC2::TransitGateway`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnTransitGatewayProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TransitGatewayAttachment`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html * @external */ export interface CfnTransitGatewayAttachmentProps { /** * `AWS::EC2::TransitGatewayAttachment.SubnetIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html#cfn-ec2-transitgatewayattachment-subnetids * @external */ readonly subnetIds: string[]; /** * `AWS::EC2::TransitGatewayAttachment.TransitGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html#cfn-ec2-transitgatewayattachment-transitgatewayid * @external */ readonly transitGatewayId: string; /** * `AWS::EC2::TransitGatewayAttachment.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html#cfn-ec2-transitgatewayattachment-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::TransitGatewayAttachment.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html#cfn-ec2-transitgatewayattachment-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::TransitGatewayAttachment`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html * @external * @cloudformationResource AWS::EC2::TransitGatewayAttachment */ export declare class CfnTransitGatewayAttachment extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TransitGatewayAttachment"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTransitGatewayAttachment; /** * `AWS::EC2::TransitGatewayAttachment.SubnetIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html#cfn-ec2-transitgatewayattachment-subnetids * @external */ subnetIds: string[]; /** * `AWS::EC2::TransitGatewayAttachment.TransitGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html#cfn-ec2-transitgatewayattachment-transitgatewayid * @external */ transitGatewayId: string; /** * `AWS::EC2::TransitGatewayAttachment.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html#cfn-ec2-transitgatewayattachment-vpcid * @external */ vpcId: string; /** * `AWS::EC2::TransitGatewayAttachment.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayattachment.html#cfn-ec2-transitgatewayattachment-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::TransitGatewayAttachment`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnTransitGatewayAttachmentProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TransitGatewayRoute`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html * @external */ export interface CfnTransitGatewayRouteProps { /** * `AWS::EC2::TransitGatewayRoute.TransitGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html#cfn-ec2-transitgatewayroute-transitgatewayroutetableid * @external */ readonly transitGatewayRouteTableId: string; /** * `AWS::EC2::TransitGatewayRoute.Blackhole`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html#cfn-ec2-transitgatewayroute-blackhole * @external */ readonly blackhole?: boolean | cdk.IResolvable; /** * `AWS::EC2::TransitGatewayRoute.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html#cfn-ec2-transitgatewayroute-destinationcidrblock * @external */ readonly destinationCidrBlock?: string; /** * `AWS::EC2::TransitGatewayRoute.TransitGatewayAttachmentId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html#cfn-ec2-transitgatewayroute-transitgatewayattachmentid * @external */ readonly transitGatewayAttachmentId?: string; } /** * A CloudFormation `AWS::EC2::TransitGatewayRoute`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html * @external * @cloudformationResource AWS::EC2::TransitGatewayRoute */ export declare class CfnTransitGatewayRoute extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TransitGatewayRoute"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTransitGatewayRoute; /** * `AWS::EC2::TransitGatewayRoute.TransitGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html#cfn-ec2-transitgatewayroute-transitgatewayroutetableid * @external */ transitGatewayRouteTableId: string; /** * `AWS::EC2::TransitGatewayRoute.Blackhole`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html#cfn-ec2-transitgatewayroute-blackhole * @external */ blackhole: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::TransitGatewayRoute.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html#cfn-ec2-transitgatewayroute-destinationcidrblock * @external */ destinationCidrBlock: string | undefined; /** * `AWS::EC2::TransitGatewayRoute.TransitGatewayAttachmentId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroute.html#cfn-ec2-transitgatewayroute-transitgatewayattachmentid * @external */ transitGatewayAttachmentId: string | undefined; /** * Create a new `AWS::EC2::TransitGatewayRoute`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnTransitGatewayRouteProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TransitGatewayRouteTable`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetable.html * @external */ export interface CfnTransitGatewayRouteTableProps { /** * `AWS::EC2::TransitGatewayRouteTable.TransitGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetable.html#cfn-ec2-transitgatewayroutetable-transitgatewayid * @external */ readonly transitGatewayId: string; /** * `AWS::EC2::TransitGatewayRouteTable.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetable.html#cfn-ec2-transitgatewayroutetable-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::TransitGatewayRouteTable`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetable.html * @external * @cloudformationResource AWS::EC2::TransitGatewayRouteTable */ export declare class CfnTransitGatewayRouteTable extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TransitGatewayRouteTable"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTransitGatewayRouteTable; /** * `AWS::EC2::TransitGatewayRouteTable.TransitGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetable.html#cfn-ec2-transitgatewayroutetable-transitgatewayid * @external */ transitGatewayId: string; /** * `AWS::EC2::TransitGatewayRouteTable.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetable.html#cfn-ec2-transitgatewayroutetable-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::TransitGatewayRouteTable`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnTransitGatewayRouteTableProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TransitGatewayRouteTableAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetableassociation.html * @external */ export interface CfnTransitGatewayRouteTableAssociationProps { /** * `AWS::EC2::TransitGatewayRouteTableAssociation.TransitGatewayAttachmentId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetableassociation.html#cfn-ec2-transitgatewayroutetableassociation-transitgatewayattachmentid * @external */ readonly transitGatewayAttachmentId: string; /** * `AWS::EC2::TransitGatewayRouteTableAssociation.TransitGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetableassociation.html#cfn-ec2-transitgatewayroutetableassociation-transitgatewayroutetableid * @external */ readonly transitGatewayRouteTableId: string; } /** * A CloudFormation `AWS::EC2::TransitGatewayRouteTableAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetableassociation.html * @external * @cloudformationResource AWS::EC2::TransitGatewayRouteTableAssociation */ export declare class CfnTransitGatewayRouteTableAssociation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TransitGatewayRouteTableAssociation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTransitGatewayRouteTableAssociation; /** * `AWS::EC2::TransitGatewayRouteTableAssociation.TransitGatewayAttachmentId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetableassociation.html#cfn-ec2-transitgatewayroutetableassociation-transitgatewayattachmentid * @external */ transitGatewayAttachmentId: string; /** * `AWS::EC2::TransitGatewayRouteTableAssociation.TransitGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetableassociation.html#cfn-ec2-transitgatewayroutetableassociation-transitgatewayroutetableid * @external */ transitGatewayRouteTableId: string; /** * Create a new `AWS::EC2::TransitGatewayRouteTableAssociation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnTransitGatewayRouteTableAssociationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::TransitGatewayRouteTablePropagation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html * @external */ export interface CfnTransitGatewayRouteTablePropagationProps { /** * `AWS::EC2::TransitGatewayRouteTablePropagation.TransitGatewayAttachmentId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html#cfn-ec2-transitgatewayroutetablepropagation-transitgatewayattachmentid * @external */ readonly transitGatewayAttachmentId: string; /** * `AWS::EC2::TransitGatewayRouteTablePropagation.TransitGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html#cfn-ec2-transitgatewayroutetablepropagation-transitgatewayroutetableid * @external */ readonly transitGatewayRouteTableId: string; } /** * A CloudFormation `AWS::EC2::TransitGatewayRouteTablePropagation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html * @external * @cloudformationResource AWS::EC2::TransitGatewayRouteTablePropagation */ export declare class CfnTransitGatewayRouteTablePropagation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::TransitGatewayRouteTablePropagation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnTransitGatewayRouteTablePropagation; /** * `AWS::EC2::TransitGatewayRouteTablePropagation.TransitGatewayAttachmentId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html#cfn-ec2-transitgatewayroutetablepropagation-transitgatewayattachmentid * @external */ transitGatewayAttachmentId: string; /** * `AWS::EC2::TransitGatewayRouteTablePropagation.TransitGatewayRouteTableId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgatewayroutetablepropagation.html#cfn-ec2-transitgatewayroutetablepropagation-transitgatewayroutetableid * @external */ transitGatewayRouteTableId: string; /** * Create a new `AWS::EC2::TransitGatewayRouteTablePropagation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnTransitGatewayRouteTablePropagationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPC`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html * @external */ export interface CfnVPCProps { /** * `AWS::EC2::VPC.CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-cidrblock * @external */ readonly cidrBlock: string; /** * `AWS::EC2::VPC.EnableDnsHostnames`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-EnableDnsHostnames * @external */ readonly enableDnsHostnames?: boolean | cdk.IResolvable; /** * `AWS::EC2::VPC.EnableDnsSupport`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-EnableDnsSupport * @external */ readonly enableDnsSupport?: boolean | cdk.IResolvable; /** * `AWS::EC2::VPC.InstanceTenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-instancetenancy * @external */ readonly instanceTenancy?: string; /** * `AWS::EC2::VPC.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::VPC`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html * @external * @cloudformationResource AWS::EC2::VPC */ export declare class CfnVPC extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPC"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPC; /** * @external * @cloudformationAttribute CidrBlock */ readonly attrCidrBlock: string; /** * @external * @cloudformationAttribute CidrBlockAssociations */ readonly attrCidrBlockAssociations: string[]; /** * @external * @cloudformationAttribute DefaultNetworkAcl */ readonly attrDefaultNetworkAcl: string; /** * @external * @cloudformationAttribute DefaultSecurityGroup */ readonly attrDefaultSecurityGroup: string; /** * @external * @cloudformationAttribute Ipv6CidrBlocks */ readonly attrIpv6CidrBlocks: string[]; /** * `AWS::EC2::VPC.CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-cidrblock * @external */ cidrBlock: string; /** * `AWS::EC2::VPC.EnableDnsHostnames`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-EnableDnsHostnames * @external */ enableDnsHostnames: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::VPC.EnableDnsSupport`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-EnableDnsSupport * @external */ enableDnsSupport: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::VPC.InstanceTenancy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-instancetenancy * @external */ instanceTenancy: string | undefined; /** * `AWS::EC2::VPC.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::VPC`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPCProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPCCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html * @external */ export interface CfnVPCCidrBlockProps { /** * `AWS::EC2::VPCCidrBlock.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::VPCCidrBlock.AmazonProvidedIpv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-amazonprovidedipv6cidrblock * @external */ readonly amazonProvidedIpv6CidrBlock?: boolean | cdk.IResolvable; /** * `AWS::EC2::VPCCidrBlock.CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-cidrblock * @external */ readonly cidrBlock?: string; } /** * A CloudFormation `AWS::EC2::VPCCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html * @external * @cloudformationResource AWS::EC2::VPCCidrBlock */ export declare class CfnVPCCidrBlock extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPCCidrBlock"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPCCidrBlock; /** * `AWS::EC2::VPCCidrBlock.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-vpcid * @external */ vpcId: string; /** * `AWS::EC2::VPCCidrBlock.AmazonProvidedIpv6CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-amazonprovidedipv6cidrblock * @external */ amazonProvidedIpv6CidrBlock: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::VPCCidrBlock.CidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-cidrblock * @external */ cidrBlock: string | undefined; /** * Create a new `AWS::EC2::VPCCidrBlock`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPCCidrBlockProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPCDHCPOptionsAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html * @external */ export interface CfnVPCDHCPOptionsAssociationProps { /** * `AWS::EC2::VPCDHCPOptionsAssociation.DhcpOptionsId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html#cfn-ec2-vpcdhcpoptionsassociation-dhcpoptionsid * @external */ readonly dhcpOptionsId: string; /** * `AWS::EC2::VPCDHCPOptionsAssociation.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html#cfn-ec2-vpcdhcpoptionsassociation-vpcid * @external */ readonly vpcId: string; } /** * A CloudFormation `AWS::EC2::VPCDHCPOptionsAssociation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html * @external * @cloudformationResource AWS::EC2::VPCDHCPOptionsAssociation */ export declare class CfnVPCDHCPOptionsAssociation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPCDHCPOptionsAssociation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPCDHCPOptionsAssociation; /** * `AWS::EC2::VPCDHCPOptionsAssociation.DhcpOptionsId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html#cfn-ec2-vpcdhcpoptionsassociation-dhcpoptionsid * @external */ dhcpOptionsId: string; /** * `AWS::EC2::VPCDHCPOptionsAssociation.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html#cfn-ec2-vpcdhcpoptionsassociation-vpcid * @external */ vpcId: string; /** * Create a new `AWS::EC2::VPCDHCPOptionsAssociation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPCDHCPOptionsAssociationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPCEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html * @external */ export interface CfnVPCEndpointProps { /** * `AWS::EC2::VPCEndpoint.ServiceName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-servicename * @external */ readonly serviceName: string; /** * `AWS::EC2::VPCEndpoint.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::VPCEndpoint.PolicyDocument`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-policydocument * @external */ readonly policyDocument?: any | cdk.IResolvable; /** * `AWS::EC2::VPCEndpoint.PrivateDnsEnabled`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-privatednsenabled * @external */ readonly privateDnsEnabled?: boolean | cdk.IResolvable; /** * `AWS::EC2::VPCEndpoint.RouteTableIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-routetableids * @external */ readonly routeTableIds?: string[]; /** * `AWS::EC2::VPCEndpoint.SecurityGroupIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-securitygroupids * @external */ readonly securityGroupIds?: string[]; /** * `AWS::EC2::VPCEndpoint.SubnetIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-subnetids * @external */ readonly subnetIds?: string[]; /** * `AWS::EC2::VPCEndpoint.VpcEndpointType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-vpcendpointtype * @external */ readonly vpcEndpointType?: string; } /** * A CloudFormation `AWS::EC2::VPCEndpoint`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html * @external * @cloudformationResource AWS::EC2::VPCEndpoint */ export declare class CfnVPCEndpoint extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPCEndpoint"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPCEndpoint; /** * @external * @cloudformationAttribute CreationTimestamp */ readonly attrCreationTimestamp: string; /** * @external * @cloudformationAttribute DnsEntries */ readonly attrDnsEntries: string[]; /** * @external * @cloudformationAttribute NetworkInterfaceIds */ readonly attrNetworkInterfaceIds: string[]; /** * `AWS::EC2::VPCEndpoint.ServiceName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-servicename * @external */ serviceName: string; /** * `AWS::EC2::VPCEndpoint.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-vpcid * @external */ vpcId: string; /** * `AWS::EC2::VPCEndpoint.PolicyDocument`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-policydocument * @external */ policyDocument: any | cdk.IResolvable | undefined; /** * `AWS::EC2::VPCEndpoint.PrivateDnsEnabled`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-privatednsenabled * @external */ privateDnsEnabled: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::VPCEndpoint.RouteTableIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-routetableids * @external */ routeTableIds: string[] | undefined; /** * `AWS::EC2::VPCEndpoint.SecurityGroupIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-securitygroupids * @external */ securityGroupIds: string[] | undefined; /** * `AWS::EC2::VPCEndpoint.SubnetIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-subnetids * @external */ subnetIds: string[] | undefined; /** * `AWS::EC2::VPCEndpoint.VpcEndpointType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-vpcendpointtype * @external */ vpcEndpointType: string | undefined; /** * Create a new `AWS::EC2::VPCEndpoint`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPCEndpointProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPCEndpointConnectionNotification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html * @external */ export interface CfnVPCEndpointConnectionNotificationProps { /** * `AWS::EC2::VPCEndpointConnectionNotification.ConnectionEvents`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html#cfn-ec2-vpcendpointconnectionnotification-connectionevents * @external */ readonly connectionEvents: string[]; /** * `AWS::EC2::VPCEndpointConnectionNotification.ConnectionNotificationArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html#cfn-ec2-vpcendpointconnectionnotification-connectionnotificationarn * @external */ readonly connectionNotificationArn: string; /** * `AWS::EC2::VPCEndpointConnectionNotification.ServiceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html#cfn-ec2-vpcendpointconnectionnotification-serviceid * @external */ readonly serviceId?: string; /** * `AWS::EC2::VPCEndpointConnectionNotification.VPCEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html#cfn-ec2-vpcendpointconnectionnotification-vpcendpointid * @external */ readonly vpcEndpointId?: string; } /** * A CloudFormation `AWS::EC2::VPCEndpointConnectionNotification`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html * @external * @cloudformationResource AWS::EC2::VPCEndpointConnectionNotification */ export declare class CfnVPCEndpointConnectionNotification extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPCEndpointConnectionNotification"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPCEndpointConnectionNotification; /** * `AWS::EC2::VPCEndpointConnectionNotification.ConnectionEvents`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html#cfn-ec2-vpcendpointconnectionnotification-connectionevents * @external */ connectionEvents: string[]; /** * `AWS::EC2::VPCEndpointConnectionNotification.ConnectionNotificationArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html#cfn-ec2-vpcendpointconnectionnotification-connectionnotificationarn * @external */ connectionNotificationArn: string; /** * `AWS::EC2::VPCEndpointConnectionNotification.ServiceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html#cfn-ec2-vpcendpointconnectionnotification-serviceid * @external */ serviceId: string | undefined; /** * `AWS::EC2::VPCEndpointConnectionNotification.VPCEndpointId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointconnectionnotification.html#cfn-ec2-vpcendpointconnectionnotification-vpcendpointid * @external */ vpcEndpointId: string | undefined; /** * Create a new `AWS::EC2::VPCEndpointConnectionNotification`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPCEndpointConnectionNotificationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPCEndpointService`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservice.html * @external */ export interface CfnVPCEndpointServiceProps { /** * `AWS::EC2::VPCEndpointService.AcceptanceRequired`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservice.html#cfn-ec2-vpcendpointservice-acceptancerequired * @external */ readonly acceptanceRequired?: boolean | cdk.IResolvable; /** * `AWS::EC2::VPCEndpointService.GatewayLoadBalancerArns`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservice.html#cfn-ec2-vpcendpointservice-gatewayloadbalancerarns * @external */ readonly gatewayLoadBalancerArns?: string[]; /** * `AWS::EC2::VPCEndpointService.NetworkLoadBalancerArns`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservice.html#cfn-ec2-vpcendpointservice-networkloadbalancerarns * @external */ readonly networkLoadBalancerArns?: string[]; } /** * A CloudFormation `AWS::EC2::VPCEndpointService`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservice.html * @external * @cloudformationResource AWS::EC2::VPCEndpointService */ export declare class CfnVPCEndpointService extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPCEndpointService"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPCEndpointService; /** * `AWS::EC2::VPCEndpointService.AcceptanceRequired`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservice.html#cfn-ec2-vpcendpointservice-acceptancerequired * @external */ acceptanceRequired: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::VPCEndpointService.GatewayLoadBalancerArns`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservice.html#cfn-ec2-vpcendpointservice-gatewayloadbalancerarns * @external */ gatewayLoadBalancerArns: string[] | undefined; /** * `AWS::EC2::VPCEndpointService.NetworkLoadBalancerArns`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservice.html#cfn-ec2-vpcendpointservice-networkloadbalancerarns * @external */ networkLoadBalancerArns: string[] | undefined; /** * Create a new `AWS::EC2::VPCEndpointService`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnVPCEndpointServiceProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPCEndpointServicePermissions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservicepermissions.html * @external */ export interface CfnVPCEndpointServicePermissionsProps { /** * `AWS::EC2::VPCEndpointServicePermissions.ServiceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservicepermissions.html#cfn-ec2-vpcendpointservicepermissions-serviceid * @external */ readonly serviceId: string; /** * `AWS::EC2::VPCEndpointServicePermissions.AllowedPrincipals`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservicepermissions.html#cfn-ec2-vpcendpointservicepermissions-allowedprincipals * @external */ readonly allowedPrincipals?: string[]; } /** * A CloudFormation `AWS::EC2::VPCEndpointServicePermissions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservicepermissions.html * @external * @cloudformationResource AWS::EC2::VPCEndpointServicePermissions */ export declare class CfnVPCEndpointServicePermissions extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPCEndpointServicePermissions"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPCEndpointServicePermissions; /** * `AWS::EC2::VPCEndpointServicePermissions.ServiceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservicepermissions.html#cfn-ec2-vpcendpointservicepermissions-serviceid * @external */ serviceId: string; /** * `AWS::EC2::VPCEndpointServicePermissions.AllowedPrincipals`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservicepermissions.html#cfn-ec2-vpcendpointservicepermissions-allowedprincipals * @external */ allowedPrincipals: string[] | undefined; /** * Create a new `AWS::EC2::VPCEndpointServicePermissions`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPCEndpointServicePermissionsProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPCGatewayAttachment`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html * @external */ export interface CfnVPCGatewayAttachmentProps { /** * `AWS::EC2::VPCGatewayAttachment.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::VPCGatewayAttachment.InternetGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-internetgatewayid * @external */ readonly internetGatewayId?: string; /** * `AWS::EC2::VPCGatewayAttachment.VpnGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-vpngatewayid * @external */ readonly vpnGatewayId?: string; } /** * A CloudFormation `AWS::EC2::VPCGatewayAttachment`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html * @external * @cloudformationResource AWS::EC2::VPCGatewayAttachment */ export declare class CfnVPCGatewayAttachment extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPCGatewayAttachment"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPCGatewayAttachment; /** * `AWS::EC2::VPCGatewayAttachment.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-vpcid * @external */ vpcId: string; /** * `AWS::EC2::VPCGatewayAttachment.InternetGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-internetgatewayid * @external */ internetGatewayId: string | undefined; /** * `AWS::EC2::VPCGatewayAttachment.VpnGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-vpngatewayid * @external */ vpnGatewayId: string | undefined; /** * Create a new `AWS::EC2::VPCGatewayAttachment`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPCGatewayAttachmentProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPCPeeringConnection`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html * @external */ export interface CfnVPCPeeringConnectionProps { /** * `AWS::EC2::VPCPeeringConnection.PeerVpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peervpcid * @external */ readonly peerVpcId: string; /** * `AWS::EC2::VPCPeeringConnection.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-vpcid * @external */ readonly vpcId: string; /** * `AWS::EC2::VPCPeeringConnection.PeerOwnerId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peerownerid * @external */ readonly peerOwnerId?: string; /** * `AWS::EC2::VPCPeeringConnection.PeerRegion`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peerregion * @external */ readonly peerRegion?: string; /** * `AWS::EC2::VPCPeeringConnection.PeerRoleArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peerrolearn * @external */ readonly peerRoleArn?: string; /** * `AWS::EC2::VPCPeeringConnection.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::VPCPeeringConnection`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html * @external * @cloudformationResource AWS::EC2::VPCPeeringConnection */ export declare class CfnVPCPeeringConnection extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPCPeeringConnection"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPCPeeringConnection; /** * `AWS::EC2::VPCPeeringConnection.PeerVpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peervpcid * @external */ peerVpcId: string; /** * `AWS::EC2::VPCPeeringConnection.VpcId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-vpcid * @external */ vpcId: string; /** * `AWS::EC2::VPCPeeringConnection.PeerOwnerId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peerownerid * @external */ peerOwnerId: string | undefined; /** * `AWS::EC2::VPCPeeringConnection.PeerRegion`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peerregion * @external */ peerRegion: string | undefined; /** * `AWS::EC2::VPCPeeringConnection.PeerRoleArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peerrolearn * @external */ peerRoleArn: string | undefined; /** * `AWS::EC2::VPCPeeringConnection.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::VPCPeeringConnection`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPCPeeringConnectionProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPNConnection`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html * @external */ export interface CfnVPNConnectionProps { /** * `AWS::EC2::VPNConnection.CustomerGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-customergatewayid * @external */ readonly customerGatewayId: string; /** * `AWS::EC2::VPNConnection.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-type * @external */ readonly type: string; /** * `AWS::EC2::VPNConnection.StaticRoutesOnly`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-StaticRoutesOnly * @external */ readonly staticRoutesOnly?: boolean | cdk.IResolvable; /** * `AWS::EC2::VPNConnection.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-tags * @external */ readonly tags?: cdk.CfnTag[]; /** * `AWS::EC2::VPNConnection.TransitGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-transitgatewayid * @external */ readonly transitGatewayId?: string; /** * `AWS::EC2::VPNConnection.VpnGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-vpngatewayid * @external */ readonly vpnGatewayId?: string; /** * `AWS::EC2::VPNConnection.VpnTunnelOptionsSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-vpntunneloptionsspecifications * @external */ readonly vpnTunnelOptionsSpecifications?: Array<CfnVPNConnection.VpnTunnelOptionsSpecificationProperty | cdk.IResolvable> | cdk.IResolvable; } /** * A CloudFormation `AWS::EC2::VPNConnection`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html * @external * @cloudformationResource AWS::EC2::VPNConnection */ export declare class CfnVPNConnection extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPNConnection"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPNConnection; /** * `AWS::EC2::VPNConnection.CustomerGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-customergatewayid * @external */ customerGatewayId: string; /** * `AWS::EC2::VPNConnection.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-type * @external */ type: string; /** * `AWS::EC2::VPNConnection.StaticRoutesOnly`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-StaticRoutesOnly * @external */ staticRoutesOnly: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::VPNConnection.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-tags * @external */ readonly tags: cdk.TagManager; /** * `AWS::EC2::VPNConnection.TransitGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-transitgatewayid * @external */ transitGatewayId: string | undefined; /** * `AWS::EC2::VPNConnection.VpnGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-vpngatewayid * @external */ vpnGatewayId: string | undefined; /** * `AWS::EC2::VPNConnection.VpnTunnelOptionsSpecifications`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-vpntunneloptionsspecifications * @external */ vpnTunnelOptionsSpecifications: Array<CfnVPNConnection.VpnTunnelOptionsSpecificationProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * Create a new `AWS::EC2::VPNConnection`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPNConnectionProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::EC2::VPNConnection`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html * @external * @cloudformationResource AWS::EC2::VPNConnection */ export declare namespace CfnVPNConnection { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-vpnconnection-vpntunneloptionsspecification.html * @external */ interface VpnTunnelOptionsSpecificationProperty { /** * `CfnVPNConnection.VpnTunnelOptionsSpecificationProperty.PreSharedKey`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-vpnconnection-vpntunneloptionsspecification.html#cfn-ec2-vpnconnection-vpntunneloptionsspecification-presharedkey * @external */ readonly preSharedKey?: string; /** * `CfnVPNConnection.VpnTunnelOptionsSpecificationProperty.TunnelInsideCidr`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-vpnconnection-vpntunneloptionsspecification.html#cfn-ec2-vpnconnection-vpntunneloptionsspecification-tunnelinsidecidr * @external */ readonly tunnelInsideCidr?: string; } } /** * Properties for defining a `AWS::EC2::VPNConnectionRoute`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html * @external */ export interface CfnVPNConnectionRouteProps { /** * `AWS::EC2::VPNConnectionRoute.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html#cfn-ec2-vpnconnectionroute-cidrblock * @external */ readonly destinationCidrBlock: string; /** * `AWS::EC2::VPNConnectionRoute.VpnConnectionId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html#cfn-ec2-vpnconnectionroute-connectionid * @external */ readonly vpnConnectionId: string; } /** * A CloudFormation `AWS::EC2::VPNConnectionRoute`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html * @external * @cloudformationResource AWS::EC2::VPNConnectionRoute */ export declare class CfnVPNConnectionRoute extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPNConnectionRoute"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPNConnectionRoute; /** * `AWS::EC2::VPNConnectionRoute.DestinationCidrBlock`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html#cfn-ec2-vpnconnectionroute-cidrblock * @external */ destinationCidrBlock: string; /** * `AWS::EC2::VPNConnectionRoute.VpnConnectionId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html#cfn-ec2-vpnconnectionroute-connectionid * @external */ vpnConnectionId: string; /** * Create a new `AWS::EC2::VPNConnectionRoute`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPNConnectionRouteProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPNGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html * @external */ export interface CfnVPNGatewayProps { /** * `AWS::EC2::VPNGateway.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-type * @external */ readonly type: string; /** * `AWS::EC2::VPNGateway.AmazonSideAsn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-amazonsideasn * @external */ readonly amazonSideAsn?: number; /** * `AWS::EC2::VPNGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::EC2::VPNGateway`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html * @external * @cloudformationResource AWS::EC2::VPNGateway */ export declare class CfnVPNGateway extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPNGateway"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPNGateway; /** * `AWS::EC2::VPNGateway.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-type * @external */ type: string; /** * `AWS::EC2::VPNGateway.AmazonSideAsn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-amazonsideasn * @external */ amazonSideAsn: number | undefined; /** * `AWS::EC2::VPNGateway.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::EC2::VPNGateway`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPNGatewayProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VPNGatewayRoutePropagation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html * @external */ export interface CfnVPNGatewayRoutePropagationProps { /** * `AWS::EC2::VPNGatewayRoutePropagation.RouteTableIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html#cfn-ec2-vpngatewayrouteprop-routetableids * @external */ readonly routeTableIds: string[]; /** * `AWS::EC2::VPNGatewayRoutePropagation.VpnGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html#cfn-ec2-vpngatewayrouteprop-vpngatewayid * @external */ readonly vpnGatewayId: string; } /** * A CloudFormation `AWS::EC2::VPNGatewayRoutePropagation`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html * @external * @cloudformationResource AWS::EC2::VPNGatewayRoutePropagation */ export declare class CfnVPNGatewayRoutePropagation extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VPNGatewayRoutePropagation"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVPNGatewayRoutePropagation; /** * `AWS::EC2::VPNGatewayRoutePropagation.RouteTableIds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html#cfn-ec2-vpngatewayrouteprop-routetableids * @external */ routeTableIds: string[]; /** * `AWS::EC2::VPNGatewayRoutePropagation.VpnGatewayId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html#cfn-ec2-vpngatewayrouteprop-vpngatewayid * @external */ vpnGatewayId: string; /** * Create a new `AWS::EC2::VPNGatewayRoutePropagation`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVPNGatewayRoutePropagationProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::Volume`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html * @external */ export interface CfnVolumeProps { /** * `AWS::EC2::Volume.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-availabilityzone * @external */ readonly availabilityZone: string; /** * `AWS::EC2::Volume.AutoEnableIO`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-autoenableio * @external */ readonly autoEnableIo?: boolean | cdk.IResolvable; /** * `AWS::EC2::Volume.Encrypted`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-encrypted * @external */ readonly encrypted?: boolean | cdk.IResolvable; /** * `AWS::EC2::Volume.Iops`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-iops * @external */ readonly iops?: number; /** * `AWS::EC2::Volume.KmsKeyId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-kmskeyid * @external */ readonly kmsKeyId?: string; /** * `AWS::EC2::Volume.MultiAttachEnabled`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-multiattachenabled * @external */ readonly multiAttachEnabled?: boolean | cdk.IResolvable; /** * `AWS::EC2::Volume.OutpostArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-outpostarn * @external */ readonly outpostArn?: string; /** * `AWS::EC2::Volume.Size`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-size * @external */ readonly size?: number; /** * `AWS::EC2::Volume.SnapshotId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-snapshotid * @external */ readonly snapshotId?: string; /** * `AWS::EC2::Volume.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-tags * @external */ readonly tags?: cdk.CfnTag[]; /** * `AWS::EC2::Volume.VolumeType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-volumetype * @external */ readonly volumeType?: string; } /** * A CloudFormation `AWS::EC2::Volume`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html * @external * @cloudformationResource AWS::EC2::Volume */ export declare class CfnVolume extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::Volume"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVolume; /** * `AWS::EC2::Volume.AvailabilityZone`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-availabilityzone * @external */ availabilityZone: string; /** * `AWS::EC2::Volume.AutoEnableIO`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-autoenableio * @external */ autoEnableIo: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Volume.Encrypted`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-encrypted * @external */ encrypted: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Volume.Iops`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-iops * @external */ iops: number | undefined; /** * `AWS::EC2::Volume.KmsKeyId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-kmskeyid * @external */ kmsKeyId: string | undefined; /** * `AWS::EC2::Volume.MultiAttachEnabled`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-multiattachenabled * @external */ multiAttachEnabled: boolean | cdk.IResolvable | undefined; /** * `AWS::EC2::Volume.OutpostArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-outpostarn * @external */ outpostArn: string | undefined; /** * `AWS::EC2::Volume.Size`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-size * @external */ size: number | undefined; /** * `AWS::EC2::Volume.SnapshotId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-snapshotid * @external */ snapshotId: string | undefined; /** * `AWS::EC2::Volume.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-tags * @external */ readonly tags: cdk.TagManager; /** * `AWS::EC2::Volume.VolumeType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-volumetype * @external */ volumeType: string | undefined; /** * Create a new `AWS::EC2::Volume`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVolumeProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::EC2::VolumeAttachment`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html * @external */ export interface CfnVolumeAttachmentProps { /** * `AWS::EC2::VolumeAttachment.Device`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-device * @external */ readonly device: string; /** * `AWS::EC2::VolumeAttachment.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-instanceid * @external */ readonly instanceId: string; /** * `AWS::EC2::VolumeAttachment.VolumeId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-volumeid * @external */ readonly volumeId: string; } /** * A CloudFormation `AWS::EC2::VolumeAttachment`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html * @external * @cloudformationResource AWS::EC2::VolumeAttachment */ export declare class CfnVolumeAttachment extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EC2::VolumeAttachment"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnVolumeAttachment; /** * `AWS::EC2::VolumeAttachment.Device`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-device * @external */ device: string; /** * `AWS::EC2::VolumeAttachment.InstanceId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-instanceid * @external */ instanceId: string; /** * `AWS::EC2::VolumeAttachment.VolumeId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-volumeid * @external */ volumeId: string; /** * Create a new `AWS::EC2::VolumeAttachment`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnVolumeAttachmentProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; }
the_stack
export const description = ` TODO: - test compatibility between bind groups and pipelines - the binding resource in bindGroups[i].layout is "group-equivalent" (value-equal) to pipelineLayout.bgls[i]. - in the test fn, test once without the dispatch/draw (should always be valid) and once with the dispatch/draw, to make sure the validation happens in dispatch/draw. - x= {dispatch, all draws} (dispatch/draw should be size 0 to make sure validation still happens if no-op) - x= all relevant stages TODO: subsume existing test, rewrite fixture as needed. `; import { kUnitCaseParamsBuilder } from '../../../../../common/framework/params_builder.js'; import { makeTestGroup } from '../../../../../common/framework/test_group.js'; import { memcpy, unreachable } from '../../../../../common/util/util.js'; import { kSamplerBindingTypes, kShaderStageCombinations, kBufferBindingTypes, ValidBindableResource, } from '../../../../capability_info.js'; import { GPUConst } from '../../../../constants.js'; import { ProgrammableEncoderType, kProgrammableEncoderTypes, } from '../../../../util/command_buffer_maker.js'; import { ValidationTest } from '../../validation_test.js'; const kComputeCmds = ['dispatch', 'dispatchIndirect'] as const; type ComputeCmd = typeof kComputeCmds[number]; const kRenderCmds = ['draw', 'drawIndexed', 'drawIndirect', 'drawIndexedIndirect'] as const; type RenderCmd = typeof kRenderCmds[number]; // Test resource type compatibility in pipeline and bind group // TODO: Add externalTexture const kResourceTypes: ValidBindableResource[] = [ 'uniformBuf', 'filtSamp', 'sampledTex', 'storageTex', ]; function getTestCmds( encoderType: ProgrammableEncoderType ): readonly ComputeCmd[] | readonly RenderCmd[] { return encoderType === 'compute pass' ? kComputeCmds : kRenderCmds; } const kCompatTestParams = kUnitCaseParamsBuilder .combine('encoderType', kProgrammableEncoderTypes) .expand('call', p => getTestCmds(p.encoderType)) .combine('callWithZero', [true, false]); class F extends ValidationTest { getIndexBuffer(): GPUBuffer { return this.device.createBuffer({ size: 8 * Uint32Array.BYTES_PER_ELEMENT, usage: GPUBufferUsage.INDEX, }); } getIndirectBuffer(indirectParams: Array<number>): GPUBuffer { const buffer = this.device.createBuffer({ mappedAtCreation: true, size: indirectParams.length * Uint32Array.BYTES_PER_ELEMENT, usage: GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST, }); memcpy({ src: new Uint32Array(indirectParams) }, { dst: buffer.getMappedRange() }); buffer.unmap(); return buffer; } getBindingResourceType(entry: GPUBindGroupLayoutEntry): ValidBindableResource { if (entry.buffer !== undefined) return 'uniformBuf'; if (entry.sampler !== undefined) return 'filtSamp'; if (entry.texture !== undefined) return 'sampledTex'; if (entry.storageTexture !== undefined) return 'storageTex'; unreachable(); } createRenderPipelineWithLayout( bindGroups: Array<Array<GPUBindGroupLayoutEntry>> ): GPURenderPipeline { const shader = ` [[stage(vertex)]] fn vs_main() -> [[builtin(position)]] vec4<f32> { return vec4<f32>(1.0, 1.0, 0.0, 1.0); } [[stage(fragment)]] fn fs_main() -> [[location(0)]] vec4<f32> { return vec4<f32>(0.0, 1.0, 0.0, 1.0); } `; const module = this.device.createShaderModule({ code: shader }); const pipeline = this.device.createRenderPipeline({ layout: this.device.createPipelineLayout({ bindGroupLayouts: bindGroups.map(entries => this.device.createBindGroupLayout({ entries })), }), vertex: { module, entryPoint: 'vs_main', }, fragment: { module, entryPoint: 'fs_main', targets: [{ format: 'rgba8unorm' }], }, primitive: { topology: 'triangle-list' }, }); return pipeline; } createComputePipelineWithLayout( bindGroups: Array<Array<GPUBindGroupLayoutEntry>> ): GPUComputePipeline { const shader = ` [[stage(compute), workgroup_size(1, 1, 1)]] fn main([[builtin(global_invocation_id)]] GlobalInvocationID : vec3<u32>) { } `; const module = this.device.createShaderModule({ code: shader }); const pipeline = this.device.createComputePipeline({ layout: this.device.createPipelineLayout({ bindGroupLayouts: bindGroups.map(entries => this.device.createBindGroupLayout({ entries })), }), compute: { module, entryPoint: 'main', }, }); return pipeline; } createBindGroupWithLayout(bglEntries: Array<GPUBindGroupLayoutEntry>): GPUBindGroup { const bgEntries: Array<GPUBindGroupEntry> = []; for (const entry of bglEntries) { const resource = this.getBindingResource(this.getBindingResourceType(entry)); bgEntries.push({ binding: entry.binding, resource, }); } return this.device.createBindGroup({ entries: bgEntries, layout: this.device.createBindGroupLayout({ entries: bglEntries }), }); } doCompute(pass: GPUComputePassEncoder, call: ComputeCmd | undefined, callWithZero: boolean) { const x = callWithZero ? 0 : 1; switch (call) { case 'dispatch': pass.dispatch(x, 1, 1); break; case 'dispatchIndirect': pass.dispatchIndirect(this.getIndirectBuffer([x, 1, 1]), 0); break; default: break; } } doRender( pass: GPURenderPassEncoder | GPURenderBundleEncoder, call: RenderCmd | undefined, callWithZero: boolean ) { const vertexCount = callWithZero ? 0 : 3; switch (call) { case 'draw': pass.draw(vertexCount, 1, 0, 0); break; case 'drawIndexed': pass.setIndexBuffer(this.getIndexBuffer(), 'uint32'); pass.drawIndexed(vertexCount, 1, 0, 0, 0); break; case 'drawIndirect': pass.drawIndirect(this.getIndirectBuffer([vertexCount, 1, 0, 0, 0]), 0); break; case 'drawIndexedIndirect': pass.setIndexBuffer(this.getIndexBuffer(), 'uint32'); pass.drawIndexedIndirect(this.getIndirectBuffer([vertexCount, 1, 0, 0, 0]), 0); break; default: break; } } createBindGroupLayoutEntry( encoderType: ProgrammableEncoderType, resourceType: ValidBindableResource, useU32Array: boolean ): GPUBindGroupLayoutEntry { const entry: GPUBindGroupLayoutEntry = { binding: 0, visibility: encoderType === 'compute pass' ? GPUShaderStage.COMPUTE : GPUShaderStage.FRAGMENT, }; switch (resourceType) { case 'uniformBuf': entry.buffer = { hasDynamicOffset: useU32Array }; // default type: uniform break; case 'filtSamp': entry.sampler = {}; // default type: filtering break; case 'sampledTex': entry.texture = {}; // default sampleType: float break; case 'storageTex': entry.storageTexture = { access: 'write-only', format: 'rgba8unorm' }; break; } return entry; } runTest( encoderType: ProgrammableEncoderType, pipeline: GPUComputePipeline | GPURenderPipeline, bindGroups: Array<GPUBindGroup | undefined>, dynamicOffsets: Array<number> | undefined, call: ComputeCmd | RenderCmd | undefined, callWithZero: boolean, success: boolean ) { const { encoder, validateFinish } = this.createEncoder(encoderType); if (encoder instanceof GPUComputePassEncoder) { encoder.setPipeline(pipeline as GPUComputePipeline); } else { encoder.setPipeline(pipeline as GPURenderPipeline); } for (let i = 0; i < bindGroups.length; i++) { const bindGroup = bindGroups[i]; if (!bindGroup) { break; } if (dynamicOffsets) { encoder.setBindGroup( i, bindGroup, new Uint32Array(dynamicOffsets), 0, dynamicOffsets.length ); } else { encoder.setBindGroup(i, bindGroup); } } if (encoder instanceof GPUComputePassEncoder) { this.doCompute(encoder, call as ComputeCmd, callWithZero); } else { this.doRender(encoder, call as RenderCmd, callWithZero); } validateFinish(success); } } export const g = makeTestGroup(F); g.test('bind_groups_and_pipeline_layout_mismatch') .desc( ` Tests the bind groups must match the requirements of the pipeline layout. - bind groups required by the pipeline layout are required. - bind groups unused by the pipeline layout can be set or not. ` ) .params( kCompatTestParams .beginSubcases() .combineWithParams([ { setBindGroup0: true, setBindGroup1: true, setUnusedBindGroup2: true, _success: true }, { setBindGroup0: true, setBindGroup1: true, setUnusedBindGroup2: false, _success: true }, { setBindGroup0: true, setBindGroup1: false, setUnusedBindGroup2: true, _success: false }, { setBindGroup0: false, setBindGroup1: true, setUnusedBindGroup2: true, _success: false }, { setBindGroup0: false, setBindGroup1: false, setUnusedBindGroup2: false, _success: false }, ]) .combine('useU32Array', [false, true]) ) .fn(t => { const { encoderType, call, callWithZero, setBindGroup0, setBindGroup1, setUnusedBindGroup2, _success, useU32Array, } = t.params; const visibility = encoderType === 'compute pass' ? GPUShaderStage.COMPUTE : GPUShaderStage.VERTEX; const bindGroupLayouts: Array<Array<GPUBindGroupLayoutEntry>> = [ // bind group layout 0 [ { binding: 0, visibility, buffer: { hasDynamicOffset: useU32Array }, // default type: uniform }, ], // bind group layout 1 [ { binding: 0, visibility, buffer: { hasDynamicOffset: useU32Array }, // default type: uniform }, ], ]; // Create required bind groups const bindGroup0 = setBindGroup0 ? t.createBindGroupWithLayout(bindGroupLayouts[0]) : undefined; const bindGroup1 = setBindGroup1 ? t.createBindGroupWithLayout(bindGroupLayouts[1]) : undefined; const unusedBindGroup2 = setUnusedBindGroup2 ? t.createBindGroupWithLayout(bindGroupLayouts[1]) : undefined; // Create fixed pipeline const pipeline = encoderType === 'compute pass' ? t.createComputePipelineWithLayout(bindGroupLayouts) : t.createRenderPipelineWithLayout(bindGroupLayouts); const dynamicOffsets = useU32Array ? [0] : undefined; // Test without the dispatch/draw (should always be valid) t.runTest( encoderType, pipeline, [bindGroup0, bindGroup1, unusedBindGroup2], dynamicOffsets, undefined, false, true ); // Test with the dispatch/draw, to make sure the validation happens in dispatch/draw. t.runTest( encoderType, pipeline, [bindGroup0, bindGroup1, unusedBindGroup2], dynamicOffsets, call, callWithZero, _success ); }); g.test('buffer_binding,render_pipeline') .desc( ` The GPUBufferBindingLayout bindings configure should be exactly same in PipelineLayout and bindgroup. - TODO: test more draw functions, e.g. indirect - TODO: test more visibilities, e.g. vetex - TODO: bind group should be created with different layout ` ) .params(u => u.combine('type', kBufferBindingTypes)) .fn(async t => { const { type } = t.params; // Create fixed bindGroup const uniformBuffer = t.getUniformBuffer(); const bindGroup = t.device.createBindGroup({ entries: [ { binding: 0, resource: { buffer: uniformBuffer, }, }, ], layout: t.device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: {}, // default type: uniform }, ], }), }); // Create pipeline with different layouts const pipeline = t.createRenderPipelineWithLayout([ [ { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type, }, }, ], ]); const { encoder, validateFinish } = t.createEncoder('render pass'); encoder.setPipeline(pipeline); encoder.setBindGroup(0, bindGroup); encoder.draw(3); validateFinish(type === undefined || type === 'uniform'); }); g.test('sampler_binding,render_pipeline') .desc( ` The GPUSamplerBindingLayout bindings configure should be exactly same in PipelineLayout and bindgroup. - TODO: test more draw functions, e.g. indirect - TODO: test more visibilities, e.g. vetex ` ) .params(u => u // .combine('bglType', kSamplerBindingTypes) .combine('bgType', kSamplerBindingTypes) ) .fn(async t => { const { bglType, bgType } = t.params; const bindGroup = t.device.createBindGroup({ entries: [ { binding: 0, resource: bgType === 'comparison' ? t.device.createSampler({ compare: 'always' }) : t.device.createSampler(), }, ], layout: t.device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.FRAGMENT, sampler: { type: bgType }, }, ], }), }); // Create pipeline with different layouts const pipeline = t.createRenderPipelineWithLayout([ [ { binding: 0, visibility: GPUShaderStage.FRAGMENT, sampler: { type: bglType, }, }, ], ]); const { encoder, validateFinish } = t.createEncoder('render pass'); encoder.setPipeline(pipeline); encoder.setBindGroup(0, bindGroup); encoder.draw(3); validateFinish(bglType === bgType); }); g.test('bgl_binding_mismatch') .desc( 'Tests the binding number must exist or not exist in both bindGroups[i].layout and pipelineLayout.bgls[i]' ) .params( kCompatTestParams .beginSubcases() .combineWithParams([ { bgBindings: [0, 1, 2], plBindings: [0, 1, 2], _success: true }, { bgBindings: [0, 1, 2], plBindings: [0, 1, 3], _success: false }, { bgBindings: [0, 2], plBindings: [0, 2], _success: true }, { bgBindings: [0, 2], plBindings: [2, 0], _success: true }, { bgBindings: [0, 1, 2], plBindings: [0, 1], _success: false }, { bgBindings: [0, 1], plBindings: [0, 1, 2], _success: false }, ]) .combine('useU32Array', [false, true]) ) .fn(t => { const { encoderType, call, callWithZero, bgBindings, plBindings, _success, useU32Array, } = t.params; const visibility = encoderType === 'compute pass' ? GPUShaderStage.COMPUTE : GPUShaderStage.VERTEX; const bglEntries: Array<GPUBindGroupLayoutEntry> = []; for (const binding of bgBindings) { bglEntries.push({ binding, visibility, buffer: { hasDynamicOffset: useU32Array }, // default type: uniform }); } const bindGroup = t.createBindGroupWithLayout(bglEntries); const plEntries: Array<Array<GPUBindGroupLayoutEntry>> = [[]]; for (const binding of plBindings) { plEntries[0].push({ binding, visibility, buffer: { hasDynamicOffset: useU32Array }, // default type: uniform }); } const pipeline = encoderType === 'compute pass' ? t.createComputePipelineWithLayout(plEntries) : t.createRenderPipelineWithLayout(plEntries); const dynamicOffsets = useU32Array ? new Array(bgBindings.length).fill(0) : undefined; // Test without the dispatch/draw (should always be valid) t.runTest(encoderType, pipeline, [bindGroup], dynamicOffsets, undefined, false, true); // Test with the dispatch/draw, to make sure the validation happens in dispatch/draw. t.runTest(encoderType, pipeline, [bindGroup], dynamicOffsets, call, callWithZero, _success); }); g.test('bgl_visibility_mismatch') .desc('Tests the visibility in bindGroups[i].layout and pipelineLayout.bgls[i] must be matched') .params( kCompatTestParams .beginSubcases() .combine('bgVisibility', kShaderStageCombinations) .expand('plVisibility', p => p.encoderType === 'compute pass' ? ([GPUConst.ShaderStage.COMPUTE] as const) : ([ GPUConst.ShaderStage.VERTEX, GPUConst.ShaderStage.FRAGMENT, GPUConst.ShaderStage.VERTEX | GPUConst.ShaderStage.FRAGMENT, ] as const) ) .combine('useU32Array', [false, true]) ) .fn(t => { const { encoderType, call, callWithZero, bgVisibility, plVisibility, useU32Array } = t.params; const bglEntries: Array<GPUBindGroupLayoutEntry> = [ { binding: 0, visibility: bgVisibility, buffer: { hasDynamicOffset: useU32Array }, // default type: uniform }, ]; const bindGroup = t.createBindGroupWithLayout(bglEntries); const plEntries: Array<Array<GPUBindGroupLayoutEntry>> = [ [ { binding: 0, visibility: plVisibility, buffer: { hasDynamicOffset: useU32Array }, // default type: uniform }, ], ]; const pipeline = encoderType === 'compute pass' ? t.createComputePipelineWithLayout(plEntries) : t.createRenderPipelineWithLayout(plEntries); const dynamicOffsets = useU32Array ? [0] : undefined; // Test without the dispatch/draw (should always be valid) t.runTest(encoderType, pipeline, [bindGroup], dynamicOffsets, undefined, false, true); // Test with the dispatch/draw, to make sure the validation happens in dispatch/draw. t.runTest( encoderType, pipeline, [bindGroup], dynamicOffsets, call, callWithZero, bgVisibility === plVisibility ); }); g.test('bgl_resource_type_mismatch') .desc( ` Tests the binding resource type in bindGroups[i].layout and pipelineLayout.bgls[i] must be matched - TODO: Test externalTexture ` ) .params( kCompatTestParams .beginSubcases() .combine('bgResourceType', kResourceTypes) .combine('plResourceType', kResourceTypes) .expand('useU32Array', p => (p.bgResourceType === 'uniformBuf' ? [true, false] : [false])) ) .fn(t => { const { encoderType, call, callWithZero, bgResourceType, plResourceType, useU32Array, } = t.params; const bglEntries: Array<GPUBindGroupLayoutEntry> = [ t.createBindGroupLayoutEntry(encoderType, bgResourceType, useU32Array), ]; const bindGroup = t.createBindGroupWithLayout(bglEntries); const plEntries: Array<Array<GPUBindGroupLayoutEntry>> = [ [t.createBindGroupLayoutEntry(encoderType, plResourceType, useU32Array)], ]; const pipeline = encoderType === 'compute pass' ? t.createComputePipelineWithLayout(plEntries) : t.createRenderPipelineWithLayout(plEntries); const dynamicOffsets = useU32Array ? [0] : undefined; // Test without the dispatch/draw (should always be valid) t.runTest(encoderType, pipeline, [bindGroup], dynamicOffsets, undefined, false, true); // Test with the dispatch/draw, to make sure the validation happens in dispatch/draw. t.runTest( encoderType, pipeline, [bindGroup], dynamicOffsets, call, callWithZero, bgResourceType === plResourceType ); });
the_stack
* Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ import { errors } from '@elastic/elasticsearch'; import { opensearchClientMock } from './mocks'; import { loggingSystemMock } from '../../logging/logging_system.mock'; import { retryCallCluster, migrationRetryCallCluster } from './retry_call_cluster'; const dummyBody = { foo: 'bar' }; const createErrorReturn = (err: any) => opensearchClientMock.createErrorTransportRequestPromise(err); describe('retryCallCluster', () => { let client: ReturnType<typeof opensearchClientMock.createOpenSearchClient>; beforeEach(() => { client = opensearchClientMock.createOpenSearchClient(); }); it('returns response from OpenSearch API call in case of success', async () => { const successReturn = opensearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody, }); client.asyncSearch.get.mockReturnValue(successReturn); const result = await retryCallCluster(() => client.asyncSearch.get()); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects with `NoLivingConnectionsError`', async () => { const successReturn = opensearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody, }); client.asyncSearch.get .mockImplementationOnce(() => createErrorReturn(new errors.NoLivingConnectionsError('no living connections', {} as any)) ) .mockImplementationOnce(() => successReturn); const result = await retryCallCluster(() => client.asyncSearch.get()); expect(result.body).toEqual(dummyBody); }); it('rejects when OpenSearch API calls reject with other errors', async () => { client.ping .mockImplementationOnce(() => createErrorReturn(new Error('unknown error'))) .mockImplementationOnce(() => opensearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) ); await expect(retryCallCluster(() => client.ping())).rejects.toMatchInlineSnapshot( `[Error: unknown error]` ); }); it('stops retrying when OpenSearch API calls reject with other errors', async () => { client.ping .mockImplementationOnce(() => createErrorReturn(new errors.NoLivingConnectionsError('no living connections', {} as any)) ) .mockImplementationOnce(() => createErrorReturn(new errors.NoLivingConnectionsError('no living connections', {} as any)) ) .mockImplementationOnce(() => createErrorReturn(new Error('unknown error'))) .mockImplementationOnce(() => opensearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) ); await expect(retryCallCluster(() => client.ping())).rejects.toMatchInlineSnapshot( `[Error: unknown error]` ); }); }); describe('migrationRetryCallCluster', () => { let client: ReturnType<typeof opensearchClientMock.createOpenSearchClient>; let logger: ReturnType<typeof loggingSystemMock.createLogger>; beforeEach(() => { client = opensearchClientMock.createOpenSearchClient(); logger = loggingSystemMock.createLogger(); }); const mockClientPingWithErrorBeforeSuccess = (error: any) => { client.ping .mockImplementationOnce(() => createErrorReturn(error)) .mockImplementationOnce(() => createErrorReturn(error)) .mockImplementationOnce(() => opensearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) ); }; it('retries OpenSearch API calls that rejects with `NoLivingConnectionsError`', async () => { mockClientPingWithErrorBeforeSuccess( new errors.NoLivingConnectionsError('no living connections', {} as any) ); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects with `ConnectionError`', async () => { mockClientPingWithErrorBeforeSuccess(new errors.ConnectionError('connection error', {} as any)); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects with `TimeoutError`', async () => { mockClientPingWithErrorBeforeSuccess(new errors.TimeoutError('timeout error', {} as any)); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects with 503 `ResponseError`', async () => { mockClientPingWithErrorBeforeSuccess( new errors.ResponseError({ statusCode: 503, } as any) ); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects 401 `ResponseError`', async () => { mockClientPingWithErrorBeforeSuccess( new errors.ResponseError({ statusCode: 401, } as any) ); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects with 403 `ResponseError`', async () => { mockClientPingWithErrorBeforeSuccess( new errors.ResponseError({ statusCode: 403, } as any) ); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects with 408 `ResponseError`', async () => { mockClientPingWithErrorBeforeSuccess( new errors.ResponseError({ statusCode: 408, } as any) ); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects with 410 `ResponseError`', async () => { mockClientPingWithErrorBeforeSuccess( new errors.ResponseError({ statusCode: 410, } as any) ); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('retries OpenSearch API calls that rejects with `snapshot_in_progress_exception` `ResponseError`', async () => { mockClientPingWithErrorBeforeSuccess( new errors.ResponseError({ statusCode: 500, body: { error: { type: 'snapshot_in_progress_exception', }, }, } as any) ); const result = await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(result.body).toEqual(dummyBody); }); it('logs only once for each unique error message', async () => { client.ping .mockImplementationOnce(() => createErrorReturn( new errors.ResponseError({ statusCode: 503, } as any) ) ) .mockImplementationOnce(() => createErrorReturn(new errors.ConnectionError('connection error', {} as any)) ) .mockImplementationOnce(() => createErrorReturn( new errors.ResponseError({ statusCode: 503, } as any) ) ) .mockImplementationOnce(() => createErrorReturn(new errors.ConnectionError('connection error', {} as any)) ) .mockImplementationOnce(() => createErrorReturn( new errors.ResponseError({ statusCode: 500, body: { error: { type: 'snapshot_in_progress_exception', }, }, } as any) ) ) .mockImplementationOnce(() => opensearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) ); await migrationRetryCallCluster(() => client.ping(), logger, 1); expect(loggingSystemMock.collect(logger).warn).toMatchInlineSnapshot(` Array [ Array [ "Unable to connect to OpenSearch. Error: Response Error", ], Array [ "Unable to connect to OpenSearch. Error: connection error", ], Array [ "Unable to connect to OpenSearch. Error: snapshot_in_progress_exception", ], ] `); }); it('rejects when OpenSearch API calls reject with other errors', async () => { client.ping .mockImplementationOnce(() => createErrorReturn( new errors.ResponseError({ statusCode: 418, body: { error: { type: `I'm a teapot`, }, }, } as any) ) ) .mockImplementationOnce(() => opensearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) ); await expect( migrationRetryCallCluster(() => client.ping(), logger, 1) ).rejects.toMatchInlineSnapshot(`[ResponseError: I'm a teapot]`); }); it('stops retrying when OpenSearch API calls reject with other errors', async () => { client.ping .mockImplementationOnce(() => createErrorReturn(new errors.TimeoutError('timeout error', {} as any)) ) .mockImplementationOnce(() => createErrorReturn(new errors.TimeoutError('timeout error', {} as any)) ) .mockImplementationOnce(() => createErrorReturn(new Error('unknown error'))) .mockImplementationOnce(() => opensearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) ); await expect( migrationRetryCallCluster(() => client.ping(), logger, 1) ).rejects.toMatchInlineSnapshot(`[Error: unknown error]`); }); });
the_stack
"use strict"; import * as net from "net"; import * as path from "path"; import * as fs from "fs"; import * as vscode from "vscode"; import { workspace, Disposable, ExtensionContext, window, commands, ConfigurationTarget, debug, DebugAdapterExecutable, ProviderResult, DebugConfiguration, WorkspaceFolder, CancellationToken, DebugConfigurationProvider, extensions, } from "vscode"; import { LanguageClientOptions, State } from "vscode-languageclient"; import { LanguageClient, ServerOptions } from "vscode-languageclient/node"; import { ProgressReport, handleProgressMessage } from "./progress"; import { Timing } from "./time"; import { registerRunCommands } from "./run"; import { registerLinkProviders } from "./linkProvider"; import { expandVars, getArrayStrFromConfigExpandingVars, getStrFromConfigExpandingVars } from "./expandVars"; import { registerInteractiveCommands } from "./interactive/rfInteractive"; import { logError, OUTPUT_CHANNEL } from "./channel"; interface ExecuteWorkspaceCommandArgs { command: string; arguments: any; } function createClientOptions(initializationOptions: object): LanguageClientOptions { const clientOptions: LanguageClientOptions = { documentSelector: ["robotframework"], synchronize: { configurationSection: ["robot", "robocorp.home"], }, outputChannel: OUTPUT_CHANNEL, initializationOptions: initializationOptions, }; return clientOptions; } function startLangServerIO(command: string, args: string[], initializationOptions: object): LanguageClient { const serverOptions: ServerOptions = { command, args, }; let src: string = path.resolve(__dirname, "../../src"); serverOptions.options = { env: { ...process.env, PYTHONPATH: src } }; // See: https://code.visualstudio.com/api/language-extensions/language-server-extension-guide return new LanguageClient(command, serverOptions, createClientOptions(initializationOptions)); } function startLangServerTCP(addr: number, initializationOptions: object): LanguageClient { const serverOptions: ServerOptions = function () { return new Promise((resolve, reject) => { var client = new net.Socket(); client.connect(addr, "127.0.0.1", function () { resolve({ reader: client, writer: client, }); }); }); }; return new LanguageClient( `tcp lang server (port ${addr})`, serverOptions, createClientOptions(initializationOptions) ); } function findExecutableInPath(executable: string) { const IS_WINDOWS = process.platform == "win32"; const sep = IS_WINDOWS ? ";" : ":"; const PATH = process.env["PATH"]; const split = PATH.split(sep); for (let i = 0; i < split.length; i++) { const s = path.join(split[i], executable); if (fs.existsSync(s)) { return s; } } return undefined; } class RobotDebugConfigurationProvider implements DebugConfigurationProvider { provideDebugConfigurations?(folder: WorkspaceFolder | undefined, token?: CancellationToken): DebugConfiguration[] { let configurations: DebugConfiguration[] = []; configurations.push({ "type": "robotframework-lsp", "name": "Robot Framework: Launch .robot file", "request": "launch", "cwd": '^"\\${workspaceFolder}"', "target": '^"\\${file}"', "terminal": "none", "env": {}, "args": [], }); return configurations; } async resolveDebugConfigurationWithSubstitutedVariables( folder: WorkspaceFolder | undefined, debugConfiguration: DebugConfiguration, token?: CancellationToken ): Promise<DebugConfiguration> { // When we resolve a configuration we add the pythonpath and variables to the command line. let args: Array<string> = debugConfiguration.args; let config = workspace.getConfiguration("robot"); let pythonpath: Array<string> = getArrayStrFromConfigExpandingVars(config, "pythonpath"); let variables: object = config.get("variables"); let targetRobot: object = debugConfiguration.target; // If it's not specified in the language, let's check if some plugin wants to provide an implementation. let interpreter: InterpreterInfo = await commands.executeCommand("robot.resolveInterpreter", targetRobot); if (interpreter) { pythonpath = pythonpath.concat(interpreter.additionalPythonpathEntries); if (interpreter.environ) { if (!debugConfiguration.env) { debugConfiguration.env = interpreter.environ; } else { for (let key of Object.keys(interpreter.environ)) { debugConfiguration.env[key] = interpreter.environ[key]; } } } // Also, overridde env variables in the launch config. try { let newEnv: { [key: string]: string } | "cancelled" = await commands.executeCommand( "robocorp.updateLaunchEnv", { "targetRobot": targetRobot, "env": debugConfiguration.env, } ); if (newEnv == "cancelled") { OUTPUT_CHANNEL.appendLine("Launch cancelled"); return undefined; } debugConfiguration.env = newEnv; } catch (error) { // The command may not be available. } } let newArgs = []; pythonpath.forEach((element) => { newArgs.push("--pythonpath"); newArgs.push(element); }); for (let key in variables) { if (variables.hasOwnProperty(key)) { newArgs.push("--variable"); newArgs.push(key + ":" + expandVars(variables[key])); } } if (args) { args = args.concat(newArgs); } else { args = newArgs; } debugConfiguration.args = args; if (debugConfiguration.cwd) { let stat: vscode.FileStat; try { stat = await vscode.workspace.fs.stat(vscode.Uri.file(debugConfiguration.cwd)); } catch (err) { window.showErrorMessage( "Unable to launch. Reason: the cwd: " + debugConfiguration.cwd + " does not exist." ); return undefined; } if ((stat.type | vscode.FileType.File) == 1) { window.showErrorMessage( "Unable to launch. Reason: the cwd: " + debugConfiguration.cwd + " seems to be a file and not a directory." ); return undefined; } } return debugConfiguration; } } interface InterpreterInfo { pythonExe: string; environ?: { [key: string]: string }; additionalPythonpathEntries: string[]; } function registerDebugger(languageServerExecutable: string) { async function createDebugAdapterExecutable( env: { [key: string]: string }, targetRobot: string ): Promise<DebugAdapterExecutable> { let dapPythonExecutable: string = getStrFromConfigExpandingVars( workspace.getConfiguration("robot"), "python.executable" ); // If it's not specified in the language, let's check if some plugin wants to provide an implementation. let interpreter: InterpreterInfo = await commands.executeCommand("robot.resolveInterpreter", targetRobot); if (interpreter) { dapPythonExecutable = interpreter.pythonExe; if (interpreter.environ) { if (!env) { env = interpreter.environ; } else { for (let key of Object.keys(interpreter.environ)) { env[key] = interpreter.environ[key]; } } } } else if (!dapPythonExecutable && env) { // If a `PYTHON_EXE` is specified in the env, give it priority vs using the language server // executable. dapPythonExecutable = env["PYTHON_EXE"]; } if (!dapPythonExecutable) { // If the dapPythonExecutable is not specified, use the default language server executable. if (!languageServerExecutable) { window.showWarningMessage( "Error getting language server python executable for creating a debug adapter." ); return; } dapPythonExecutable = languageServerExecutable; } let targetMain: string = path.resolve(__dirname, "../../src/robotframework_debug_adapter/__main__.py"); if (!fs.existsSync(targetMain)) { window.showWarningMessage("Error. Expected: " + targetMain + " to exist."); return; } if (!fs.existsSync(dapPythonExecutable)) { window.showWarningMessage("Error. Expected: " + dapPythonExecutable + " to exist."); return; } if (env) { return new DebugAdapterExecutable(dapPythonExecutable, ["-u", targetMain], { "env": env }); } else { return new DebugAdapterExecutable(dapPythonExecutable, ["-u", targetMain]); } } try { debug.registerDebugConfigurationProvider("robotframework-lsp", new RobotDebugConfigurationProvider()); debug.registerDebugAdapterDescriptorFactory("robotframework-lsp", { createDebugAdapterDescriptor: (session) => { let env = session.configuration.env; let target = session.configuration.target; return createDebugAdapterExecutable(env, target); }, }); } catch (error) { // i.e.: https://github.com/microsoft/vscode/issues/118562 logError("Error registering debugger.", error); } } interface ExecutableAndMessage { executable: string; message: string; } async function getDefaultLanguageServerPythonExecutable(): Promise<ExecutableAndMessage> { OUTPUT_CHANNEL.appendLine("Getting language server Python executable."); let languageServerPython: string = getStrFromConfigExpandingVars( workspace.getConfiguration("robot"), "language-server.python" ); let executable: string = languageServerPython; if (!executable || (executable.indexOf("/") == -1 && executable.indexOf("\\") == -1)) { // Try to use the Robocorp Code extension to provide one for us (if it's installed and // available). try { let languageServerPython: string = await commands.executeCommand<string>( "robocorp.getLanguageServerPython" ); if (languageServerPython) { OUTPUT_CHANNEL.appendLine( "Language server Python executable gotten from robocorp.getLanguageServerPython." ); return { executable: languageServerPython, "message": undefined, }; } } catch (error) { // The command may not be available (in this case, go forward and try to find it in the filesystem). } // Search python from the path. if (!executable) { OUTPUT_CHANNEL.appendLine("Language server Python executable. Searching in PATH."); if (process.platform == "win32") { executable = findExecutableInPath("python.exe"); } else { executable = findExecutableInPath("python3"); if (!fs.existsSync(executable)) { executable = findExecutableInPath("python"); } } } else { OUTPUT_CHANNEL.appendLine("Language server Python executable. Searching " + executable + " from the PATH."); executable = findExecutableInPath(executable); OUTPUT_CHANNEL.appendLine("Language server Python executable. Found: " + executable); } if (!fs.existsSync(executable)) { return { executable: undefined, "message": "Unable to start robotframework-lsp because: python could not be found on the PATH. Do you want to select a python executable to start robotframework-lsp?", }; } return { executable: executable, "message": undefined, }; } else { if (!fs.existsSync(executable)) { return { executable: undefined, "message": "Unable to start robotframework-lsp because: " + executable + " does not exist. Do you want to select a new python executable to start robotframework-lsp?", }; } return { executable: executable, "message": undefined, }; } } export async function activate(context: ExtensionContext) { try { // The first thing we need is the python executable. let timing = new Timing(); let executableAndMessage = await getDefaultLanguageServerPythonExecutable(); if (executableAndMessage.message) { OUTPUT_CHANNEL.appendLine(executableAndMessage.message); let saveInUser: string = "Yes (save in user settings)"; let saveInWorkspace: string = "Yes (save in workspace settings)"; let selection = await window.showWarningMessage( executableAndMessage.message, ...[saveInUser, saveInWorkspace, "No"] ); // robot.language-server.python if (selection == saveInUser || selection == saveInWorkspace) { let onfulfilled = await window.showOpenDialog({ "canSelectMany": false, "openLabel": "Select python exe", }); if (!onfulfilled || onfulfilled.length == 0) { // There's not much we can do (besides start listening to changes to the related variables // on the finally block so that we start listening and ask for a reload if a related configuration changes). OUTPUT_CHANNEL.appendLine("Unable to start (python selection cancelled)."); return; } let configurationTarget: ConfigurationTarget; if (selection == saveInUser) { configurationTarget = ConfigurationTarget.Global; } else { configurationTarget = ConfigurationTarget.Workspace; } let config = workspace.getConfiguration("robot"); try { config.update("language-server.python", onfulfilled[0].fsPath, configurationTarget); } catch (err) { let errorMessage = "Error persisting python to start the language server.\nError: " + err.message; logError("Error persisting python to start the language server.", err); if (configurationTarget == ConfigurationTarget.Workspace) { try { config.update("language-server.python", onfulfilled[0].fsPath, ConfigurationTarget.Global); window.showInformationMessage( "It was not possible to save the configuration in the workspace. It was saved in the user settings instead." ); err = undefined; } catch (err2) { // ignore this one (show original error). } } if (err !== undefined) { window.showErrorMessage(errorMessage); } } executableAndMessage = { "executable": onfulfilled[0].fsPath, message: undefined }; } else { // There's not much we can do (besides start listening to changes to the related variables // on the finally block so that we start listening and ask for a reload if a related configuration changes). OUTPUT_CHANNEL.appendLine("Unable to start (no python executable specified)."); return; } } let port: number = workspace.getConfiguration("robot").get<number>("language-server.tcp-port"); let langServer: LanguageClient; let initializationOptions: object = {}; try { let pluginsDir: string = await commands.executeCommand<string>("robocorp.getPluginsDir"); try { if (pluginsDir && pluginsDir.length > 0) { OUTPUT_CHANNEL.appendLine("Plugins dir: " + pluginsDir + "."); initializationOptions["pluginsDir"] = pluginsDir; } } catch (error) { logError("Error setting pluginsDir.", error); } } catch (error) { // The command may not be available. } if (port) { // For TCP server needs to be started seperately OUTPUT_CHANNEL.appendLine("Connecting to port: " + port); langServer = startLangServerTCP(port, initializationOptions); } else { let targetMain: string = path.resolve(__dirname, "../../src/robotframework_ls/__main__.py"); if (!fs.existsSync(targetMain)) { window.showWarningMessage("Error. Expected: " + targetMain + " to exist."); return; } let args: Array<string> = ["-u", targetMain]; let lsArgs = workspace.getConfiguration("robot").get<Array<string>>("language-server.args"); if (lsArgs) { args = args.concat(lsArgs); } OUTPUT_CHANNEL.appendLine( "Starting RobotFramework Language Server with args: " + executableAndMessage.executable + "," + args ); langServer = startLangServerIO(executableAndMessage.executable, args, initializationOptions); } let stopListeningOnDidChangeState = langServer.onDidChangeState((event) => { if (event.newState == State.Running) { // i.e.: We need to register the customProgress as soon as it's running (we can't wait for onReady) // because at that point if there are open documents, lots of things may've happened already, in // which case the progress won't be shown on some cases where it should be shown. context.subscriptions.push( langServer.onNotification("$/customProgress", (args: ProgressReport) => { // OUTPUT_CHANNEL.appendLine(args.id + ' - ' + args.kind + ' - ' + args.title + ' - ' + args.message + ' - ' + args.increment); handleProgressMessage(args); }) ); context.subscriptions.push( langServer.onRequest("$/executeWorkspaceCommand", async (args: ExecuteWorkspaceCommandArgs) => { // OUTPUT_CHANNEL.appendLine(args.command + " - " + args.arguments); let ret; try { ret = await commands.executeCommand(args.command, args.arguments); } catch (err) { if (!(err.message && err.message.endsWith("not found"))) { // Log if the error wasn't that the command wasn't found logError("Error executing workspace command.", err); } } return ret; }) ); stopListeningOnDidChangeState.dispose(); } }); let disposable: Disposable = langServer.start(); registerDebugger(executableAndMessage.executable); await registerRunCommands(context); await registerLinkProviders(context); await registerInteractiveCommands(context, langServer); context.subscriptions.push(disposable); // i.e.: if we return before it's ready, the language server commands // may not be available. OUTPUT_CHANNEL.appendLine("Waiting for RobotFramework (python) Language Server to finish activating..."); await langServer.onReady(); let version = extensions.getExtension("robocorp.robotframework-lsp").packageJSON.version; try { let lsVersion = await commands.executeCommand("robot.getLanguageServerVersion"); if (lsVersion != version) { window.showErrorMessage( "Error: expected robotframework-lsp version: " + version + ". Found: " + lsVersion + "." + " Please uninstall the older version from the python environment." ); } } catch (err) { let msg = "Error: robotframework-lsp version mismatch. Please uninstall the older version from the python environment."; logError(msg, err); window.showErrorMessage(msg); } OUTPUT_CHANNEL.appendLine("RobotFramework Language Server ready. Took: " + timing.getTotalElapsedAsStr()); } finally { workspace.onDidChangeConfiguration((event) => { for (let s of [ "robot.language-server.python", "robot.language-server.tcp-port", "robot.language-server.args", ]) { if (event.affectsConfiguration(s)) { window .showWarningMessage( 'Please use the "Reload Window" action for changes in ' + s + " to take effect.", ...["Reload Window"] ) .then((selection) => { if (selection === "Reload Window") { commands.executeCommand("workbench.action.reloadWindow"); } }); return; } } }); } }
the_stack
import 'fake-indexeddb/auto'; import { initSchema as initSchemaType, syncClasses, ModelInstanceCreator, } from '../src/datastore/datastore'; import { ExclusiveStorage as StorageType } from '../src/storage/storage'; import { MutationEventOutbox } from '../src/sync/outbox'; import { ModelMerger } from '../src/sync/merger'; import { Model as ModelType, testSchema, internalTestSchema } from './helpers'; import { TransformerMutationType, createMutationInstanceFromModelOperation, } from '../src/sync/utils'; import { PersistentModelConstructor, InternalSchema, SchemaModel, } from '../src/types'; import { MutationEvent } from '../src/sync/'; let initSchema: typeof initSchemaType; // using <any> to access private members let DataStore: any; let Storage: StorageType; let anyStorage: any; let outbox: MutationEventOutbox; let merger: ModelMerger; let modelInstanceCreator: ModelInstanceCreator; let Model: PersistentModelConstructor<ModelType>; const schema: InternalSchema = internalTestSchema(); describe('Outbox tests', () => { let modelId: string; beforeAll(async () => { jest.resetAllMocks(); await instantiateOutbox(); const newModel = new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), }); const mutationEvent = await createMutationEvent(newModel); ({ modelId } = mutationEvent); await outbox.enqueue(Storage, mutationEvent); }); it('Should return the create mutation from Outbox.peek', async () => { await Storage.runExclusive(async s => { let head; while (!head) { head = await outbox.peek(s); } const modelData: ModelType = JSON.parse(head.data); expect(head.modelId).toEqual(modelId); expect(head.operation).toEqual(TransformerMutationType.CREATE); expect(modelData.field1).toEqual('Some value'); const response = { ...modelData, _version: 1, _lastChangedAt: Date.now(), _deleted: false, }; await processMutationResponse( s, response, TransformerMutationType.CREATE ); head = await outbox.peek(s); expect(head).toBeFalsy(); }); }); it('Should sync the _version from a mutation response to other items with the same `id` in the queue', async () => { const last = await DataStore.query(Model, modelId); const updatedModel1 = Model.copyOf(last, updated => { updated.field1 = 'another value'; updated.dateCreated = new Date().toISOString(); }); const mutationEvent = await createMutationEvent(updatedModel1); await outbox.enqueue(Storage, mutationEvent); await Storage.runExclusive(async s => { // this mutation is now "in progress" let head; while (!head) { head = await outbox.peek(s); } const modelData: ModelType = JSON.parse(head.data); expect(head.modelId).toEqual(modelId); expect(head.operation).toEqual(TransformerMutationType.UPDATE); expect(modelData.field1).toEqual('another value'); const mutationsForModel = await outbox.getForModel(s, last); expect(mutationsForModel.length).toEqual(1); }); // add 2 update mutations to the queue: const updatedModel2 = Model.copyOf(last, updated => { updated.field1 = 'another value2'; updated.dateCreated = new Date().toISOString(); }); await outbox.enqueue(Storage, await createMutationEvent(updatedModel2)); const updatedModel3 = Model.copyOf(last, updated => { updated.field1 = 'another value3'; updated.dateCreated = new Date().toISOString(); }); await outbox.enqueue(Storage, await createMutationEvent(updatedModel3)); // model2 should get deleted when model3 is enqueued, so we're expecting to see // 2 items in the queue for this Model total (including the in progress record - updatedModel1) const mutationsForModel = await outbox.getForModel(Storage, last); expect(mutationsForModel.length).toEqual(2); const [_inProgress, nextMutation] = mutationsForModel; const modelData: ModelType = JSON.parse(nextMutation.data); // and the next item in the queue should be updatedModel3 expect(modelData.field1).toEqual('another value3'); // response from AppSync for the first update mutation - updatedModel1: const response = { ...updatedModel1, _version: (updatedModel1 as any)._version + 1, // increment version like we would expect coming back from AppSync _lastChangedAt: Date.now(), _deleted: false, createdAt: '2021-11-30T20:51:00.250Z', updatedAt: '2021-11-30T20:52:00.250Z', }; await Storage.runExclusive(async s => { // process mutation response, which dequeues updatedModel1 // and syncs its version to the remaining item in the mutation queue await processMutationResponse( s, response, TransformerMutationType.UPDATE ); const inProgress = await outbox.peek(s); const inProgressData = JSON.parse(inProgress.data); // updatedModel3 should now be in progress with the _version from the mutation response expect(inProgressData.field1).toEqual('another value3'); expect(inProgressData._version).toEqual(2); // response from AppSync for the second update mutation - updatedModel3: const response2 = { ...updatedModel3, _version: inProgressData._version + 1, // increment version like we would expect coming back from AppSync _lastChangedAt: Date.now(), _deleted: false, createdAt: '2021-11-30T20:51:00.250Z', updatedAt: '2021-11-30T20:52:00.250Z', }; await processMutationResponse( s, response2, TransformerMutationType.UPDATE ); const head = await outbox.peek(s); expect(head).toBeFalsy(); }); }); it('Should NOT sync the _version from a handled conflict mutation response', async () => { const last = await DataStore.query(Model, modelId); const updatedModel1 = Model.copyOf(last, updated => { updated.field1 = 'another value'; updated.dateCreated = new Date().toISOString(); }); const mutationEvent = await createMutationEvent(updatedModel1); await outbox.enqueue(Storage, mutationEvent); await Storage.runExclusive(async s => { // this mutation is now "in progress" let head; while (!head) { head = await outbox.peek(s); } const modelData: ModelType = JSON.parse(head.data); expect(head.modelId).toEqual(modelId); expect(head.operation).toEqual(TransformerMutationType.UPDATE); expect(modelData.field1).toEqual('another value'); const mutationsForModel = await outbox.getForModel(s, last); expect(mutationsForModel.length).toEqual(1); }); // add an update mutations to the queue: const updatedModel2 = Model.copyOf(last, updated => { updated.field1 = 'another value2'; updated.dateCreated = new Date().toISOString(); }); await outbox.enqueue(Storage, await createMutationEvent(updatedModel2)); // 2 items in the queue for this Model total (including the in progress record - updatedModel1) const mutationsForModel = await outbox.getForModel(Storage, last); expect(mutationsForModel.length).toEqual(2); const [_inProgress, nextMutation] = mutationsForModel; const modelData: ModelType = JSON.parse(nextMutation.data); // and the next item in the queue should be updatedModel2 expect(modelData.field1).toEqual('another value2'); // response from AppSync with a handled conflict: const response = { ...updatedModel1, field1: 'a different value set by another client', _version: (updatedModel1 as any)._version + 1, // increment version like we would expect coming back from AppSync _lastChangedAt: Date.now(), _deleted: false, }; await Storage.runExclusive(async s => { // process mutation response, which dequeues updatedModel1 // but SHOULD NOT sync the _version, since the data in the response is different await processMutationResponse( s, response, TransformerMutationType.UPDATE ); const inProgress = await outbox.peek(s); const inProgressData = JSON.parse(inProgress.data); // updatedModel2 should now be in progress with the _version from the mutation response expect(inProgressData.field1).toEqual('another value2'); const oldVersion = (modelData as any)._version; expect(inProgressData._version).toEqual(oldVersion); // same response as above, await processMutationResponse( s, response, TransformerMutationType.UPDATE ); const head = await outbox.peek(s); expect(head).toBeFalsy(); }); }); // https://github.com/aws-amplify/amplify-js/issues/7888 it('Should retain the fields from the create mutation in the queue when it gets merged with an enqueued update mutation', async () => { const field1 = 'Some value'; const currentTimestamp = new Date().toISOString(); const optionalField1 = 'Optional value'; const newModel = new Model({ field1, dateCreated: currentTimestamp, }); const mutationEvent = await createMutationEvent(newModel); ({ modelId } = mutationEvent); await outbox.enqueue(Storage, mutationEvent); const updatedModel = Model.copyOf(newModel, updated => { updated.optionalField1 = optionalField1; }); const updateMutationEvent = await createMutationEvent(updatedModel); await outbox.enqueue(Storage, updateMutationEvent); await Storage.runExclusive(async s => { const head = await outbox.peek(s); const headData = JSON.parse(head.data); expect(headData.field1).toEqual(field1); expect(headData.dateCreated).toEqual(currentTimestamp); expect(headData.optionalField1).toEqual(optionalField1); }); }); }); // performs all the required dependency injection // in order to have a functional Outbox without the Sync Engine async function instantiateOutbox(): Promise<void> { ({ initSchema, DataStore } = require('../src/datastore/datastore')); const classes = initSchema(testSchema()); const ownSymbol = Symbol('sync'); ({ Model } = classes as { Model: PersistentModelConstructor<ModelType>; }); const MutationEvent = syncClasses[ 'MutationEvent' ] as PersistentModelConstructor<any>; await DataStore.start(); Storage = <StorageType>DataStore.storage; anyStorage = Storage; const namespaceResolver = anyStorage.storage.namespaceResolver.bind(anyStorage); ({ modelInstanceCreator } = anyStorage.storage); const getModelDefinition = ( modelConstructor: PersistentModelConstructor<any> ): SchemaModel => { const namespaceName = namespaceResolver(modelConstructor); const modelDefinition = schema.namespaces[namespaceName].models[modelConstructor.name]; return modelDefinition; }; const userClasses = {}; userClasses['Model'] = Model; outbox = new MutationEventOutbox( schema, MutationEvent, modelInstanceCreator, ownSymbol ); merger = new ModelMerger(outbox, ownSymbol); } async function createMutationEvent(model): Promise<MutationEvent> { const [[originalElement, opType]] = await anyStorage.storage.save(model); const MutationEventConstructor = syncClasses[ 'MutationEvent' ] as PersistentModelConstructor<MutationEvent>; const modelConstructor = (Object.getPrototypeOf(originalElement) as Object) .constructor as PersistentModelConstructor<any>; return createMutationInstanceFromModelOperation( undefined, undefined, opType, modelConstructor, originalElement, {}, MutationEventConstructor, modelInstanceCreator ); } async function processMutationResponse( storage, record, recordOp ): Promise<void> { await outbox.dequeue(storage, record, recordOp); const modelConstructor = Model as PersistentModelConstructor<any>; const model = modelInstanceCreator(modelConstructor, record); await merger.merge(storage, model); }
the_stack
import * as React from "react" import { motion } from "../.." import { fireEvent } from "@testing-library/dom" import { motionValue } from "../../value" import { mouseDown, mouseEnter, mouseLeave, mouseUp, render, } from "../../../jest.setup" import { drag, MockDrag } from "../drag/__tests__/utils" describe("press", () => { test("press event listeners fire", () => { const press = jest.fn() const Component = () => <motion.div onTap={() => press()} /> const { container, rerender } = render(<Component />) rerender(<Component />) fireEvent.mouseDown(container.firstChild as Element) fireEvent.mouseUp(container.firstChild as Element) expect(press).toBeCalledTimes(1) }) test("press event listeners are cleaned up", () => { const press = jest.fn() const { container, rerender } = render( <motion.div onTap={() => press()} /> ) rerender(<motion.div onTap={() => press()} />) fireEvent.mouseDown(container.firstChild as Element) fireEvent.mouseUp(container.firstChild as Element) expect(press).toBeCalledTimes(1) rerender(<motion.div />) fireEvent.mouseDown(container.firstChild as Element) fireEvent.mouseUp(container.firstChild as Element) expect(press).toBeCalledTimes(1) }) test("onTapCancel is correctly removed from a component", () => { const cancelA = jest.fn() const Component = () => ( <> <motion.div data-testid="a" onTap={() => {}} onTapCancel={cancelA} /> <motion.div data-testid="b" onTap={() => {}} /> </> ) const { getByTestId } = render(<Component />) const a = getByTestId("a") const b = getByTestId("b") fireEvent.mouseDown(a) fireEvent.mouseUp(a) expect(cancelA).not.toHaveBeenCalled() fireEvent.mouseDown(b) fireEvent.mouseUp(b) expect(cancelA).not.toHaveBeenCalled() }) test("press event listeners fire if triggered by child", () => { const press = jest.fn() const Component = () => ( <motion.div onTap={() => press()}> <motion.div data-testid="child" /> </motion.div> ) const { getByTestId, rerender } = render(<Component />) rerender(<Component />) fireEvent.mouseDown(getByTestId("child")) fireEvent.mouseUp(getByTestId("child")) expect(press).toBeCalledTimes(1) }) test("press event listeners fire if triggered by child and released on bound element", () => { const press = jest.fn() const Component = () => ( <motion.div onTap={() => press()}> <motion.div data-testid="child" /> </motion.div> ) const { container, getByTestId, rerender } = render(<Component />) rerender(<Component />) fireEvent.mouseDown(getByTestId("child")) fireEvent.mouseUp(container.firstChild as Element) expect(press).toBeCalledTimes(1) }) test("press event listeners fire if triggered by bound element and released on child", () => { const press = jest.fn() const Component = () => ( <motion.div onTap={() => press()}> <motion.div data-testid="child" /> </motion.div> ) const { container, getByTestId, rerender } = render(<Component />) rerender(<Component />) fireEvent.mouseDown(container.firstChild as Element) fireEvent.mouseUp(getByTestId("child")) expect(press).toBeCalledTimes(1) }) test("press cancel fires if press released outside element", () => { const pressCancel = jest.fn() const Component = () => ( <motion.div> <motion.div onTapCancel={() => pressCancel()} data-testid="child" /> </motion.div> ) const { container, getByTestId, rerender } = render(<Component />) rerender(<Component />) fireEvent.mouseDown(getByTestId("child")) fireEvent.mouseUp(container.firstChild as Element) expect(pressCancel).toBeCalledTimes(1) }) test("press event listeners doesn't fire if parent is being dragged", async () => { const press = jest.fn() const Component = () => ( <MockDrag> <motion.div drag> <motion.div data-testid="pressTarget" onTap={() => press()} /> </motion.div> </MockDrag> ) const { rerender, getByTestId } = render(<Component />) rerender(<Component />) const pointer = await drag(getByTestId("pressTarget")).to(1, 1) await pointer.to(10, 10) pointer.end() expect(press).toBeCalledTimes(0) }) test("press event listeners do fire if parent is being dragged only a little bit", async () => { const press = jest.fn() const Component = () => ( <MockDrag> <motion.div drag> <motion.div data-testid="pressTarget" onTap={() => press()} /> </motion.div> </MockDrag> ) const { rerender, getByTestId } = render(<Component />) rerender(<Component />) const pointer = await drag(getByTestId("pressTarget")).to(0.5, 0.5) pointer.end() expect(press).toBeCalledTimes(1) }) test("press event listeners unset", () => { const press = jest.fn() const Component = () => <motion.div onTap={() => press()} /> const { container, rerender } = render(<Component />) rerender(<Component />) rerender(<Component />) fireEvent.mouseDown(container.firstChild as Element) fireEvent.mouseUp(container.firstChild as Element) rerender(<Component />) rerender(<Component />) fireEvent.mouseDown(container.firstChild as Element) fireEvent.mouseUp(container.firstChild as Element) fireEvent.mouseDown(container.firstChild as Element) fireEvent.mouseUp(container.firstChild as Element) expect(press).toBeCalledTimes(3) }) test("press gesture variant applies and unapplies", () => { const promise = new Promise((resolve) => { const opacityHistory: number[] = [] const opacity = motionValue(0.5) const logOpacity = () => opacityHistory.push(opacity.get()) const Component = () => ( <motion.div initial={{ opacity: 0.5 }} transition={{ type: false }} whileTap={{ opacity: 1 }} style={{ opacity }} /> ) const { container } = render(<Component />) logOpacity() // 0.5 // Trigger mouse down mouseDown(container.firstChild as Element) logOpacity() // 1 // Trigger mouse up mouseUp(container.firstChild as Element) logOpacity() // 0.5 resolve(opacityHistory) }) return expect(promise).resolves.toEqual([0.5, 1, 0.5]) }) test("press gesture variant unapplies children", () => { const promise = new Promise((resolve) => { const opacityHistory: number[] = [] const opacity = motionValue(0.5) const logOpacity = () => opacityHistory.push(opacity.get()) const Component = () => ( <motion.div whileTap="pressed"> <motion.div data-testid="child" variants={{ pressed: { opacity: 1 } }} style={{ opacity }} transition={{ type: false }} /> </motion.div> ) const { getByTestId } = render(<Component />) logOpacity() // 0.5 // Trigger mouse down mouseDown(getByTestId("child") as Element) logOpacity() // 1 // Trigger mouse up mouseUp(getByTestId("child") as Element) logOpacity() // 0.5 resolve(opacityHistory) }) return expect(promise).resolves.toEqual([0.5, 1, 0.5]) }) /** * TODO: We want the behaviour that we can override individual componnets with their * own whileX props to apply gesture behaviour just on that component. * * We want to add it in a way that maintains propagation of `animate`. */ // test.skip("press gesture variants - children can override with own variant", () => { // const promise = new Promise(resolve => { // const opacityHistory: number[] = [] // const opacity = motionValue(0.5) // const logOpacity = () => opacityHistory.push(opacity.get()) // const Component = () => ( // <motion.div whileTap="pressed"> // <motion.div // data-testid="child" // variants={{ // pressed: { opacity: 1 }, // childPressed: { opacity: 0.1 }, // }} // style={{ opacity }} // transition={{ type: false }} // whileTap="childPressed" // /> // </motion.div> // ) // const { getByTestId, rerender } = render(<Component />) // rerender(<Component />) // logOpacity() // 0.5 // // Trigger mouse down // fireEvent.mouseDown(getByTestId("child") as Element) // logOpacity() // 1 // // Trigger mouse up // fireEvent.mouseUp(getByTestId("child") as Element) // logOpacity() // 0.5 // resolve(opacityHistory) // }) // return expect(promise).resolves.toEqual([0.5, 0.1, 0.5]) // }) test("press gesture variant applies and unapplies with whileHover", () => { const promise = new Promise((resolve) => { const opacityHistory: number[] = [] const opacity = motionValue(0.5) const logOpacity = () => opacityHistory.push(opacity.get()) const Component = () => ( <motion.div initial={{ opacity: 0.5 }} transition={{ type: false }} whileHover={{ opacity: 0.75 }} whileTap={{ opacity: 1 }} style={{ opacity }} /> ) const { container, rerender } = render(<Component />) rerender(<Component />) logOpacity() // 0.5 // Trigger hover mouseEnter(container.firstChild as Element) logOpacity() // 0.75 // Trigger mouse down fireEvent.mouseDown(container.firstChild as Element) logOpacity() // 1 // Trigger mouse up fireEvent.mouseUp(container.firstChild as Element) logOpacity() // 0.75 // Trigger hover end mouseLeave(container.firstChild as Element) logOpacity() // Trigger hover mouseEnter(container.firstChild as Element) logOpacity() // Trigger mouse down fireEvent.mouseDown(container.firstChild as Element) logOpacity() // Trigger hover end mouseLeave(container.firstChild as Element) logOpacity() // Trigger mouse up fireEvent.mouseUp(container.firstChild as Element) logOpacity() resolve(opacityHistory) }) return expect(promise).resolves.toEqual([ 0.5, 0.75, 1, 0.75, 0.5, 0.75, 1, 1, 0.5, ]) }) test("press gesture variant applies and unapplies as state changes", () => { const promise = new Promise((resolve) => { const opacityHistory: number[] = [] const opacity = motionValue(0.5) const logOpacity = () => opacityHistory.push(opacity.get()) const Component = ({ isActive }: { isActive: boolean }) => { return ( <motion.div initial={{ opacity: isActive ? 1 : 0.5 }} animate={{ opacity: isActive ? 1 : 0.5 }} whileHover={{ opacity: isActive ? 1 : 0.75 }} whileTap={{ opacity: 1 }} transition={{ type: false }} style={{ opacity }} /> ) } const { container, rerender } = render( <Component isActive={false} /> ) rerender(<Component isActive={false} />) logOpacity() // 0.5 // Trigger hover mouseEnter(container.firstChild as Element) logOpacity() // 0.75 // Trigger mouse down fireEvent.mouseDown(container.firstChild as Element) logOpacity() // 1 rerender(<Component isActive={true} />) rerender(<Component isActive={true} />) // Trigger mouse up fireEvent.mouseUp(container.firstChild as Element) logOpacity() // 1 // Trigger hover end mouseLeave(container.firstChild as Element) logOpacity() // 1 // Trigger hover mouseEnter(container.firstChild as Element) logOpacity() // 1 // Trigger mouse down fireEvent.mouseDown(container.firstChild as Element) logOpacity() // 1 // Trigger hover end mouseLeave(container.firstChild as Element) logOpacity() // 1 // Trigger mouse up fireEvent.mouseUp(container.firstChild as Element) logOpacity() // 1 resolve(opacityHistory) }) return expect(promise).resolves.toEqual([ 0.5, 0.75, 1, 1, 1, 1, 1, 1, 1, ]) }) })
the_stack
import { Configuration, configurationValue, } from "@atomist/automation-client/lib/configuration"; import { ConfigurationAware, HandlerContext, } from "@atomist/automation-client/lib/HandlerContext"; import { guid } from "@atomist/automation-client/lib/internal/util/string"; import { ProjectOperationCredentials } from "@atomist/automation-client/lib/operations/common/ProjectOperationCredentials"; import { RemoteRepoRef } from "@atomist/automation-client/lib/operations/common/RepoId"; import { logger } from "@atomist/automation-client/lib/util/logger"; import * as _ from "lodash"; import { AddressChannels, addressChannelsFor, } from "../../api/context/addressChannels"; import { ParameterPromptFactory } from "../../api/context/parameterPrompt"; import { NoPreferenceStore, PreferenceStore, PreferenceStoreFactory, } from "../../api/context/preferenceStore"; import { createSkillContext } from "../../api/context/skillContext"; import { StatefulPushListenerInvocation } from "../../api/dsl/goalContribution"; import { EnrichGoal } from "../../api/goal/enrichGoal"; import { Goal, GoalDefinition, GoalWithPrecondition, hasPreconditions, } from "../../api/goal/Goal"; import { Goals } from "../../api/goal/Goals"; import { getGoalDefinitionFrom, PlannedGoal, } from "../../api/goal/GoalWithFulfillment"; import { SdmGoalEvent } from "../../api/goal/SdmGoalEvent"; import { SdmGoalFulfillment, SdmGoalFulfillmentMethod, SdmGoalMessage, } from "../../api/goal/SdmGoalMessage"; import { GoalImplementationMapper, isGoalFulfillment, isGoalImplementation, isGoalSideEffect, } from "../../api/goal/support/GoalImplementationMapper"; import { GoalSetTag, TagGoalSet, } from "../../api/goal/tagGoalSet"; import { GoalsSetListener, GoalsSetListenerInvocation, } from "../../api/listener/GoalsSetListener"; import { PushListenerInvocation } from "../../api/listener/PushListener"; import { GoalSetter } from "../../api/mapping/GoalSetter"; import { ProjectLoader } from "../../spi/project/ProjectLoader"; import { RepoRefResolver } from "../../spi/repo-ref/RepoRefResolver"; import { PushFields, SdmGoalState, } from "../../typings/types"; import { minimalClone } from "./minimalClone"; import { constructGoalSet, constructSdmGoal, constructSdmGoalImplementation, storeGoal, storeGoalSet, } from "./storeGoals"; /** * Configuration for handling incoming pushes */ export interface ChooseAndSetGoalsRules { projectLoader: ProjectLoader; repoRefResolver: RepoRefResolver; goalsListeners: GoalsSetListener[]; goalSetter: GoalSetter; implementationMapping: GoalImplementationMapper; enrichGoal?: EnrichGoal; tagGoalSet?: TagGoalSet; preferencesFactory?: PreferenceStoreFactory; parameterPromptFactory?: ParameterPromptFactory<any>; } /** * Choose and set goals for this push * @param {ChooseAndSetGoalsRules} rules: configuration for handling incoming pushes * @param parameters details of incoming request * @return {Promise<Goals | undefined>} */ export async function chooseAndSetGoals(rules: ChooseAndSetGoalsRules, parameters: { context: HandlerContext, credentials: ProjectOperationCredentials, push: PushFields.Fragment, }): Promise<Goals | undefined> { const { projectLoader, goalsListeners, goalSetter, implementationMapping, repoRefResolver, preferencesFactory } = rules; const { context, credentials, push } = parameters; const enrichGoal = !!rules.enrichGoal ? rules.enrichGoal : async g => g; const tagGoalSet = !!rules.tagGoalSet ? rules.tagGoalSet : async () => []; const id = repoRefResolver.repoRefFromPush(push); const addressChannels = addressChannelsFor(push.repo, context); const preferences = !!preferencesFactory ? preferencesFactory(parameters.context) : NoPreferenceStore; const configuration = (context as any as ConfigurationAware).configuration; const goalSetId = guid(); const { determinedGoals, goalsToSave, tags } = await determineGoals( { projectLoader, repoRefResolver, goalSetter, implementationMapping, enrichGoal, tagGoalSet }, { credentials, id, context, push, addressChannels, preferences, goalSetId, configuration, }); if (goalsToSave.length > 0) { // First store the goals await Promise.all(goalsToSave.map(g => storeGoal(context, g))); // And then store the goalSet await storeGoalSet(context, constructGoalSet(context, goalSetId, determinedGoals.name, goalsToSave, tags, push)); } // Let GoalSetListeners know even if we determined no goals. // This is not an error const gsi: GoalsSetListenerInvocation = { id, context, credentials, addressChannels, configuration, preferences, goalSetId, goalSetName: determinedGoals ? determinedGoals.name : undefined, goalSet: determinedGoals, push, skill: createSkillContext(context), }; await Promise.all(goalsListeners.map(l => l(gsi))); return determinedGoals; } export async function determineGoals(rules: { projectLoader: ProjectLoader, repoRefResolver: RepoRefResolver, goalSetter: GoalSetter, implementationMapping: GoalImplementationMapper, enrichGoal: EnrichGoal, tagGoalSet?: TagGoalSet, }, circumstances: { credentials: ProjectOperationCredentials, id: RemoteRepoRef, context: HandlerContext, configuration: Configuration, push: PushFields.Fragment, addressChannels: AddressChannels, preferences?: PreferenceStore, goalSetId: string, }): Promise<{ determinedGoals: Goals | undefined, goalsToSave: SdmGoalMessage[], tags: GoalSetTag[], }> { const { enrichGoal, projectLoader, repoRefResolver, goalSetter, implementationMapping, tagGoalSet } = rules; const { credentials, id, context, push, addressChannels, goalSetId, preferences, configuration } = circumstances; return projectLoader.doWithProject({ credentials, id, context, readOnly: true, cloneOptions: minimalClone(push, { detachHead: true }), }, async project => { const pli: StatefulPushListenerInvocation = { project, credentials, id, push, context, addressChannels, configuration, preferences: preferences || NoPreferenceStore, facts: {}, skill: createSkillContext(context), }; const determinedGoals = await chooseGoalsForPushOnProject({ goalSetter }, pli); if (!determinedGoals) { return { determinedGoals: undefined, goalsToSave: [], tags: [] }; } const goalsToSave = await sdmGoalsFromGoals( implementationMapping, push, repoRefResolver, pli, determinedGoals, goalSetId); // Enrich all goals before they get saved await Promise.all(goalsToSave.map(async g1 => enrichGoal(g1, pli))); // Optain tags for the goal set let tags: GoalSetTag[] = []; if (!!tagGoalSet) { tags = (await tagGoalSet(goalsToSave, pli)) || []; } return { determinedGoals, goalsToSave, tags }; }); } async function sdmGoalsFromGoals(implementationMapping: GoalImplementationMapper, push: PushFields.Fragment, repoRefResolver: RepoRefResolver, pli: PushListenerInvocation, determinedGoals: Goals, goalSetId: string): Promise<SdmGoalMessage[]> { return Promise.all(determinedGoals.goals.map(async g => { const ge = constructSdmGoal(pli.context, { goalSet: determinedGoals.name, goalSetId, goal: g, state: (hasPreconditions(g) ? SdmGoalState.planned : (g.definition.preApprovalRequired ? SdmGoalState.waiting_for_pre_approval : SdmGoalState.requested)) as SdmGoalState, id: pli.id, providerId: repoRefResolver.providerIdFromPush(pli.push), fulfillment: await fulfillment({ implementationMapping }, g, pli), }); if (ge.state === SdmGoalState.requested) { const cbs = implementationMapping.findFulfillmentCallbackForGoal({ ...ge, push }) || []; let ng: SdmGoalEvent = { ...ge, push }; for (const cb of cbs) { ng = await cb.callback(ng, pli); } return { ...ge, data: ng.data, }; } else { return ge; } })); } async function fulfillment(rules: { implementationMapping: GoalImplementationMapper, }, g: Goal, inv: PushListenerInvocation): Promise<SdmGoalFulfillment> { const { implementationMapping } = rules; const plan = await implementationMapping.findFulfillmentByPush(g, inv); if (isGoalImplementation(plan)) { return constructSdmGoalImplementation(plan, inv.configuration.name); } else if (isGoalFulfillment(g.definition as any)) { const ff = (g.definition as any).fulfillment; return { method: SdmGoalFulfillmentMethod.SideEffect, name: ff.name, registration: ff.registration, }; } else if (isGoalSideEffect(plan)) { return { method: SdmGoalFulfillmentMethod.SideEffect, name: plan.sideEffectName, registration: plan.registration || configurationValue("name"), }; } else { return { method: SdmGoalFulfillmentMethod.Other, name: "unknown", registration: "unknown" }; } } async function chooseGoalsForPushOnProject(rules: { goalSetter: GoalSetter }, pi: PushListenerInvocation): Promise<Goals> { const { goalSetter } = rules; const { push, id } = pi; try { const determinedGoals: Goals = await goalSetter.mapping(pi); if (!determinedGoals) { logger.info("No goals set by push '%s' to '%s/%s/%s'", push.after.sha, id.owner, id.repo, push.branch); return determinedGoals; } else { const filteredGoals: Goal[] = []; const plannedGoals = await planGoals(determinedGoals, pi); plannedGoals.goals.forEach(g => { if ((g as any).dependsOn) { const preConditions = (g as any).dependsOn as Goal[]; if (preConditions) { const filteredPreConditions = preConditions.filter(pc => plannedGoals.goals.some(ag => ag.uniqueName === pc.uniqueName && ag.environment === pc.environment)); if (filteredPreConditions.length > 0) { filteredGoals.push(new GoalWithPrecondition(g.definition, ...filteredPreConditions)); } else { filteredGoals.push(new Goal(g.definition)); } } else { filteredGoals.push(g); } } else { filteredGoals.push(g); } }); logger.info("Goals for push '%s' on '%s/%s/%s' are '%s'", push.after.sha, id.owner, id.repo, push.branch, plannedGoals.name); return new Goals(plannedGoals.name, ...filteredGoals); } } catch (err) { logger.error("Error determining goals: %s", err); logger.error(err.stack); throw err; } } export async function planGoals(goals: Goals, pli: PushListenerInvocation): Promise<Goals> { const allGoals = [...goals.goals]; const names = []; for (const dg of goals.goals) { if (!!(dg as any).plan) { let planResult = await (dg as any).plan(pli, goals); if (!!planResult) { // Check if planResult is a PlannedGoal or PlannedGoals instance if (!_.some(planResult, v => !!v && !!v.goals)) { planResult = { "#": { goals: planResult } }; } const allNewGoals = []; const goalMapping = new Map<string, Goal[]>(); _.forEach(planResult, (planResultGoals, n) => { names.push(n.replace(/_/g, " ")); const plannedGoals: Array<PlannedGoal | PlannedGoal[]> = []; if (Array.isArray(planResultGoals.goals)) { plannedGoals.push(...planResultGoals.goals); } else { plannedGoals.push(planResultGoals.goals); } let previousGoals = []; const newGoals = []; plannedGoals.forEach(g => { if (Array.isArray(g)) { const gNewGoals = []; for (const gg of g) { const newGoal = createGoal( gg, dg, planResultGoals.dependsOn, allNewGoals.length + gNewGoals.length, previousGoals, goalMapping); gNewGoals.push(newGoal); } allNewGoals.push(...gNewGoals); newGoals.push(...gNewGoals); previousGoals = [...gNewGoals]; } else { const newGoal = createGoal( g, dg, planResultGoals.dependsOn, allNewGoals.length, previousGoals, goalMapping); allNewGoals.push(newGoal); newGoals.push(newGoal); previousGoals = [newGoal]; } }); goalMapping.set(n, newGoals); }); // Replace existing goal with new instances const ix = allGoals.findIndex(g => g.uniqueName === dg.uniqueName); allGoals.splice(ix, 1, ...allNewGoals); // Replace all preConditions that point back to the original goal with references to new goals allGoals.filter(hasPreconditions) .filter(g => (g.dependsOn || []).some(gr => gr.uniqueName === dg.uniqueName)) .forEach(g => { _.remove(g.dependsOn, gr => gr.uniqueName === dg.uniqueName); g.dependsOn.push(...allNewGoals); }); } } } return new Goals(goals.name, ...allGoals); } function createGoal(g: PlannedGoal, dg: Goal, preConditions: string | string[], plannedGoalsCounter: number, previousGoals: Goal[], goalMapping: Map<string, Goal[]>): Goal { const uniqueName = `${dg.uniqueName}#sdm:${plannedGoalsCounter}`; const definition: GoalDefinition & { parameters: PlannedGoal["parameters"], fulfillment: PlannedGoal["fulfillment"] } = _.merge( {}, dg.definition, getGoalDefinitionFrom(g.details, uniqueName)) as any; definition.uniqueName = uniqueName; definition.parameters = g.parameters; definition.fulfillment = g.fulfillment; const dependsOn = []; if (hasPreconditions(dg)) { dependsOn.push(...dg.dependsOn); } if (!!previousGoals) { dependsOn.push(...previousGoals); } if (!!preConditions) { if (Array.isArray(preConditions)) { dependsOn.push(..._.flatten(preConditions.map(d => goalMapping.get(d)).filter(d => !!d))); } else { dependsOn.push(...goalMapping.get(preConditions)); } } return new GoalWithPrecondition(definition, ..._.uniqBy(dependsOn.filter(d => !!d), "uniqueName")); }
the_stack
import fs from "fs"; import { assert } from "@fluidframework/common-utils"; import { IDocumentService, } from "@fluidframework/driver-definitions"; import { IClient, ISequencedDocumentMessage, MessageType, ScopeType, } from "@fluidframework/protocol-definitions"; import { printMessageStats } from "./fluidAnalyzeMessages"; import { connectToWebSocket, dumpMessages, dumpMessageStats, overWrite, paramActualFormatting, messageTypeFilter, } from "./fluidFetchArgs"; function filenameFromIndex(index: number): string { return index === 0 ? "" : index.toString(); // support old tools... } let firstAvailableDelta = 1; async function* loadAllSequencedMessages( documentService?: IDocumentService, dir?: string, files?: string[]) { let lastSeq = 0; // flag for mismatch between last sequence number read and new one to be read let seqNumMismatch = false; // If we have local save, read ops from there first if (files !== undefined) { for (let i = 0; i < files.length; i++) { const file = filenameFromIndex(i); try { console.log(`reading messages${file}.json`); const fileContent = fs.readFileSync(`${dir}/messages${file}.json`, { encoding: "utf-8" }); const messages: ISequencedDocumentMessage[] = JSON.parse(fileContent); // check if there is mismatch seqNumMismatch = messages[0].sequenceNumber !== lastSeq + 1; assert(!seqNumMismatch, 0x1b9 /* "Unexpected value for sequence number of first message in file" */); lastSeq = messages[messages.length - 1].sequenceNumber; yield messages; } catch (e) { if (seqNumMismatch) { if (overWrite) { // with overWrite option on, we will delete all exisintg message.json files for (let index = 0; index < files.length; index++) { const name = filenameFromIndex(index); fs.unlinkSync(`${dir}/messages${name}.json`); } break; } // prompt user to back up and delete existing files console.error("There are deleted ops in the document being requested," + " please back up the existing messages.json file and delete it from its directory." + " Then try fetch tool again."); console.error(e); return; } else { console.error(`Error reading / parsing messages from ${files}`); console.error(e); return; } } } if (lastSeq !== 0) { console.log(`Read ${lastSeq} ops from local cache`); } } if (!documentService) { return; } const deltaStorage = await documentService.connectToDeltaStorage(); let timeStart = Date.now(); let requests = 0; let opsStorage = 0; // reading only 1 op to test if there is mismatch const teststream = deltaStorage.fetchMessages( lastSeq + 1, lastSeq + 2); let statusCode; let innerMostErrorCode; let response; try { await teststream.read(); } catch (error) { statusCode = error.getTelemetryProperties().statusCode; innerMostErrorCode = error.getTelemetryProperties().innerMostErrorCode; // if there is gap between ops, catch the error and check it is the error we need if (statusCode !== 410 || innerMostErrorCode !== "fluidDeltaDataNotAvailable") { throw error; } // get firstAvailableDelta from the error response, and set current sequence number to that response = JSON.parse(error.getTelemetryProperties().response); firstAvailableDelta = response.error.firstAvailableDelta; lastSeq = firstAvailableDelta - 1; } // continue reading rest of the ops const stream = deltaStorage.fetchMessages( lastSeq + 1, // inclusive left undefined, // to ); while (true) { const result = await stream.read(); if (result.done) { break; } requests++; const messages = result.value; // Empty buckets should never be returned assert(messages.length !== 0, 0x1ba /* "should not return empty buckets" */); // console.log(`Loaded ops at ${messages[0].sequenceNumber}`); // This parsing of message contents happens in delta manager. But when we analyze messages // for message stats, we skip that path. So parsing of json contents needs to happen here. for (const message of messages) { if (typeof message.contents === "string" && message.contents !== "" && message.type !== MessageType.ClientLeave ) { message.contents = JSON.parse(message.contents); } } opsStorage += messages.length; lastSeq = messages[messages.length - 1].sequenceNumber; yield messages; } // eslint-disable-next-line max-len console.log(`\n${Math.floor((Date.now() - timeStart) / 1000)} seconds to retrieve ${opsStorage} ops in ${requests} requests`); if (connectToWebSocket) { let logMsg = ""; const client: IClient = { mode: "write", permission: [], scopes: [ScopeType.DocRead, ScopeType.DocWrite, ScopeType.SummaryWrite], details: { capabilities: { interactive: true }, }, user: { id: "blah" }, }; console.log("Retrieving messages from web socket"); timeStart = Date.now(); const deltaStream = await documentService.connectToDeltaStream(client); const initialMessages = deltaStream.initialMessages; deltaStream.close(); console.log(`${Math.floor((Date.now() - timeStart) / 1000)} seconds to connect to web socket`); if (initialMessages) { const lastSequenceNumber = lastSeq; const filtered = initialMessages.filter((a) => a.sequenceNumber > lastSequenceNumber); const sorted = filtered.sort((a, b) => a.sequenceNumber - b.sequenceNumber); lastSeq = sorted[sorted.length - 1].sequenceNumber; // eslint-disable-next-line max-len logMsg = ` (${opsStorage} delta storage, ${initialMessages.length} initial ws messages, ${initialMessages.length - sorted.length} dup)`; yield sorted; } console.log(`${lastSeq} total messages${logMsg}`); } } async function* saveOps( gen, // AsyncGenerator<ISequencedDocumentMessage[]>, dir: string, files: string[]) { // Split into 100K ops const chunk = 100 * 1000; let sequencedMessages: ISequencedDocumentMessage[] = []; // Figure out first file we want to write to let index = 0; let curr: number = 1; if (files.length !== 0) { index = files.length - 1; const name = filenameFromIndex(index); const fileContent = fs.readFileSync(`${dir}/messages${name}.json`, { encoding: "utf-8" }); const messages: ISequencedDocumentMessage[] = JSON.parse(fileContent); curr = messages[0].sequenceNumber; } while (true) { const result: IteratorResult<ISequencedDocumentMessage[]> = await gen.next(); if (files.length === 0) { curr = firstAvailableDelta; } if (!result.done) { let messages = result.value; yield messages; if (messages[messages.length - 1].sequenceNumber < curr) { // Nothing interesting. continue; } if (messages[0].sequenceNumber < curr) { messages = messages.filter((msg) => msg.sequenceNumber >= curr); } sequencedMessages = sequencedMessages.concat(messages); assert(sequencedMessages[0].sequenceNumber === curr, 0x1bb /* "Unexpected sequence number on first of messages to save" */); assert(sequencedMessages[sequencedMessages.length - 1].sequenceNumber === curr + sequencedMessages.length - 1, 0x1bc /* "Unexpected sequence number on last of messages to save" */); } // Time to write it out? while (sequencedMessages.length >= chunk || (result.done && sequencedMessages.length !== 0)) { const name = filenameFromIndex(index); const write = sequencedMessages.splice(0, chunk); console.log(`writing messages${name}.json`); fs.writeFileSync( `${dir}/messages${name}.json`, JSON.stringify(write, undefined, paramActualFormatting ? 0 : 2)); // increment curr by chunk curr += chunk; assert(sequencedMessages.length === 0 || sequencedMessages[0].sequenceNumber === curr, 0x1bd /* "Stopped writing at unexpected sequence number" */); index++; } if (result.done) { break; } } } export async function fluidFetchMessages(documentService?: IDocumentService, saveDir?: string) { const messageStats = dumpMessageStats || dumpMessages; if (!messageStats && (saveDir === undefined || documentService === undefined)) { return; } const files = !saveDir ? undefined : fs.readdirSync(saveDir) .filter((file) => { if (!file.startsWith("messages")) { return false; } return true; }) .sort((a, b) => a.localeCompare(b)); let generator = loadAllSequencedMessages(documentService, saveDir, files); if (saveDir && files !== undefined && documentService) { generator = saveOps(generator, saveDir, files); } if (messageStats) { return printMessageStats( generator, dumpMessageStats, dumpMessages, messageTypeFilter); } else { let item; for await (item of generator) { } } }
the_stack
import { Component, Input, OnInit, OnChanges, OnDestroy, SimpleChange, Output, EventEmitter, ViewChildren, QueryList, Type, ViewChild, ElementRef, } from '@angular/core'; import { ModalOptions } from '@ionic/core'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreDynamicComponent } from '@components/dynamic-component/dynamic-component'; import { CoreCourseAnyCourseData } from '@features/courses/services/courses'; import { CoreCourse, CoreCourseProvider, } from '@features/course/services/course'; import { CoreCourseHelper, CoreCourseModule, CoreCourseModuleCompletionData, CoreCourseSection, CoreCourseSectionWithStatus, } from '@features/course/services/course-helper'; import { CoreCourseFormatDelegate } from '@features/course/services/format-delegate'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { IonContent, IonRefresher } from '@ionic/angular'; import { CoreUtils } from '@services/utils/utils'; import { CoreCourseModulePrefetchDelegate } from '@features/course/services/module-prefetch-delegate'; import { CoreBlockCourseBlocksComponent } from '@features/block/components/course-blocks/course-blocks'; import { CoreCourseSectionSelectorComponent } from '../section-selector/section-selector'; /** * Component to display course contents using a certain format. If the format isn't found, use default one. * * The inputs of this component will be shared with the course format components. Please use CoreCourseFormatDelegate * to register your handler for course formats. * * Example usage: * * <core-course-format [course]="course" [sections]="sections" (completionChanged)="onCompletionChange()"></core-course-format> */ @Component({ selector: 'core-course-format', templateUrl: 'core-course-format.html', styleUrls: ['format.scss'], }) export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { static readonly LOAD_MORE_ACTIVITIES = 20; // How many activities should load each time showMoreActivities is called. @Input() course?: CoreCourseAnyCourseData; // The course to render. @Input() sections?: CoreCourseSectionWithStatus[]; // List of course sections. The status will be calculated in this component. @Input() downloadEnabled?: boolean; // Whether the download of sections and modules is enabled. @Input() initialSectionId?: number; // The section to load first (by ID). @Input() initialSectionNumber?: number; // The section to load first (by number). @Input() moduleId?: number; // The module ID to scroll to. Must be inside the initial selected section. @Output() completionChanged = new EventEmitter<CoreCourseModuleCompletionData>(); // Notify when any module completion changes. @ViewChildren(CoreDynamicComponent) dynamicComponents?: QueryList<CoreDynamicComponent>; @ViewChild(CoreBlockCourseBlocksComponent) courseBlocksComponent?: CoreBlockCourseBlocksComponent; // All the possible component classes. courseFormatComponent?: Type<unknown>; courseSummaryComponent?: Type<unknown>; sectionSelectorComponent?: Type<unknown>; singleSectionComponent?: Type<unknown>; allSectionsComponent?: Type<unknown>; canLoadMore = false; showSectionId = 0; data: Record<string, unknown> = {}; // Data to pass to the components. displaySectionSelector?: boolean; displayBlocks?: boolean; selectedSection?: CoreCourseSection; previousSection?: CoreCourseSection; nextSection?: CoreCourseSection; allSectionsId: number = CoreCourseProvider.ALL_SECTIONS_ID; stealthModulesSectionId: number = CoreCourseProvider.STEALTH_MODULES_SECTION_ID; loaded = false; hasSeveralSections?: boolean; imageThumb?: string; progress?: number; sectionSelectorModalOptions: ModalOptions = { component: CoreCourseSectionSelectorComponent, componentProps: {}, }; protected sectionStatusObserver?: CoreEventObserver; protected selectTabObserver?: CoreEventObserver; protected lastCourseFormat?: string; protected sectionSelectorExpanded = false; constructor( protected content: IonContent, protected elementRef: ElementRef, ) { // Pass this instance to all components so they can use its methods and properties. this.data.coreCourseFormatComponent = this; } /** * Component being initialized. */ ngOnInit(): void { // Listen for section status changes. this.sectionStatusObserver = CoreEvents.on( CoreEvents.SECTION_STATUS_CHANGED, async (data) => { if (!this.downloadEnabled || !this.sections?.length || !data.sectionId || data.courseId != this.course?.id) { return; } // Check if the affected section is being downloaded. // If so, we don't update section status because it'll already be updated when the download finishes. const downloadId = CoreCourseHelper.getSectionDownloadId({ id: data.sectionId }); if (CoreCourseModulePrefetchDelegate.isBeingDownloaded(downloadId)) { return; } // Get the affected section. const section = this.sections.find(section => section.id == data.sectionId); if (!section) { return; } // Recalculate the status. await CoreCourseHelper.calculateSectionStatus(section, this.course.id, false); if (section.isDownloading && !CoreCourseModulePrefetchDelegate.isBeingDownloaded(downloadId)) { // All the modules are now downloading, set a download all promise. this.prefetch(section); } }, CoreSites.getCurrentSiteId(), ); // Listen for select course tab events to select the right section if needed. this.selectTabObserver = CoreEvents.on(CoreEvents.SELECT_COURSE_TAB, (data) => { if (data.name) { return; } let section: CoreCourseSection | undefined; if (typeof data.sectionId != 'undefined' && this.sections) { section = this.sections.find((section) => section.id == data.sectionId); } else if (typeof data.sectionNumber != 'undefined' && this.sections) { section = this.sections.find((section) => section.section == data.sectionNumber); } if (section) { this.sectionChanged(section); } }); } /** * Detect changes on input properties. */ ngOnChanges(changes: { [name: string]: SimpleChange }): void { this.setInputData(); this.sectionSelectorModalOptions.componentProps!.course = this.course; this.sectionSelectorModalOptions.componentProps!.sections = this.sections; if (changes.course && this.course) { // Course has changed, try to get the components. this.getComponents(); this.displaySectionSelector = CoreCourseFormatDelegate.displaySectionSelector(this.course); this.displayBlocks = CoreCourseFormatDelegate.displayBlocks(this.course); this.updateProgress(); if ('overviewfiles' in this.course) { this.imageThumb = this.course.overviewfiles?.[0]?.fileurl; } } if (changes.sections && this.sections) { this.sectionSelectorModalOptions.componentProps!.sections = this.sections; this.treatSections(this.sections); } if (this.downloadEnabled && (changes.downloadEnabled || changes.sections)) { this.calculateSectionsStatus(false); } } /** * Set the input data for components. */ protected setInputData(): void { this.data.course = this.course; this.data.sections = this.sections; this.data.initialSectionId = this.initialSectionId; this.data.initialSectionNumber = this.initialSectionNumber; this.data.downloadEnabled = this.downloadEnabled; this.data.moduleId = this.moduleId; this.data.completionChanged = this.completionChanged; } /** * Get the components classes. */ protected async getComponents(): Promise<void> { if (!this.course || this.course.format == this.lastCourseFormat) { return; } // Format has changed or it's the first time, load all the components. this.lastCourseFormat = this.course.format; await Promise.all([ this.loadCourseFormatComponent(), this.loadCourseSummaryComponent(), this.loadSectionSelectorComponent(), this.loadSingleSectionComponent(), this.loadAllSectionsComponent(), ]); } /** * Load course format component. * * @return Promise resolved when done. */ protected async loadCourseFormatComponent(): Promise<void> { this.courseFormatComponent = await CoreCourseFormatDelegate.getCourseFormatComponent(this.course!); } /** * Load course summary component. * * @return Promise resolved when done. */ protected async loadCourseSummaryComponent(): Promise<void> { this.courseSummaryComponent = await CoreCourseFormatDelegate.getCourseSummaryComponent(this.course!); } /** * Load section selector component. * * @return Promise resolved when done. */ protected async loadSectionSelectorComponent(): Promise<void> { this.sectionSelectorComponent = await CoreCourseFormatDelegate.getSectionSelectorComponent(this.course!); } /** * Load single section component. * * @return Promise resolved when done. */ protected async loadSingleSectionComponent(): Promise<void> { this.singleSectionComponent = await CoreCourseFormatDelegate.getSingleSectionComponent(this.course!); } /** * Load all sections component. * * @return Promise resolved when done. */ protected async loadAllSectionsComponent(): Promise<void> { this.allSectionsComponent = await CoreCourseFormatDelegate.getAllSectionsComponent(this.course!); } /** * Treat received sections. * * @param sections Sections to treat. * @return Promise resolved when done. */ protected async treatSections(sections: CoreCourseSection[]): Promise<void> { const hasAllSections = sections[0].id == CoreCourseProvider.ALL_SECTIONS_ID; this.hasSeveralSections = sections.length > 2 || (sections.length == 2 && !hasAllSections); if (this.selectedSection) { // We have a selected section, but the list has changed. Search the section in the list. let newSection = sections.find(section => this.compareSections(section, this.selectedSection!)); if (!newSection) { // Section not found, calculate which one to use. newSection = await CoreCourseFormatDelegate.getCurrentSection(this.course!, sections); } this.sectionChanged(newSection); return; } // There is no selected section yet, calculate which one to load. if (!this.hasSeveralSections) { // Always load "All sections" to display the section title. If it isn't there just load the section. this.loaded = true; this.sectionChanged(sections[0]); } else if (this.initialSectionId || this.initialSectionNumber) { // We have an input indicating the section ID to load. Search the section. const section = sections.find((section) => section.id == this.initialSectionId || (section.section && section.section == this.initialSectionNumber)); // Don't load the section if it cannot be viewed by the user. if (section && this.canViewSection(section)) { this.loaded = true; this.sectionChanged(section); } } if (!this.loaded) { // No section specified, not found or not visible, get current section. const section = await CoreCourseFormatDelegate.getCurrentSection(this.course!, sections); this.loaded = true; this.sectionChanged(section); } return; } /** * Display the section selector modal. */ async showSectionSelector(): Promise<void> { if (this.sectionSelectorExpanded) { return; } this.sectionSelectorExpanded = true; const data = await CoreDomUtils.openModal<CoreCourseSection>(this.sectionSelectorModalOptions); this.sectionSelectorExpanded = false; if (data) { this.sectionChanged(data); } } /** * Function called when selected section changes. * * @param newSection The new selected section. */ sectionChanged(newSection: CoreCourseSection): void { const previousValue = this.selectedSection; this.selectedSection = newSection; this.sectionSelectorModalOptions.componentProps!.selected = this.selectedSection; this.data.section = this.selectedSection; if (newSection.id != this.allSectionsId) { // Select next and previous sections to show the arrows. const i = this.sections!.findIndex((value) => this.compareSections(value, this.selectedSection!)); let j: number; for (j = i - 1; j >= 1; j--) { if (this.canViewSection(this.sections![j])) { break; } } this.previousSection = j >= 1 ? this.sections![j] : undefined; for (j = i + 1; j < this.sections!.length; j++) { if (this.canViewSection(this.sections![j])) { break; } } this.nextSection = j < this.sections!.length ? this.sections![j] : undefined; } else { this.previousSection = undefined; this.nextSection = undefined; this.canLoadMore = false; this.showSectionId = 0; this.showMoreActivities(); if (this.downloadEnabled) { this.calculateSectionsStatus(false); } } if (this.moduleId && typeof previousValue == 'undefined') { setTimeout(() => { CoreDomUtils.scrollToElementBySelector( this.elementRef.nativeElement, this.content, '#core-course-module-' + this.moduleId, ); }, 200); } else { this.content.scrollToTop(0); } if (!previousValue || previousValue.id != newSection.id) { // First load or section changed, add log in Moodle. CoreUtils.ignoreErrors( CoreCourse.logView(this.course!.id, newSection.section, undefined, this.course!.fullname), ); } this.invalidateSectionButtons(); } /** * Compare if two sections are equal. * * @param section1 First section. * @param section2 Second section. * @return Whether they're equal. */ compareSections(section1: CoreCourseSection, section2: CoreCourseSection): boolean { return section1 && section2 ? section1.id === section2.id : section1 === section2; } /** * Calculate the status of sections. * * @param refresh If refresh or not. */ protected calculateSectionsStatus(refresh?: boolean): void { if (!this.sections || !this.course) { return; } CoreUtils.ignoreErrors(CoreCourseHelper.calculateSectionsStatus(this.sections, this.course.id, refresh)); } /** * Confirm and prefetch a section. If the section is "all sections", prefetch all the sections. * * @param section Section to download. * @param refresh Refresh clicked (not used). */ async prefetch(section: CoreCourseSectionWithStatus): Promise<void> { section.isCalculating = true; try { await CoreCourseHelper.confirmDownloadSizeSection(this.course!.id, section, this.sections); await this.prefetchSection(section, true); } catch (error) { // User cancelled or there was an error calculating the size. if (error) { CoreDomUtils.showErrorModal(error); } } finally { section.isCalculating = false; } } /** * Prefetch a section. * * @param section The section to download. * @param manual Whether the prefetch was started manually or it was automatically started because all modules * are being downloaded. */ protected async prefetchSection(section: CoreCourseSectionWithStatus, manual?: boolean): Promise<void> { try { await CoreCourseHelper.prefetchSection(section, this.course!.id, this.sections); } catch (error) { // Don't show error message if it's an automatic download. if (!manual) { return; } CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingsection', true); } } /** * Refresh the data. * * @param refresher Refresher. * @param done Function to call when done. * @param afterCompletionChange Whether the refresh is due to a completion change. * @return Promise resolved when done. */ async doRefresh(refresher?: IonRefresher, done?: () => void, afterCompletionChange?: boolean): Promise<void> { const promises = this.dynamicComponents?.map(async (component) => { await component.callComponentFunction('doRefresh', [refresher, done, afterCompletionChange]); }) || []; if (this.courseBlocksComponent) { promises.push(this.courseBlocksComponent.doRefresh()); } await Promise.all(promises); refresher?.complete(); done?.(); } /** * Invalidate section buttons so that they are rendered again. This is necessary in order to update * some attributes that are not reactive, for example aria-label. * * @see https://github.com/ionic-team/ionic-framework/issues/21534 */ protected async invalidateSectionButtons(): Promise<void> { const previousSection = this.previousSection; const nextSection = this.nextSection; this.previousSection = undefined; this.nextSection = undefined; await CoreUtils.nextTick(); this.previousSection = previousSection; this.nextSection = nextSection; } /** * Show more activities (only used when showing all the sections at the same time). * * @param infiniteComplete Infinite scroll complete function. Only used from core-infinite-loading. */ showMoreActivities(infiniteComplete?: () => void): void { this.canLoadMore = false; const sections = this.sections || []; let modulesLoaded = 0; let i: number; for (i = this.showSectionId + 1; i < sections.length; i++) { if (!sections[i].hasContent || !sections[i].modules) { continue; } modulesLoaded += sections[i].modules.reduce((total, module) => module.visibleoncoursepage !== 0 ? total + 1 : total, 0); if (modulesLoaded >= CoreCourseFormatComponent.LOAD_MORE_ACTIVITIES) { break; } } this.showSectionId = i; this.canLoadMore = i < sections.length; if (this.canLoadMore) { // Check if any of the following sections have any content. let thereAreMore = false; for (i++; i < sections.length; i++) { if (sections[i].hasContent && sections[i].modules && sections[i].modules?.length > 0) { thereAreMore = true; break; } } this.canLoadMore = thereAreMore; } infiniteComplete && infiniteComplete(); } /** * Component destroyed. */ ngOnDestroy(): void { this.sectionStatusObserver && this.sectionStatusObserver.off(); this.selectTabObserver && this.selectTabObserver.off(); } /** * User entered the page that contains the component. */ ionViewDidEnter(): void { this.dynamicComponents?.forEach((component) => { component.callComponentFunction('ionViewDidEnter'); }); if (!this.downloadEnabled || !this.course || !this.sections) { return; } // The download status of a section might have been changed from within a module page. if (this.selectedSection && this.selectedSection.id !== CoreCourseProvider.ALL_SECTIONS_ID) { CoreCourseHelper.calculateSectionStatus(this.selectedSection, this.course.id, false, false); } else { CoreCourseHelper.calculateSectionsStatus(this.sections, this.course.id, false, false); } } /** * User left the page that contains the component. */ ionViewDidLeave(): void { this.dynamicComponents?.forEach((component) => { component.callComponentFunction('ionViewDidLeave'); }); } /** * Check whether a section can be viewed. * * @param section The section to check. * @return Whether the section can be viewed. */ canViewSection(section: CoreCourseSection): boolean { return section.uservisible !== false && !section.hiddenbynumsections && section.id != CoreCourseProvider.STEALTH_MODULES_SECTION_ID; } /** * The completion of any of the modules have changed. */ onCompletionChange(completionData: CoreCourseModuleCompletionData): void { // Emit a new event for other components. this.completionChanged.emit(completionData); if (completionData.valueused !== false || !this.course || !('progress' in this.course) || typeof this.course.progress != 'number') { return; } // If the completion value is not used, the page won't be reloaded, so update the progress bar. const completionModules = (<CoreCourseModule[]> []) .concat(...this.sections!.map((section) => section.modules)) .map((module) => module.completion && module.completion > 0 ? 1 : module.completion) .reduce((accumulator, currentValue) => (accumulator || 0) + (currentValue || 0), 0); const moduleProgressPercent = 100 / (completionModules || 1); // Use min/max here to avoid floating point rounding errors over/under-flowing the progress bar. if (completionData.state === CoreCourseProvider.COMPLETION_COMPLETE) { this.course.progress = Math.min(100, this.course.progress + moduleProgressPercent); } else { this.course.progress = Math.max(0, this.course.progress - moduleProgressPercent); } this.updateProgress(); } /** * Recalculate the download status of each section, in response to a module being downloaded. */ onModuleStatusChange(): void { if (!this.downloadEnabled || !this.sections || !this.course) { return; } CoreCourseHelper.calculateSectionsStatus(this.sections, this.course.id, false, false); } /** * Update course progress. */ protected updateProgress(): void { if ( !this.course || !('progress' in this.course) || typeof this.course.progress !== 'number' || this.course.progress < 0 || this.course.completionusertracked === false ) { this.progress = undefined; return; } this.progress = this.course.progress; } }
the_stack
module TDev.AST.Apps { export interface CordovaPlatformOptions { build: boolean; runs: string[]; } export interface CordovaOptions { email: string; website: string; domain: string; platforms: TDev.StringMap<CordovaPlatformOptions>; } export function cordovaDefaultOptions() : CordovaOptions { var opts = <CordovaOptions>{ email: "", website: "", domain: "", platforms: {} } Object.keys(cordovaPlatforms).forEach(p => { if (!!cordovaPlatforms[p].build) { opts.platforms[p] = <CordovaPlatformOptions>{ build: !!cordovaPlatforms[p].build, runs: cordovaPlatforms[p].runs || [p] } } }); return opts; } export interface DeploymentOptions { relId?: string; downloadLocalFilesFrom?: string; compileServer?: boolean; skipClient?: boolean; userId?: string; scriptId?: string; filePrefix?: string; baseUrl?: string; azureSite?: string; cordova?: CordovaOptions; runtimeFlags?: string; failOnError? : boolean; } export interface DeploymentFile { path: string; // either url or content is present url?: string; content?: string; sourceName?: string; kind?: string; isUnused?: boolean; } export interface JsonCordovaImage { src: string; width: number; height?: number; density?: string; } export interface JsonCordovaPlatform { build?: boolean; res?: string; runs?: string[]; icons: JsonCordovaImage[]; splash?: JsonCordovaImage[]; } export interface CordovaInstructions { email?: string; website?: string; domain?: string; plugins: string[]; platforms: TDev.StringMap<JsonCordovaPlatform>; runs: string[]; } export interface DeploymentInstructions { meta: any; files: DeploymentFile[]; packageResources?: PackageResource[]; cordova?: CordovaInstructions; error? : string; } export function getDeploymentInstructionsAsync(app:AST.App, options:DeploymentOptions) : Promise { var html:string = (<any>TDev).webappHtml; if (!options.userId) options.userId = "unknown" if (!options.filePrefix) options.filePrefix = "" var isCloud = options.compileServer && (options.skipClient || app.isCloud); var opts: CompilerOptions = { packaging: true, javascript: true, // always on for compiled web apps scriptId: options.scriptId, authorId: options.userId, scriptGuid: app.localGuid, azureSite: options.azureSite, } var setProp = (s:string, v:string) => { html = html.replace(s.replace(/{.*}/, ""), Util.fmt(s, v)) } html = html.replace("precompiled.js?a=", "precompiled.js") var instructions: AST.Apps.DeploymentInstructions = { meta: {}, files : [] }; if (!isCloud) { var head = Object.keys(app.imports.clientScripts).map(url => { if (/\.css$/i.test(url)) return Util.fmt('<link rel="stylesheet" href="{0:url}">', url); if (/\.js$/i.test(url)) return Util.fmt('<script type="text/javascript" src="{0:url}"></script>', url); }); html = html.replace("</head>", " " + head.join("\n ") + "\n</head>") } if (options.cordova) { html = html.replace("</head>", " <script src='cordova.js'></script>\n</head>") instructions.cordova = <CordovaInstructions>{ plugins: [], platforms: {}, runs: [] } } setProp("<title>{0:q}</title>", app.getName()) setProp('property="og:title" content="{0:q}"', app.getName()) //setProp('property="og:url" content="{0:q}"', wa.destinationAppUrl) // TODO og:image setProp('var userId = "{0:jq}"', options.userId) // TODO setProp('var userName = "{0:jq}"', "") setProp('var webAppName = "{0:jq}"', app.getName()) setProp('var webAppGuid = "{0:jq}"', app.localGuid) setProp('var runtimeFlags = "{0:jq}"', options.runtimeFlags || "") var theBase = Cloud.config.primaryCdnUrl + "/app/" + options.relId + "/c/"; AST.TypeChecker.tcApp(app) var compiled = AST.Compiler.getCompiledScript(app, opts) var errs = "" app.librariesAndThis().forEach(lib => { if (!lib.resolved) errs += "Unresolved library: " + lib.getName() + "\n" else lib.resolved.things.forEach(t => { if (t.hasErrors()) errs += "Errors in " + lib.getName() + "->" + t.getName() + "\n" }) }) if (errs) { instructions.error = errs if (options.failOnError) { ModalDialog.info(lf("compilation errors"), errs) return new PromiseInv() } } instructions.packageResources = compiled.packageResources; var clientCode = "" if (isCloud) { Util.assert(opts.javascript, "javascript should have been on"); clientCode = "var TDev; if (!TDev) TDev = {}; TDev.isWebserviceOnly = true;" } else { clientCode = compiled.getCompiledCode(); if (options.cordova) { Util.assert(opts.javascript, "javascript should have been on"); instructions.files.push({ path: options.filePrefix + "cordovaPlugins.json", content: JSON.stringify(compiled.imports.cordovaPlugins, null, 2) }); Object.keys(options.cordova.platforms).forEach(p => { if (options.cordova.platforms[p].build) { instructions.cordova.platforms[p] = cordovaPlatforms[p] options.cordova.platforms[p].runs.forEach(run => instructions.cordova.runs.push(run)); } }); instructions.cordova.plugins = Object.keys(compiled.imports.cordovaPlugins) .map(k => k + (!k || /^https?:\/\//.test(k) || /^\*?$/.test(compiled.imports.cordovaPlugins[k]) ? "" : "@" + compiled.imports.cordovaPlugins[k])); } compiled.packageResources.forEach(pr => { instructions.files.push({ path: options.filePrefix + pr.packageUrl.replace(/^\.\//, ""), url: HTML.proxyResource(pr.url), content: pr.content, kind: pr.kind, type: pr.type, sourceName: pr.sourceName, isUnused: pr.usageLevel === 0, }) // for sounds, cache multiple versions... if (pr.type == "sound") { var mp4 = HTML.patchWavToMp4Url(pr.url); if (pr.url != mp4) instructions.files.push({ path: options.filePrefix + pr.packageUrl.replace(/^\.\//, "") + ".m4a", url: mp4, kind: pr.kind, sourceName: pr.sourceName, isUnused: pr.usageLevel === 0, }) } }) if (app.getIconArtId()) { instructions.files.push({ path: options.filePrefix + 'art/icon', url: Cloud.artUrl(app.getIconArtId()), kind: "art", type: "picture", sourceName:"icon", isUnused: false, }) } if (app.splashArtId) { instructions.files.push({ path: options.filePrefix + 'art/splash', url: Cloud.artUrl(app.splashArtId), kind: "art", type: "picture", sourceName:"splash", isUnused: false, }) } } if (options.compileServer) { opts.packaging = false opts.cloud = true opts.javascript = true compiled = AST.Compiler.getCompiledScript(app, opts) var serverCode = compiled.getCompiledCode(); // update node-webkit/package.json as well compiled.imports.npmModules["faye-websocket"] = "0.8.1"; var pkgJson = { name: "td-" + app.getName().replace(/[^a-zA-Z0-9]/g, "-"), version: "0.0.0", private: true, dependencies: compiled.imports.npmModules } instructions.files.push({ path: "package.json", content: JSON.stringify(pkgJson, null, 2) }) instructions.files.push({ path: "script/compiled.js", content: serverCode, }) var pipPkgs = Object.keys(compiled.imports.pipPackages); if (pipPkgs.length > 0) { instructions.files.push({ path: "requirements.txt", content: pipPkgs.map(pkg => { var r = pkg; var v = compiled.imports.pipPackages[pkg] || ""; if (v != "*" && !/^(==|>=)/.test(v)) r += "==" + v; return r; }).join('\n') }) instructions.files.push({ path: "runtime.txt", content: "python-2.7" }); } } instructions.files.push({ path: options.filePrefix + "precompiled.js", content: clientCode, }) instructions.files.push({ path: options.filePrefix + "index.html", content: html, }) var baseUrl = options.baseUrl var addFileAsync = (fn:string, pref?:string) => { if (!pref) pref = options.filePrefix if (options.downloadLocalFilesFrom) { return Util.httpGetTextAsync(options.downloadLocalFilesFrom + fn).then(content => { instructions.files.push({ path: pref + fn, content: content }); }) } else { instructions.files.push({ path: pref + fn, url: theBase + fn }); return Promise.as() } } var lst = ["default.css", "browser.js", "runtime.js"].map(n => addFileAsync(n)) if (options.compileServer) lst.push(addFileAsync("noderuntime.js", "script/")); // this code path break cordova if (!options.cordova) { if (options.downloadLocalFilesFrom) { lst.push(addFileAsync("error.html")) lst.push(addFileAsync("browsers.html")) } else { // these 2 files are not stored in cdn, they are rewritten in the cloud [ "error", "browsers"].forEach(n => instructions.files.push({ path: options.filePrefix + n + ".html", url: Cloud.getServiceUrl() + "/app/" + n + ".html?releaseid=" + options.relId })) } } instructions.meta.isCloud = app.isCloud; return Promise.join(lst).then(() => instructions); } var densitySizes: StringMap<number> = { hdpi: 72, ldpi: 36, mdpi: 48, xhdpi: 96, xxhdpi: 144 }; var cordovaPlatforms: TDev.StringMap<JsonCordovaPlatform> = { "windows": { build: true, runs: ["windows -- --win", "windows --device -- --phone", "windows -- --phone"], res: "windows8", icons: [ { src: "res/windows8/logo.png", width: 150 }, { src: "res/windows8/smalllogo.png", width: 30 }, { src: "res/windows8/storelogo.png", width: 50 } ], splash: [ { src: "res/screen/windows8/splashscreen.png", width: 620, height: 300 }, ] }, "ios": { build: true, icons: [ //--iOS 8.0 + //--iPhone 6 Plus { src: "res/ios/icon-60@3x.png", width: 180 }, //--iOS 7.0 + -- > //--iPhone / iPod Touch-- > { src: "res/ios/icon-60.png", width: 60 }, { src: "res/ios/icon-60@2x.png", width: 120 }, // --iPad-- > { src: "res/ios/icon-76.png", width: 76 }, { src: "res/ios/icon-76@2x.png", width: 152 }, //--iOS 6.1 -- > //--Spotlight Icon-- > { src: "res/ios/icon-40.png", width: 40 }, { src: "res/ios/icon-40@2x.png", width: 80 }, // --iPhone / iPod Touch-- > { src: "res/ios/icon.png", width: 57 }, { src: "res/ios/icon@2x.png", width: 114 }, // --iPad-- > { src: "res/ios/icon-72.png", width: 72 }, { src: "res/ios/icon-72@2x.png", width: 144 }, // --iPhone Spotlight and Settings Icon { src: "res/ios/icon-small.png", width: 29 }, { src: "res/ios/icon-small@2x.png", width: 58 }, //--iPad Spotlight and Settings Icon { src: "res/ios/icon-50.png", width: 50 }, { src: "res/ios/icon-50@2x.png", width: 100 }, ], splash: [ { src: "res/screen/ios/Default~iphone.png", width: 320, height: 480 }, { src: "res/screen/ios/Default@2x~iphone.png", width: 640, height: 960 }, { src: "res/screen/ios/Default-Portrait~ipad.png", width: 768, height: 1024 }, { src: "res/screen/ios/Default-Portrait@2x~ipad.png", width: 1536, height: 2048 }, { src: "res/screen/ios/Default-Landscape~ipad.png", width: 1024, height: 768 }, { src: "res/screen/ios/Default-Landscape@2x~ipad.png", width: 2048, height: 1536 }, { src: "res/screen/ios/Default-568h@2x~iphone.png", width: 640, height: 1136 }, { src: "res/screen/ios/Default-667h.png", width: 750, height: 1334 }, { src: "res/screen/ios/Default-736h.png", width: 1242, height: 2208 }, { src: "res/screen/ios/Default-Landscape-736h.png", width: 2208, height: 1242 } ] }, "android": { build: true, icons: [ { src: "res/android/ldpi.png", density: "ldpi", width: densitySizes["ldpi"] }, { src: "res/android/mdpi.png", density: "mdpi", width: densitySizes["mdpi"] }, { src: "res/android/hdpi.png", density: "hdpi", width: densitySizes["hdpi"] }, { src: "res/android/xhdpi.png", density: "xhdpi", width: densitySizes["xhdpi"] } ], splash: [ { src:"res/screen/android/splash-land-hdpi.png", density:"land-hdpi", width: densitySizes["hdpi"] }, { src: "res/screen/android/splash-land-ldpi.png", density: "land-ldpi", width: densitySizes["ldpi"] }, { src: "res/screen/android/splash-land-mdpi.png", density: "land-mdpi", width: densitySizes["mdpi"] }, { src: "res/screen/android/splash-land-xhdpi.png", density: "land-xhdpi", width: densitySizes["xhdpi"] }, { src: "res/screen/android/splash-port-hdpi.png", density: "port-hdpi", width: densitySizes["hdpi"] }, { src: "res/screen/android/splash-port-ldpi.png", density: "port-ldpi", width: densitySizes["ldpi"] }, { src: "res/screen/android/splash-port-mdpi.png", density: "port-mdpi", width: densitySizes["mdpi"] }, { src: "res/screen/android/splash-port-xhdpi.png", density: "port-xhdpi", width: densitySizes["xhdpi"]} ] }, "amazon-fireos": { icons: [ { src: "res/android/ldpi.png", density: "ldpi", width: densitySizes["ldpi"] }, { src: "res/android/mdpi.png", density: "mdpi", width: densitySizes["mdpi"] }, { src: "res/android/hdpi.png", density: "hdpi", width: densitySizes["hdpi"] }, { src: "res/android/xhdpi.png", density: "xhdpi", width: densitySizes["xhdpi"] } ] }, "blackberry10": { res: "bb10", icons: [ { src: "res/bb10/icon-86.png", width:86 }, { src: "res/bb10/icon-150.png", width:150 }, ], }, "firefoxos": { res: "ff", icons: [ { src: "res/ff/logo.png", width: 60 } ] }, "tizen": { icons: [{ src: "res/tizen/icon-128.png", width: 128 }] }, } }
the_stack
import React from "react"; import { withTranslation, WithTranslation } from "react-i18next"; import classNames from "classnames"; import styled from "styled-components"; // @ts-ignore import { Decoration, getChangeKey, Hunk } from "react-diff-view"; import { ButtonGroup } from "../buttons"; import Tag from "../Tag"; import Icon from "../Icon"; import { Change, FileDiff, Hunk as HunkType } from "@scm-manager/ui-types"; import { ChangeEvent, DiffObjectProps } from "./DiffTypes"; import TokenizedDiffView from "./TokenizedDiffView"; import DiffButton from "./DiffButton"; import { MenuContext, OpenInFullscreenButton } from "@scm-manager/ui-components"; import DiffExpander, { ExpandableHunk } from "./DiffExpander"; import HunkExpandLink from "./HunkExpandLink"; import { Modal } from "../modals"; import ErrorNotification from "../ErrorNotification"; import HunkExpandDivider from "./HunkExpandDivider"; import { escapeWhitespace } from "./diffs"; const EMPTY_ANNOTATION_FACTORY = {}; type Props = DiffObjectProps & WithTranslation & { file: FileDiff; }; type Collapsible = { collapsed?: boolean; }; type State = Collapsible & { file: FileDiff; sideBySide?: boolean; diffExpander: DiffExpander; expansionError?: any; }; const DiffFilePanel = styled.div` /* remove bottom border for collapsed panels */ ${(props: Collapsible) => (props.collapsed ? "border-bottom: none;" : "")}; `; const FullWidthTitleHeader = styled.div` max-width: 100%; `; const MarginlessModalContent = styled.div` margin: -1.25rem; & .panel-block { flex-direction: column; align-items: stretch; } `; class DiffFile extends React.Component<Props, State> { static defaultProps: Partial<Props> = { defaultCollapse: false, markConflicts: true, }; constructor(props: Props) { super(props); this.state = { collapsed: this.defaultCollapse(), sideBySide: props.sideBySide, diffExpander: new DiffExpander(props.file), file: props.file, }; } componentDidUpdate(prevProps: Readonly<Props>) { if (!this.props.isCollapsed && this.props.defaultCollapse !== prevProps.defaultCollapse) { this.setState({ collapsed: this.defaultCollapse(), }); } } defaultCollapse: () => boolean = () => { const { defaultCollapse, file } = this.props; if (typeof defaultCollapse === "boolean") { return defaultCollapse; } else if (typeof defaultCollapse === "function") { return defaultCollapse(file.oldPath, file.newPath); } else { return false; } }; toggleCollapse = () => { const { onCollapseStateChange } = this.props; const { file } = this.state; if (this.hasContent(file)) { if (onCollapseStateChange) { onCollapseStateChange(file); } else { this.setState((state) => ({ collapsed: !state.collapsed, })); } } }; toggleSideBySide = (callback: () => void) => { this.setState( (state) => ({ sideBySide: !state.sideBySide, }), () => callback() ); }; setCollapse = (collapsed: boolean) => { const { onCollapseStateChange } = this.props; if (onCollapseStateChange) { onCollapseStateChange(this.state.file, collapsed); } else { this.setState({ collapsed, }); } }; createHunkHeader = (expandableHunk: ExpandableHunk) => { if (expandableHunk.maxExpandHeadRange > 0) { if (expandableHunk.maxExpandHeadRange <= 10) { return ( <HunkExpandDivider> <HunkExpandLink icon={"fa-angle-double-up"} onClick={this.expandHead(expandableHunk, expandableHunk.maxExpandHeadRange)} text={this.props.t("diff.expandComplete", { count: expandableHunk.maxExpandHeadRange })} /> </HunkExpandDivider> ); } else { return ( <HunkExpandDivider> <HunkExpandLink icon={"fa-angle-up"} onClick={this.expandHead(expandableHunk, 10)} text={this.props.t("diff.expandByLines", { count: 10 })} />{" "} <HunkExpandLink icon={"fa-angle-double-up"} onClick={this.expandHead(expandableHunk, expandableHunk.maxExpandHeadRange)} text={this.props.t("diff.expandComplete", { count: expandableHunk.maxExpandHeadRange })} /> </HunkExpandDivider> ); } } // hunk header must be defined return <span />; }; createHunkFooter = (expandableHunk: ExpandableHunk) => { if (expandableHunk.maxExpandBottomRange > 0) { if (expandableHunk.maxExpandBottomRange <= 10) { return ( <HunkExpandDivider> <HunkExpandLink icon={"fa-angle-double-down"} onClick={this.expandBottom(expandableHunk, expandableHunk.maxExpandBottomRange)} text={this.props.t("diff.expandComplete", { count: expandableHunk.maxExpandBottomRange })} /> </HunkExpandDivider> ); } else { return ( <HunkExpandDivider> <HunkExpandLink icon={"fa-angle-down"} onClick={this.expandBottom(expandableHunk, 10)} text={this.props.t("diff.expandByLines", { count: 10 })} />{" "} <HunkExpandLink icon={"fa-angle-double-down"} onClick={this.expandBottom(expandableHunk, expandableHunk.maxExpandBottomRange)} text={this.props.t("diff.expandComplete", { count: expandableHunk.maxExpandBottomRange })} /> </HunkExpandDivider> ); } } // hunk footer must be defined return <span />; }; createLastHunkFooter = (expandableHunk: ExpandableHunk) => { if (expandableHunk.maxExpandBottomRange !== 0) { return ( <HunkExpandDivider> <HunkExpandLink icon={"fa-angle-down"} onClick={this.expandBottom(expandableHunk, 10)} text={this.props.t("diff.expandLastBottomByLines", { count: 10 })} />{" "} <HunkExpandLink icon={"fa-angle-double-down"} onClick={this.expandBottom(expandableHunk, expandableHunk.maxExpandBottomRange)} text={this.props.t("diff.expandLastBottomComplete")} /> </HunkExpandDivider> ); } // hunk header must be defined return <span />; }; expandHead = (expandableHunk: ExpandableHunk, count: number) => { return () => { return expandableHunk.expandHead(count).then(this.diffExpanded).catch(this.diffExpansionFailed); }; }; expandBottom = (expandableHunk: ExpandableHunk, count: number) => { return () => { return expandableHunk.expandBottom(count).then(this.diffExpanded).catch(this.diffExpansionFailed); }; }; diffExpanded = (newFile: FileDiff) => { this.setState({ file: newFile, diffExpander: new DiffExpander(newFile) }); }; diffExpansionFailed = (err: any) => { this.setState({ expansionError: err }); }; collectHunkAnnotations = (hunk: HunkType) => { const { annotationFactory } = this.props; const { file } = this.state; if (annotationFactory) { return annotationFactory({ hunk, file, }); } else { return EMPTY_ANNOTATION_FACTORY; } }; handleClickEvent = (change: Change, hunk: HunkType) => { const { onClick } = this.props; const { file } = this.state; const context = { changeId: getChangeKey(change), change, hunk, file, }; if (onClick) { onClick(context); } }; createGutterEvents = (hunk: HunkType) => { const { onClick } = this.props; if (onClick) { return { onClick: (event: ChangeEvent) => { this.handleClickEvent(event.change, hunk); }, }; } }; renderHunk = (file: FileDiff, expandableHunk: ExpandableHunk, i: number) => { const hunk = expandableHunk.hunk; if (this.props.markConflicts && hunk.changes) { this.markConflicts(hunk); } const items = []; if (file._links?.lines) { items.push(this.createHunkHeader(expandableHunk)); } else if (i > 0) { items.push( <Decoration> <hr className="my-2" /> </Decoration> ); } items.push( <Hunk key={"hunk-" + hunk.content} hunk={expandableHunk.hunk} widgets={this.collectHunkAnnotations(hunk)} gutterEvents={this.createGutterEvents(hunk)} className={this.props.hunkClass ? this.props.hunkClass(hunk) : null} /> ); if (file._links?.lines) { if (i === file.hunks!.length - 1) { items.push(this.createLastHunkFooter(expandableHunk)); } else { items.push(this.createHunkFooter(expandableHunk)); } } return items; }; markConflicts = (hunk: HunkType) => { let inConflict = false; for (let i = 0; i < hunk.changes.length; ++i) { if (hunk.changes[i].content === "<<<<<<< HEAD") { inConflict = true; } if (inConflict) { hunk.changes[i].type = "conflict"; } if (hunk.changes[i].content.startsWith(">>>>>>>")) { inConflict = false; } } }; getAnchorId(file: FileDiff) { let path: string; if (file.type === "delete") { path = file.oldPath; } else { path = file.newPath; } return escapeWhitespace(path); } renderFileTitle = (file: FileDiff) => { if (file.oldPath !== file.newPath && (file.type === "copy" || file.type === "rename")) { return ( <> {file.oldPath} <Icon name="arrow-right" color="inherit" /> {file.newPath} </> ); } else if (file.type === "delete") { return file.oldPath; } return file.newPath; }; hoverFileTitle = (file: FileDiff): string => { if (file.oldPath !== file.newPath && (file.type === "copy" || file.type === "rename")) { return `${file.oldPath} > ${file.newPath}`; } else if (file.type === "delete") { return file.oldPath; } return file.newPath; }; renderChangeTag = (file: FileDiff) => { const { t } = this.props; if (!file.type) { return; } const key = "diff.changes." + file.type; let value = t(key); if (key === value) { value = file.type; } const color = value === "added" ? "success" : value === "deleted" ? "danger" : "info"; return ( <Tag className={classNames("has-text-weight-normal", "ml-3")} rounded={true} outlined={true} color={color} label={value} /> ); }; isCollapsed = () => { const { file, isCollapsed } = this.props; if (isCollapsed) { return isCollapsed(file); } return this.state.collapsed; }; hasContent = (file: FileDiff) => file && !file.isBinary && file.hunks && file.hunks.length > 0; render() { const { fileControlFactory, fileAnnotationFactory, t } = this.props; const { file, sideBySide, diffExpander, expansionError } = this.state; const viewType = sideBySide ? "split" : "unified"; const collapsed = this.isCollapsed(); const fileAnnotations = fileAnnotationFactory ? fileAnnotationFactory(file) : null; const innerContent = ( <div className="panel-block p-0"> {fileAnnotations} <TokenizedDiffView className={viewType} viewType={viewType} file={file}> {(hunks: HunkType[]) => hunks?.map((hunk, n) => { return this.renderHunk(file, diffExpander.getHunk(n), n); }) } </TokenizedDiffView> </div> ); let icon = "angle-right"; let body = null; if (!collapsed) { icon = "angle-down"; body = innerContent; } const collapseIcon = this.hasContent(file) ? <Icon name={icon} color="inherit" /> : null; const fileControls = fileControlFactory ? fileControlFactory(file, this.setCollapse) : null; const modalTitle = file.type === "delete" ? file.oldPath : file.newPath; const openInFullscreen = file?.hunks?.length ? ( <OpenInFullscreenButton modalTitle={modalTitle} modalBody={<MarginlessModalContent>{innerContent}</MarginlessModalContent>} /> ) : null; const sideBySideToggle = file?.hunks?.length && ( <MenuContext.Consumer> {({ setCollapsed }) => ( <DiffButton icon={sideBySide ? "align-left" : "columns"} tooltip={t(sideBySide ? "diff.combined" : "diff.sideBySide")} onClick={() => this.toggleSideBySide(() => { if (this.state.sideBySide) { setCollapsed(true); } }) } /> )} </MenuContext.Consumer> ); const headerButtons = ( <div className={classNames("level-right", "is-flex", "ml-auto")}> <ButtonGroup> {sideBySideToggle} {openInFullscreen} {fileControls} </ButtonGroup> </div> ); let errorModal; if (expansionError) { errorModal = ( <Modal title={t("diff.expansionFailed")} closeFunction={() => this.setState({ expansionError: undefined })} body={<ErrorNotification error={expansionError} />} active={true} /> ); } return ( <DiffFilePanel className={classNames("panel", "is-size-6")} collapsed={(file && file.isBinary) || collapsed} id={this.getAnchorId(file)} > {errorModal} <div className="panel-heading"> <div className={classNames("level", "is-flex-wrap-wrap")}> <FullWidthTitleHeader className={classNames("level-left", "is-flex", "is-clickable")} onClick={this.toggleCollapse} title={this.hoverFileTitle(file)} > {collapseIcon} <span className={classNames("is-ellipsis-overflow", "is-size-6", "ml-1")}> {this.renderFileTitle(file)} </span> {this.renderChangeTag(file)} </FullWidthTitleHeader> {headerButtons} </div> </div> {body} </DiffFilePanel> ); } } export default withTranslation("repos")(DiffFile);
the_stack
Cluster tests are run if there is a pre-existing minikube cluster. Before running cluster tests the TEST_NAMESPACE namespace is removed, if it exists, from the minikube cluster. Resources are created as part of the cluster tests in the TEST_NAMESPACE namespace. This is done to minimize destructive impact of the cluster tests on an existing minikube cluster and vice versa. */ import * as utils from "../helpers/utils"; import { minikubeReady } from "../helpers/minikube"; import type { Frame, Page } from "playwright"; const TEST_NAMESPACE = "integration-tests"; function getSidebarSelectors(itemId: string) { const root = `.SidebarItem[data-test-id="${itemId}"]`; return { expandSubMenu: `${root} .nav-item`, subMenuLink: (href: string) => `[data-testid=cluster-sidebar] .sub-menu a[href^="${href}"]`, }; } function getLoadedSelector(page: CommonPage): string { if (page.expectedText) { return `${page.expectedSelector} >> text='${page.expectedText}'`; } return page.expectedSelector; } interface CommonPage { name: string; href: string; expectedSelector: string; expectedText?: string; } interface TopPageTest { page: CommonPage; } interface SubPageTest { drawerId: string; pages: CommonPage[]; } type CommonPageTest = TopPageTest | SubPageTest; function isTopPageTest(test: CommonPageTest): test is TopPageTest { return typeof (test as any).page === "object"; } const commonPageTests: CommonPageTest[] = [{ page: { name: "Cluster", href: "/overview", expectedSelector: "div[data-testid='cluster-overview-page'] div.label", expectedText: "CPU", }, }, { page: { name: "Nodes", href: "/nodes", expectedSelector: "h5.title", expectedText: "Nodes", }, }, { drawerId: "workloads", pages: [ { name: "Overview", href: "/workloads", expectedSelector: "h5.box", expectedText: "Overview", }, { name: "Pods", href: "/pods", expectedSelector: "h5.title", expectedText: "Pods", }, { name: "Deployments", href: "/deployments", expectedSelector: "h5.title", expectedText: "Deployments", }, { name: "DaemonSets", href: "/daemonsets", expectedSelector: "h5.title", expectedText: "Daemon Sets", }, { name: "StatefulSets", href: "/statefulsets", expectedSelector: "h5.title", expectedText: "Stateful Sets", }, { name: "ReplicaSets", href: "/replicasets", expectedSelector: "h5.title", expectedText: "Replica Sets", }, { name: "Jobs", href: "/jobs", expectedSelector: "h5.title", expectedText: "Jobs", }, { name: "CronJobs", href: "/cronjobs", expectedSelector: "h5.title", expectedText: "Cron Jobs", }, ], }, { drawerId: "config", pages: [ { name: "ConfigMaps", href: "/configmaps", expectedSelector: "h5.title", expectedText: "Config Maps", }, { name: "Secrets", href: "/secrets", expectedSelector: "h5.title", expectedText: "Secrets", }, { name: "Resource Quotas", href: "/resourcequotas", expectedSelector: "h5.title", expectedText: "Resource Quotas", }, { name: "Limit Ranges", href: "/limitranges", expectedSelector: "h5.title", expectedText: "Limit Ranges", }, { name: "HPA", href: "/hpa", expectedSelector: "h5.title", expectedText: "Horizontal Pod Autoscalers", }, { name: "Pod Disruption Budgets", href: "/poddisruptionbudgets", expectedSelector: "h5.title", expectedText: "Pod Disruption Budgets", }, ], }, { drawerId: "networks", pages: [ { name: "Services", href: "/services", expectedSelector: "h5.title", expectedText: "Services", }, { name: "Endpoints", href: "/endpoints", expectedSelector: "h5.title", expectedText: "Endpoints", }, { name: "Ingresses", href: "/ingresses", expectedSelector: "h5.title", expectedText: "Ingresses", }, { name: "Network Policies", href: "/network-policies", expectedSelector: "h5.title", expectedText: "Network Policies", }, ], }, { drawerId: "storage", pages: [ { name: "Persistent Volume Claims", href: "/persistent-volume-claims", expectedSelector: "h5.title", expectedText: "Persistent Volume Claims", }, { name: "Persistent Volumes", href: "/persistent-volumes", expectedSelector: "h5.title", expectedText: "Persistent Volumes", }, { name: "Storage Classes", href: "/storage-classes", expectedSelector: "h5.title", expectedText: "Storage Classes", }, ], }, { page: { name: "Namespaces", href: "/namespaces", expectedSelector: "h5.title", expectedText: "Namespaces", }, }, { page: { name: "Events", href: "/events", expectedSelector: "h5.title", expectedText: "Events", }, }, { drawerId: "apps", pages: [ { name: "Charts", href: "/apps/charts", expectedSelector: "div.HelmCharts input", }, { name: "Releases", href: "/apps/releases", expectedSelector: "h5.title", expectedText: "Releases", }, ], }, { drawerId: "users", pages: [ { name: "Service Accounts", href: "/service-accounts", expectedSelector: "h5.title", expectedText: "Service Accounts", }, { name: "Roles", href: "/roles", expectedSelector: "h5.title", expectedText: "Roles", }, { name: "Cluster Roles", href: "/cluster-roles", expectedSelector: "h5.title", expectedText: "Cluster Roles", }, { name: "Role Bindings", href: "/role-bindings", expectedSelector: "h5.title", expectedText: "Role Bindings", }, { name: "Cluster Role Bindings", href: "/cluster-role-bindings", expectedSelector: "h5.title", expectedText: "Cluster Role Bindings", }, { name: "Pod Security Policies", href: "/pod-security-policies", expectedSelector: "h5.title", expectedText: "Pod Security Policies", }, ], }, { drawerId: "custom-resources", pages: [ { name: "Definitions", href: "/crd/definitions", expectedSelector: "h5.title", expectedText: "Custom Resources", }, ], }]; utils.describeIf(minikubeReady(TEST_NAMESPACE))("Minikube based tests", () => { let window: Page, cleanup: () => Promise<void>, frame: Frame; beforeEach(async () => { ({ window, cleanup } = await utils.start()); await utils.clickWelcomeButton(window); frame = await utils.lauchMinikubeClusterFromCatalog(window); }, 10*60*1000); afterEach(async () => { await cleanup(); }, 10*60*1000); it("shows cluster context menu in sidebar", async () => { await frame.click(`[data-testid="sidebar-cluster-dropdown"]`); await frame.waitForSelector(`.Menu >> text="Add to Hotbar"`); await frame.waitForSelector(`.Menu >> text="Settings"`); await frame.waitForSelector(`.Menu >> text="Disconnect"`); await frame.waitForSelector(`.Menu >> text="Delete"`); }); it("should navigate around common cluster pages", async () => { for (const test of commonPageTests) { if (isTopPageTest(test)) { const { href, expectedText, expectedSelector } = test.page; const menuButton = await frame.waitForSelector(`a[href^="${href}"]`); await menuButton.click(); await frame.waitForSelector(`${expectedSelector} >> text='${expectedText}'`); continue; } const { drawerId, pages } = test; const selectors = getSidebarSelectors(drawerId); const mainPageSelector = `${selectors.subMenuLink(pages[0].href)} >> text='${pages[0].name}'`; await frame.click(selectors.expandSubMenu); await frame.waitForSelector(mainPageSelector); for (const page of pages) { const subPageButton = await frame.waitForSelector(selectors.subMenuLink(page.href)); await subPageButton.click(); await frame.waitForSelector(getLoadedSelector(page)); } await frame.click(selectors.expandSubMenu); await frame.waitForSelector(mainPageSelector, { state: "hidden" }); } }, 10*60*1000); it("show logs and highlight the log search entries", async () => { await frame.click(`a[href="/workloads"]`); await frame.click(`a[href="/pods"]`); const namespacesSelector = await frame.waitForSelector(".NamespaceSelect"); await namespacesSelector.click(); await namespacesSelector.type("kube-system"); await namespacesSelector.press("Enter"); await namespacesSelector.click(); const kubeApiServerRow = await frame.waitForSelector("div.TableCell >> text=kube-apiserver"); await kubeApiServerRow.click(); await frame.waitForSelector(".Drawer", { state: "visible" }); const showPodLogsIcon = await frame.waitForSelector(".Drawer .drawer-title .Icon >> text=subject"); showPodLogsIcon.click(); // Check if controls are available await frame.waitForSelector(".Dock.isOpen"); await frame.waitForSelector(".LogList .VirtualList"); await frame.waitForSelector(".LogResourceSelector"); const logSearchInput = await frame.waitForSelector(".LogSearch .SearchInput input"); await logSearchInput.type(":"); await frame.waitForSelector(".LogList .list span.active"); const showTimestampsButton = await frame.waitForSelector(".LogControls .show-timestamps"); await showTimestampsButton.click(); const showPreviousButton = await frame.waitForSelector(".LogControls .show-previous"); await showPreviousButton.click(); }, 10*60*1000); it("should show the default namespaces", async () => { await frame.click('a[href="/namespaces"]'); await frame.waitForSelector("div.TableCell >> text='default'"); await frame.waitForSelector("div.TableCell >> text='kube-system'"); }, 10*60*1000); it(`should create the ${TEST_NAMESPACE} and a pod in the namespace`, async () => { await frame.click('a[href="/namespaces"]'); await frame.click("button.add-button"); await frame.waitForSelector("div.AddNamespaceDialog >> text='Create Namespace'"); const namespaceNameInput = await frame.waitForSelector(".AddNamespaceDialog input"); await namespaceNameInput.type(TEST_NAMESPACE); await namespaceNameInput.press("Enter"); await frame.waitForSelector(`div.TableCell >> text=${TEST_NAMESPACE}`); if ((await frame.innerText(`a[href^="/workloads"] .expand-icon`)) === "keyboard_arrow_down") { await frame.click(`a[href^="/workloads"]`); } await frame.click(`a[href^="/pods"]`); const namespacesSelector = await frame.waitForSelector(".NamespaceSelect"); await namespacesSelector.click(); await namespacesSelector.type(TEST_NAMESPACE); await namespacesSelector.press("Enter"); await namespacesSelector.click(); await frame.click(".Icon.new-dock-tab"); try { await frame.click("li.MenuItem.create-resource-tab", { // NOTE: the following shouldn't be required, but is because without it a TypeError is thrown // see: https://github.com/microsoft/playwright/issues/8229 position: { y: 0, x: 0, }, }); } catch (error) { console.log(error); await frame.waitForTimeout(100_000); } const testPodName = "nginx-create-pod-test"; const monacoEditor = await frame.waitForSelector(`.Dock.isOpen [data-test-component="monaco-editor"]`); await monacoEditor.click(); await monacoEditor.type("apiVersion: v1", { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await monacoEditor.type("kind: Pod", { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await monacoEditor.type("metadata:", { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await monacoEditor.type(` name: ${testPodName}`, { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await monacoEditor.type(`namespace: ${TEST_NAMESPACE}`, { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await monacoEditor.press("Backspace", { delay: 10 }); await monacoEditor.type("spec:", { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await monacoEditor.type(" containers:", { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await monacoEditor.type(`- name: ${testPodName}`, { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await monacoEditor.type(" image: nginx:alpine", { delay: 10 }); await monacoEditor.press("Enter", { delay: 10 }); await frame.click(".Dock .Button >> text='Create'"); await frame.waitForSelector(`.TableCell >> text=${testPodName}`); }, 10*60*1000); });
the_stack
import * as vscode from "vscode"; import * as utils from "./utils"; import { Constants } from "./constants"; import { ReqRefresh } from "./types"; import { LeoIntegration } from "./leoIntegration"; import { LeoNode } from "./leoNode"; import { LeoSettingsProvider } from "./webviews/leoSettingsWebview"; import { LeoButtonNode } from "./leoButtonNode"; var LeoInteg: LeoIntegration | undefined = undefined; /** * * Called by vscode when extension is activated * It creates the leoIntegration instance * Will also open the 'welcome/Settings' webview instance if a new version is opened */ export function activate(p_context: vscode.ExtensionContext) { const w_start = process.hrtime(); // For calculating total startup time duration // * Reset Extension context flags (used in 'when' clauses in package.json) utils.setContext(Constants.CONTEXT_FLAGS.BRIDGE_READY, false); // Connected to a leobridge server? utils.setContext(Constants.CONTEXT_FLAGS.TREE_OPENED, false); // Having a Leo file opened on that server? const w_leoIntegExtension = vscode.extensions.getExtension(Constants.PUBLISHER + '.' + Constants.NAME)!; const w_leoIntegVersion = w_leoIntegExtension.packageJSON.version; const w_leo: LeoIntegration = new LeoIntegration(p_context); if (w_leo) { LeoInteg = w_leo; } const w_leoSettingsWebview: LeoSettingsProvider = w_leo.leoSettingsWebview; const w_previousVersion = p_context.globalState.get<string>(Constants.VERSION_STATE_KEY); // Shortcut pointers for readability const U = undefined; const BRIDGE = Constants.LEOBRIDGE; const CMD = Constants.COMMANDS; // * Refresh helper variables: 'states' refresh will also refresh documents pane. const NO_REFRESH: ReqRefresh = {}; const REFRESH_NODE_BODY: ReqRefresh = { node: true, // Reveal the returned 'selected position' without changes to the tree body: true, // Goto/select another node needs the body pane refreshed states: true // * Also refreshes documents pane if node's 'changed' state differ. }; const REFRESH_TREE: ReqRefresh = { tree: true, states: true // * Also refreshes documents pane if node's 'changed' state differ. }; const REFRESH_TREE_BODY: ReqRefresh = { tree: true, body: true, states: true // * Also refreshes documents pane if node's 'changed' state differ. }; const w_commands: [string, (...args: any[]) => any][] = [ // ! REMOVE TESTS ENTRIES FROM PACKAGE.JSON FOR MASTER BRANCH RELEASES ! // ["leointeg.test", () => w_leo.test()], // Test function useful when debugging // ["leointeg.testFromOutline", () => w_leo.test(true)], // Test function useful when debugging. // * Define entries for all commands [CMD.MINIBUFFER, () => w_leo.minibuffer()], // Is referenced in package.json [CMD.STATUS_BAR, () => w_leo.statusBarOnClick()], [CMD.EXECUTE, () => w_leo.nodeCommand({ action: BRIDGE.EXECUTE_SCRIPT, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.CLICK_BUTTON, (p_node: LeoButtonNode) => w_leo.clickAtButton(p_node)], // Not referenced in package.json [CMD.GOTO_SCRIPT, (p_node: LeoButtonNode) => w_leo.gotoScript(p_node)], [CMD.REMOVE_BUTTON, (p_node: LeoButtonNode) => w_leo.removeAtButton(p_node)], [CMD.CLOSE_FILE, () => w_leo.closeLeoFile()], [CMD.NEW_FILE, () => w_leo.newLeoFile()], [CMD.OPEN_FILE, (p_uri?: vscode.Uri) => w_leo.openLeoFile(p_uri)], [CMD.IMPORT_ANY_FILE, () => w_leo.importAnyFile()], // No URL passed from the command definition. [CMD.CLEAR_RECENT_FILES, () => w_leo.clearRecentLeoFiles()], [CMD.RECENT_FILES, () => w_leo.showRecentLeoFiles()], [CMD.SAVE_AS_FILE, () => w_leo.saveAsLeoFile()], [CMD.SAVE_AS_LEOJS, () => w_leo.saveAsLeoJsFile()], [CMD.SAVE_FILE, () => w_leo.saveLeoFile()], // [CMD.SAVE_DISABLED, () => { }], [CMD.SAVE_FILE_FO, () => w_leo.saveLeoFile(true)], [CMD.SWITCH_FILE, () => w_leo.switchLeoFile()], [CMD.SET_OPENED_FILE, (p_index: number) => w_leo.selectOpenedLeoDocument(p_index)], [CMD.REFRESH_FROM_DISK, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.REFRESH_FROM_DISK_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: false })], [CMD.REFRESH_FROM_DISK_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.REFRESH_FROM_DISK_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.REFRESH_FROM_DISK_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.REFRESH_FROM_DISK_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.WRITE_AT_FILE_NODES, () => w_leo.nodeCommand({ action: BRIDGE.WRITE_AT_FILE_NODES, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.WRITE_AT_FILE_NODES_FO, () => w_leo.nodeCommand({ action: BRIDGE.WRITE_AT_FILE_NODES, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.WRITE_DIRTY_AT_FILE_NODES, () => w_leo.nodeCommand({ action: BRIDGE.WRITE_DIRTY_AT_FILE_NODES, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.WRITE_DIRTY_AT_FILE_NODES_FO, () => w_leo.nodeCommand({ action: BRIDGE.WRITE_DIRTY_AT_FILE_NODES, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.GIT_DIFF, () => w_leo.nodeCommand({ action: BRIDGE.GIT_DIFF, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.HEADLINE, (p_node: LeoNode) => w_leo.editHeadline(p_node, true)], [CMD.HEADLINE_SELECTION, () => w_leo.editHeadline(U, false)], [CMD.HEADLINE_SELECTION_FO, () => w_leo.editHeadline(U, true)], // cut/copy/paste/delete given node. [CMD.COPY, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.COPY_PNODE, node: p_node, refreshType: NO_REFRESH, fromOutline: true, keepSelection: true })], [CMD.CUT, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.CUT_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: true })], [CMD.DELETE, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.DELETE_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: true })], [CMD.PASTE, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.PASTE_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: false })], [CMD.PASTE_CLONE, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.PASTE_CLONE_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: false })], // cut/copy/paste/delete current selection (self.commander.p) [CMD.COPY_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.COPY_PNODE, node: U, refreshType: NO_REFRESH, fromOutline: false })], [CMD.CUT_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.CUT_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.CUT_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.CUT_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.DELETE_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.DELETE_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.DELETE_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.DELETE_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.PASTE_CLONE_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.PASTE_CLONE_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.PASTE_CLONE_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.PASTE_CLONE_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.PASTE_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.PASTE_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.PASTE_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.PASTE_PNODE, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.CONTRACT_ALL, () => w_leo.nodeCommand({ action: BRIDGE.CONTRACT_ALL, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.CONTRACT_ALL_FO, () => w_leo.nodeCommand({ action: BRIDGE.CONTRACT_ALL, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.CONTRACT_OR_GO_LEFT, () => w_leo.nodeCommand({ action: BRIDGE.CONTRACT_OR_GO_LEFT, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.EXPAND_AND_GO_RIGHT, () => w_leo.nodeCommand({ action: BRIDGE.EXPAND_AND_GO_RIGHT, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.GOTO_NEXT_CLONE, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.GOTO_NEXT_CLONE, node: p_node, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.GOTO_NEXT_CLONE_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.GOTO_NEXT_CLONE, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: false })], [CMD.GOTO_NEXT_CLONE_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.GOTO_NEXT_CLONE, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.GOTO_NEXT_MARKED, () => w_leo.nodeCommand({ action: BRIDGE.GOTO_NEXT_MARKED, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.GOTO_FIRST_VISIBLE, () => w_leo.nodeCommand({ action: BRIDGE.GOTO_FIRST_VISIBLE, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.GOTO_LAST_SIBLING, () => w_leo.nodeCommand({ action: BRIDGE.GOTO_LAST_SIBLING, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.GOTO_LAST_VISIBLE, () => w_leo.nodeCommand({ action: BRIDGE.GOTO_LAST_VISIBLE, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.GOTO_NEXT_VISIBLE, () => w_leo.nodeCommand({ action: BRIDGE.GOTO_NEXT_VISIBLE, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.GOTO_PREV_VISIBLE, () => w_leo.nodeCommand({ action: BRIDGE.GOTO_PREV_VISIBLE, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.PAGE_UP, () => w_leo.nodeCommand({ action: BRIDGE.PAGE_UP, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.PAGE_DOWN, () => w_leo.nodeCommand({ action: BRIDGE.PAGE_DOWN, node: U, refreshType: REFRESH_NODE_BODY, fromOutline: true })], [CMD.DEHOIST, () => w_leo.nodeCommand({ action: BRIDGE.DEHOIST, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.DEHOIST_FO, () => w_leo.nodeCommand({ action: BRIDGE.DEHOIST, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.HOIST, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.HOIST_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.HOIST_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.HOIST_PNODE, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.HOIST_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.HOIST_PNODE, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.CLONE, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.CLONE_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.CLONE_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.CLONE_PNODE, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.CLONE_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.CLONE_PNODE, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.INSERT, (p_node: LeoNode) => w_leo.insertNode(p_node, true, false)], [CMD.INSERT_SELECTION, () => w_leo.insertNode(U, false, false)], [CMD.INSERT_SELECTION_FO, () => w_leo.insertNode(U, true, false)], [CMD.INSERT_CHILD, (p_node: LeoNode) => w_leo.insertNode(p_node, true, true)], [CMD.INSERT_CHILD_SELECTION, () => w_leo.insertNode(U, false, true)], [CMD.INSERT_CHILD_SELECTION_FO, () => w_leo.insertNode(U, true, true)], // Special command for when inserting rapidly more than one node without // even specifying a headline label, such as spamming CTRL+I rapidly. [CMD.INSERT_SELECTION_INTERRUPT, () => w_leo.insertNode(U, false, false, true)], [CMD.INSERT_CHILD_SELECTION_INTERRUPT, () => w_leo.insertNode(U, false, true, true)], [CMD.MARK, (p_node: LeoNode) => w_leo.changeMark(true, p_node, true)], [CMD.MARK_SELECTION, () => w_leo.changeMark(true, U, false)], [CMD.MARK_SELECTION_FO, () => w_leo.changeMark(true, U, true)], [CMD.UNMARK, (p_node: LeoNode) => w_leo.changeMark(false, p_node, true)], [CMD.UNMARK_SELECTION, () => w_leo.changeMark(false, U, false)], [CMD.UNMARK_SELECTION_FO, () => w_leo.changeMark(false, U, true)], [CMD.EXTRACT, () => w_leo.nodeCommand({ action: BRIDGE.EXTRACT, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.EXTRACT_NAMES, () => w_leo.nodeCommand({ action: BRIDGE.EXTRACT_NAMES, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.MOVE_DOWN, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_DOWN, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: true })], [CMD.MOVE_DOWN_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_DOWN, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.MOVE_DOWN_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_DOWN, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.MOVE_LEFT, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_LEFT, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: true })], [CMD.MOVE_LEFT_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_LEFT, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.MOVE_LEFT_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_LEFT, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.MOVE_RIGHT, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_RIGHT, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: true })], [CMD.MOVE_RIGHT_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_RIGHT, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.MOVE_RIGHT_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_RIGHT, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.MOVE_UP, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_UP, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: true })], [CMD.MOVE_UP_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_UP, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.MOVE_UP_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_PNODE_UP, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.DEMOTE, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.DEMOTE_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: true })], [CMD.DEMOTE_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.DEMOTE_PNODE, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.DEMOTE_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.DEMOTE_PNODE, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.PROMOTE, (p_node: LeoNode) => w_leo.nodeCommand({ action: BRIDGE.PROMOTE_PNODE, node: p_node, refreshType: REFRESH_TREE_BODY, fromOutline: true, keepSelection: true })], [CMD.PROMOTE_SELECTION, () => w_leo.nodeCommand({ action: BRIDGE.PROMOTE_PNODE, node: U, refreshType: REFRESH_TREE, fromOutline: false })], [CMD.PROMOTE_SELECTION_FO, () => w_leo.nodeCommand({ action: BRIDGE.PROMOTE_PNODE, node: U, refreshType: REFRESH_TREE, fromOutline: true })], [CMD.SORT_CHILDREN, () => w_leo.nodeCommand({ action: BRIDGE.SORT_CHILDREN, node: U, refreshType: REFRESH_TREE, fromOutline: false, keepSelection: true })], [CMD.SORT_CHILDREN_FO, () => w_leo.nodeCommand({ action: BRIDGE.SORT_CHILDREN, node: U, refreshType: REFRESH_TREE, fromOutline: true, keepSelection: true })], [CMD.SORT_SIBLING, () => w_leo.nodeCommand({ action: BRIDGE.SORT_SIBLINGS, node: U, refreshType: REFRESH_TREE, fromOutline: false, keepSelection: true })], [CMD.SORT_SIBLING_FO, () => w_leo.nodeCommand({ action: BRIDGE.SORT_SIBLINGS, node: U, refreshType: REFRESH_TREE, fromOutline: true, keepSelection: true })], [CMD.REDO, () => w_leo.nodeCommand({ action: BRIDGE.REDO, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.REDO_DISABLED, () => { }], [CMD.REDO_FO, () => w_leo.nodeCommand({ action: BRIDGE.REDO, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.UNDO, () => w_leo.nodeCommand({ action: BRIDGE.UNDO, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: false })], [CMD.UNDO_DISABLED, () => { }], [CMD.UNDO_FO, () => w_leo.nodeCommand({ action: BRIDGE.UNDO, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.CONNECT, () => w_leo.connect()], [CMD.START_SERVER, () => w_leo.startServer()], [CMD.STOP_SERVER, () => w_leo.killServer()], [CMD.CHOOSE_LEO_FOLDER, () => w_leo.chooseLeoFolder()], // Called by nodes in tree when selected either by mouse, or with enter [CMD.SELECT_NODE, (p_node: LeoNode) => w_leo.selectTreeNode(p_node, false, false)], [CMD.OPEN_ASIDE, (p_node: LeoNode) => w_leo.selectTreeNode(p_node, false, true)], [CMD.SHOW_OUTLINE, () => w_leo.showOutline(true)], // Also focuses on outline [CMD.SHOW_LOG, () => w_leo.showLogPane()], [CMD.SHOW_BODY, () => w_leo.showBody(false)], // Also focuses on body [CMD.SHOW_WELCOME, () => w_leoSettingsWebview.openWebview()], [CMD.SHOW_SETTINGS, () => w_leoSettingsWebview.openWebview()], // Same as SHOW_WELCOME [CMD.COPY_MARKED, () => w_leo.nodeCommand({ action: BRIDGE.COPY_MARKED, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.DIFF_MARKED_NODES, () => w_leo.nodeCommand({ action: BRIDGE.DIFF_MARKED_NODES, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.MARK_CHANGED_ITEMS, () => w_leo.nodeCommand({ action: BRIDGE.MARK_CHANGED_ITEMS, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.MARK_SUBHEADS, () => w_leo.nodeCommand({ action: BRIDGE.MARK_SUBHEADS, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.UNMARK_ALL, () => w_leo.nodeCommand({ action: BRIDGE.UNMARK_ALL, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.CLONE_MARKED_NODES, () => w_leo.nodeCommand({ action: BRIDGE.CLONE_MARKED_NODES, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.DELETE_MARKED_NODES, () => w_leo.nodeCommand({ action: BRIDGE.DELETE_MARKED_NODES, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.MOVE_MARKED_NODES, () => w_leo.nodeCommand({ action: BRIDGE.MOVE_MARKED_NODES, node: U, refreshType: REFRESH_TREE_BODY, fromOutline: true })], [CMD.PREV_NODE, () => w_leo.prevNextNode(false)], [CMD.PREV_NODE_FO, () => w_leo.prevNextNode(false)], [CMD.NEXT_NODE, () => w_leo.prevNextNode(true)], [CMD.NEXT_NODE_FO, () => w_leo.prevNextNode(true)], [CMD.START_SEARCH, () => w_leo.startSearch()], [CMD.FIND_ALL, () => w_leo.findAll(false)], [CMD.FIND_NEXT, () => w_leo.find(false, false)], [CMD.FIND_NEXT_FO, () => w_leo.find(true, false)], [CMD.FIND_PREVIOUS, () => w_leo.find(false, true)], [CMD.FIND_PREVIOUS_FO, () => w_leo.find(true, true)], [CMD.FIND_VAR, () => w_leo.findSymbol(false)], [CMD.FIND_DEF, () => w_leo.findSymbol(true)], [CMD.REPLACE, () => w_leo.replace(false, false)], [CMD.REPLACE_FO, () => w_leo.replace(true, false)], [CMD.REPLACE_THEN_FIND, () => w_leo.replace(false, true)], [CMD.REPLACE_THEN_FIND_FO, () => w_leo.replace(true, true)], [CMD.REPLACE_ALL, () => w_leo.findAll(true)], [CMD.GOTO_GLOBAL_LINE, () => w_leo.gotoGlobalLine()], [CMD.TAG_CHILDREN, () => w_leo.tagChildren()], [CMD.CLONE_FIND_ALL, () => w_leo.cloneFind(false, false)], [CMD.CLONE_FIND_ALL_FLATTENED, () => w_leo.cloneFind(false, true)], [CMD.CLONE_FIND_TAG, () => w_leo.cloneFindTag()], [CMD.CLONE_FIND_MARKED, () => w_leo.cloneFind(true, false)], [CMD.CLONE_FIND_FLATTENED_MARKED, () => w_leo.cloneFind(true, true)], [CMD.SET_FIND_EVERYWHERE_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.ENTIRE_OUTLINE)], [CMD.SET_FIND_NODE_ONLY_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.NODE_ONLY)], [CMD.SET_FIND_SUBOUTLINE_ONLY_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.SUBOUTLINE_ONLY)], [CMD.TOGGLE_FIND_IGNORE_CASE_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.IGNORE_CASE)], [CMD.TOGGLE_FIND_MARK_CHANGES_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.MARK_CHANGES)], [CMD.TOGGLE_FIND_MARK_FINDS_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.MARK_FINDS)], [CMD.TOGGLE_FIND_REGEXP_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.REG_EXP)], [CMD.TOGGLE_FIND_WORD_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.WHOLE_WORD)], [CMD.TOGGLE_FIND_SEARCH_BODY_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.SEARCH_BODY)], [CMD.TOGGLE_FIND_SEARCH_HEADLINE_OPTION, () => w_leo.setSearchSetting(Constants.FIND_INPUTS_IDS.SEARCH_HEADLINE)], [CMD.SET_ENABLE_PREVIEW, () => w_leo.config.setEnablePreview()], [CMD.CLEAR_CLOSE_EMPTY_GROUPS, () => w_leo.config.clearCloseEmptyGroups()], [CMD.SET_CLOSE_ON_FILE_DELETE, () => w_leo.config.setCloseOnFileDelete()], ]; w_commands.map(function (p_command) { p_context.subscriptions.push(vscode.commands.registerCommand(...p_command)); }); // * Close remaining Leo Bodies restored by vscode from last session. closeLeoTextEditors(); // * Show a welcome screen on version updates, then start the actual extension. showWelcomeIfNewer(w_leoIntegVersion, w_previousVersion, w_leo) .then(() => { // if setting for preview mode enabled is false then show popup setTimeout(() => { // A second and a half to make sure first installs have finished setting those // and not to try to see if they're set too soon w_leo.config.checkEnablePreview(); w_leo.config.checkCloseEmptyGroups(); w_leo.config.checkCloseOnFileDelete(); }, 1500); // Start server and/or connect to it, as per user settings w_leo.startNetworkServices(); // Save version # for next startup comparison p_context.globalState.update(Constants.VERSION_STATE_KEY, w_leoIntegVersion); // * Log time taken for startup // console.log('leoInteg startup launched in ', utils.getDurationMs(w_start), 'ms'); }); } /** * * Called when extension is deactivated */ export function deactivate(): Promise<boolean> { closeLeoTextEditors(); if (LeoInteg) { LeoInteg.activated = false; LeoInteg.cleanupBody().then(() => { LeoInteg?.stopConnection(); }); // Call to LeoInteg.stopServer() is not needed: server should handle disconnects. // Server should open tk GUI dialogs if dirty files still remain before closing itself. return new Promise((p_resolve, p_reject) => { setTimeout(() => { LeoInteg?.killServer(); p_resolve(true); }, 30000); } ); } else { return Promise.resolve(false); } } /** * * Closes all visible text editors that have Leo filesystem scheme */ function closeLeoTextEditors() { vscode.window.visibleTextEditors.forEach(p_textEditor => { if (p_textEditor.document.uri.scheme === Constants.URI_LEO_SCHEME) { if (p_textEditor.hide) { p_textEditor.hide(); } } }); } /** * * Show welcome screen if needed, based on last version executed * @param p_version Current version, as a string, from packageJSON.version * @param p_previousVersion Previous version, as a string, from context.globalState.get service * @returns A promise that triggers when command to show the welcome screen is finished, or immediately if not needed */ async function showWelcomeIfNewer(p_version: string, p_previousVersion: string | undefined, p_leoInteg: LeoIntegration): Promise<unknown> { let w_showWelcomeScreen: boolean = false; if (p_previousVersion === undefined) { console.log('leointeg first-time install'); // Force-Set/Clear leointeg's required configuration settings p_leoInteg.config.setEnablePreview(); p_leoInteg.config.clearCloseEmptyGroups(); p_leoInteg.config.setCloseOnFileDelete(); w_showWelcomeScreen = true; } else { if (p_previousVersion !== p_version) { vscode.window.showInformationMessage(`leoInteg upgraded from v${p_previousVersion} to v${p_version}`); // Force-Set/Clear leointeg's required configuration settings but show info messages p_leoInteg.config.checkEnablePreview(true); p_leoInteg.config.checkCloseEmptyGroups(true); p_leoInteg.config.checkCloseOnFileDelete(true); } const [w_major, w_minor] = p_version.split('.').map(p_stringVal => parseInt(p_stringVal, 10)); const [w_prevMajor, w_prevMinor] = p_previousVersion.split('.').map(p_stringVal => parseInt(p_stringVal, 10)); if ( (w_major === w_prevMajor && w_minor === w_prevMinor) || // Don't notify on downgrades (w_major < w_prevMajor || (w_major === w_prevMajor && w_minor < w_prevMinor)) ) { w_showWelcomeScreen = false; } else if (w_major !== w_prevMajor || (w_major === w_prevMajor && w_minor > w_prevMinor)) { // Will show on major or minor upgrade (Formatted as 'Major.Minor.Revision' eg. 1.2.3) w_showWelcomeScreen = true; } } if (w_showWelcomeScreen) { return vscode.commands.executeCommand(Constants.COMMANDS.SHOW_WELCOME); } else { return Promise.resolve(); } }
the_stack
import { equal as constantTimeEqual } from "@stablelib/constant-time"; import { wipe } from "@stablelib/wipe"; export const DIGEST_LENGTH = 16; // Port of Andrew Moon's Poly1305-donna-16. Public domain. // https://github.com/floodyberry/poly1305-donna /** * Poly1305 computes 16-byte authenticator of message using * a one-time 32-byte key. * * Important: key should be used for only one message, * it should never repeat. */ export class Poly1305 { readonly digestLength = DIGEST_LENGTH; private _buffer = new Uint8Array(16); private _r = new Uint16Array(10); private _h = new Uint16Array(10); private _pad = new Uint16Array(8); private _leftover = 0; private _fin = 0; private _finished = false; constructor(key: Uint8Array) { let t0 = key[0] | key[1] << 8; this._r[0] = (t0) & 0x1fff; let t1 = key[2] | key[3] << 8; this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; let t2 = key[4] | key[5] << 8; this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; let t3 = key[6] | key[7] << 8; this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; let t4 = key[8] | key[9] << 8; this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; this._r[5] = ((t4 >>> 1)) & 0x1ffe; let t5 = key[10] | key[11] << 8; this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; let t6 = key[12] | key[13] << 8; this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; let t7 = key[14] | key[15] << 8; this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; this._r[9] = ((t7 >>> 5)) & 0x007f; this._pad[0] = key[16] | key[17] << 8; this._pad[1] = key[18] | key[19] << 8; this._pad[2] = key[20] | key[21] << 8; this._pad[3] = key[22] | key[23] << 8; this._pad[4] = key[24] | key[25] << 8; this._pad[5] = key[26] | key[27] << 8; this._pad[6] = key[28] | key[29] << 8; this._pad[7] = key[30] | key[31] << 8; } private _blocks(m: Uint8Array, mpos: number, bytes: number) { let hibit = this._fin ? 0 : 1 << 11; let h0 = this._h[0], h1 = this._h[1], h2 = this._h[2], h3 = this._h[3], h4 = this._h[4], h5 = this._h[5], h6 = this._h[6], h7 = this._h[7], h8 = this._h[8], h9 = this._h[9]; let r0 = this._r[0], r1 = this._r[1], r2 = this._r[2], r3 = this._r[3], r4 = this._r[4], r5 = this._r[5], r6 = this._r[6], r7 = this._r[7], r8 = this._r[8], r9 = this._r[9]; while (bytes >= 16) { let t0 = m[mpos + 0] | m[mpos + 1] << 8; h0 += (t0) & 0x1fff; let t1 = m[mpos + 2] | m[mpos + 3] << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; let t2 = m[mpos + 4] | m[mpos + 5] << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; let t3 = m[mpos + 6] | m[mpos + 7] << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; let t4 = m[mpos + 8] | m[mpos + 9] << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; h5 += ((t4 >>> 1)) & 0x1fff; let t5 = m[mpos + 10] | m[mpos + 11] << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; let t6 = m[mpos + 12] | m[mpos + 13] << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; let t7 = m[mpos + 14] | m[mpos + 15] << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; h9 += ((t7 >>> 5)) | hibit; let c = 0; let d0 = c; d0 += h0 * r0; d0 += h1 * (5 * r9); d0 += h2 * (5 * r8); d0 += h3 * (5 * r7); d0 += h4 * (5 * r6); c = (d0 >>> 13); d0 &= 0x1fff; d0 += h5 * (5 * r5); d0 += h6 * (5 * r4); d0 += h7 * (5 * r3); d0 += h8 * (5 * r2); d0 += h9 * (5 * r1); c += (d0 >>> 13); d0 &= 0x1fff; let d1 = c; d1 += h0 * r1; d1 += h1 * r0; d1 += h2 * (5 * r9); d1 += h3 * (5 * r8); d1 += h4 * (5 * r7); c = (d1 >>> 13); d1 &= 0x1fff; d1 += h5 * (5 * r6); d1 += h6 * (5 * r5); d1 += h7 * (5 * r4); d1 += h8 * (5 * r3); d1 += h9 * (5 * r2); c += (d1 >>> 13); d1 &= 0x1fff; let d2 = c; d2 += h0 * r2; d2 += h1 * r1; d2 += h2 * r0; d2 += h3 * (5 * r9); d2 += h4 * (5 * r8); c = (d2 >>> 13); d2 &= 0x1fff; d2 += h5 * (5 * r7); d2 += h6 * (5 * r6); d2 += h7 * (5 * r5); d2 += h8 * (5 * r4); d2 += h9 * (5 * r3); c += (d2 >>> 13); d2 &= 0x1fff; let d3 = c; d3 += h0 * r3; d3 += h1 * r2; d3 += h2 * r1; d3 += h3 * r0; d3 += h4 * (5 * r9); c = (d3 >>> 13); d3 &= 0x1fff; d3 += h5 * (5 * r8); d3 += h6 * (5 * r7); d3 += h7 * (5 * r6); d3 += h8 * (5 * r5); d3 += h9 * (5 * r4); c += (d3 >>> 13); d3 &= 0x1fff; let d4 = c; d4 += h0 * r4; d4 += h1 * r3; d4 += h2 * r2; d4 += h3 * r1; d4 += h4 * r0; c = (d4 >>> 13); d4 &= 0x1fff; d4 += h5 * (5 * r9); d4 += h6 * (5 * r8); d4 += h7 * (5 * r7); d4 += h8 * (5 * r6); d4 += h9 * (5 * r5); c += (d4 >>> 13); d4 &= 0x1fff; let d5 = c; d5 += h0 * r5; d5 += h1 * r4; d5 += h2 * r3; d5 += h3 * r2; d5 += h4 * r1; c = (d5 >>> 13); d5 &= 0x1fff; d5 += h5 * r0; d5 += h6 * (5 * r9); d5 += h7 * (5 * r8); d5 += h8 * (5 * r7); d5 += h9 * (5 * r6); c += (d5 >>> 13); d5 &= 0x1fff; let d6 = c; d6 += h0 * r6; d6 += h1 * r5; d6 += h2 * r4; d6 += h3 * r3; d6 += h4 * r2; c = (d6 >>> 13); d6 &= 0x1fff; d6 += h5 * r1; d6 += h6 * r0; d6 += h7 * (5 * r9); d6 += h8 * (5 * r8); d6 += h9 * (5 * r7); c += (d6 >>> 13); d6 &= 0x1fff; let d7 = c; d7 += h0 * r7; d7 += h1 * r6; d7 += h2 * r5; d7 += h3 * r4; d7 += h4 * r3; c = (d7 >>> 13); d7 &= 0x1fff; d7 += h5 * r2; d7 += h6 * r1; d7 += h7 * r0; d7 += h8 * (5 * r9); d7 += h9 * (5 * r8); c += (d7 >>> 13); d7 &= 0x1fff; let d8 = c; d8 += h0 * r8; d8 += h1 * r7; d8 += h2 * r6; d8 += h3 * r5; d8 += h4 * r4; c = (d8 >>> 13); d8 &= 0x1fff; d8 += h5 * r3; d8 += h6 * r2; d8 += h7 * r1; d8 += h8 * r0; d8 += h9 * (5 * r9); c += (d8 >>> 13); d8 &= 0x1fff; let d9 = c; d9 += h0 * r9; d9 += h1 * r8; d9 += h2 * r7; d9 += h3 * r6; d9 += h4 * r5; c = (d9 >>> 13); d9 &= 0x1fff; d9 += h5 * r4; d9 += h6 * r3; d9 += h7 * r2; d9 += h8 * r1; d9 += h9 * r0; c += (d9 >>> 13); d9 &= 0x1fff; c = (((c << 2) + c)) | 0; c = (c + d0) | 0; d0 = c & 0x1fff; c = (c >>> 13); d1 += c; h0 = d0; h1 = d1; h2 = d2; h3 = d3; h4 = d4; h5 = d5; h6 = d6; h7 = d7; h8 = d8; h9 = d9; mpos += 16; bytes -= 16; } this._h[0] = h0; this._h[1] = h1; this._h[2] = h2; this._h[3] = h3; this._h[4] = h4; this._h[5] = h5; this._h[6] = h6; this._h[7] = h7; this._h[8] = h8; this._h[9] = h9; } finish(mac: Uint8Array, macpos = 0): this { const g = new Uint16Array(10); let c: number; let mask: number; let f: number; let i: number; if (this._leftover) { i = this._leftover; this._buffer[i++] = 1; for (; i < 16; i++) { this._buffer[i] = 0; } this._fin = 1; this._blocks(this._buffer, 0, 16); } c = this._h[1] >>> 13; this._h[1] &= 0x1fff; for (i = 2; i < 10; i++) { this._h[i] += c; c = this._h[i] >>> 13; this._h[i] &= 0x1fff; } this._h[0] += (c * 5); c = this._h[0] >>> 13; this._h[0] &= 0x1fff; this._h[1] += c; c = this._h[1] >>> 13; this._h[1] &= 0x1fff; this._h[2] += c; g[0] = this._h[0] + 5; c = g[0] >>> 13; g[0] &= 0x1fff; for (i = 1; i < 10; i++) { g[i] = this._h[i] + c; c = g[i] >>> 13; g[i] &= 0x1fff; } g[9] -= (1 << 13); mask = (c ^ 1) - 1; for (i = 0; i < 10; i++) { g[i] &= mask; } mask = ~mask; for (i = 0; i < 10; i++) { this._h[i] = (this._h[i] & mask) | g[i]; } this._h[0] = ((this._h[0]) | (this._h[1] << 13)) & 0xffff; this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff; this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff; this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff; this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff; this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff; this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff; this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff; f = this._h[0] + this._pad[0]; this._h[0] = f & 0xffff; for (i = 1; i < 8; i++) { f = (((this._h[i] + this._pad[i]) | 0) + (f >>> 16)) | 0; this._h[i] = f & 0xffff; } mac[macpos + 0] = this._h[0] >>> 0; mac[macpos + 1] = this._h[0] >>> 8; mac[macpos + 2] = this._h[1] >>> 0; mac[macpos + 3] = this._h[1] >>> 8; mac[macpos + 4] = this._h[2] >>> 0; mac[macpos + 5] = this._h[2] >>> 8; mac[macpos + 6] = this._h[3] >>> 0; mac[macpos + 7] = this._h[3] >>> 8; mac[macpos + 8] = this._h[4] >>> 0; mac[macpos + 9] = this._h[4] >>> 8; mac[macpos + 10] = this._h[5] >>> 0; mac[macpos + 11] = this._h[5] >>> 8; mac[macpos + 12] = this._h[6] >>> 0; mac[macpos + 13] = this._h[6] >>> 8; mac[macpos + 14] = this._h[7] >>> 0; mac[macpos + 15] = this._h[7] >>> 8; this._finished = true; return this; } update(m: Uint8Array): this { let mpos = 0; let bytes = m.length; let want: number; if (this._leftover) { want = (16 - this._leftover); if (want > bytes) { want = bytes; } for (let i = 0; i < want; i++) { this._buffer[this._leftover + i] = m[mpos + i]; } bytes -= want; mpos += want; this._leftover += want; if (this._leftover < 16) { return this; } this._blocks(this._buffer, 0, 16); this._leftover = 0; } if (bytes >= 16) { want = bytes - (bytes % 16); this._blocks(m, mpos, want); mpos += want; bytes -= want; } if (bytes) { for (let i = 0; i < bytes; i++) { this._buffer[this._leftover + i] = m[mpos + i]; } this._leftover += bytes; } return this; } digest(): Uint8Array { // TODO(dchest): it behaves differently than other hashes/HMAC, // because it throws when finished — others just return saved result. if (this._finished) { throw new Error("Poly1305 was finished"); } let mac = new Uint8Array(16); this.finish(mac); return mac; } clean(): this { wipe(this._buffer); wipe(this._r); wipe(this._h); wipe(this._pad); this._leftover = 0; this._fin = 0; this._finished = true; // mark as finished even if not return this; } } /** * Returns 16-byte authenticator of data using a one-time 32-byte key. * * Important: key should be used for only one message, it should never repeat. */ export function oneTimeAuth(key: Uint8Array, data: Uint8Array): Uint8Array { const h = new Poly1305(key); h.update(data); const digest = h.digest(); h.clean(); return digest; } /** * Returns true if two authenticators are 16-byte long and equal. * Uses contant-time comparison to avoid leaking timing information. */ export function equal(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== DIGEST_LENGTH || b.length !== DIGEST_LENGTH) { return false; } return constantTimeEqual(a, b); }
the_stack
declare namespace ua { type Callback = (error: Error | null, count: number) => void; interface VisitorOptions { hostname?: string | undefined; path?: string | undefined; https?: boolean | undefined; enableBatching?: boolean | undefined; batchSize?: number | undefined; /** * Tracking ID */ tid?: string | undefined; /** * Client ID */ cid?: string | undefined; /** * User ID */ uid?: string | undefined; debug?: boolean | undefined; strictCidFormat?: boolean | undefined; requestOptions?: { [key: string]: any } | undefined; headers?: { [key: string]: string } | undefined; } interface MiddlewareOptions extends VisitorOptions { cookieName?: string | undefined; } interface PageviewParams { /** * Document Path * * The path portion of the page URL. Should begin with '/'. * * Max length: 2048 Bytes */ dp?: string | undefined; /** * Document Host Name * * Specifies the hostname from which content was hosted. * * Max length: 100 Bytes */ dh?: string | undefined; /** * Document Title * * The title of the page / document. * * Max length: 1500 Bytes */ dt?: string | undefined; /** * Document location URL * * Use this parameter to send the full URL (document location) of the page on which content resides. * * Max length: 2048 Bytes */ dl?: string | undefined; [key: string]: any; } interface ScreenviewParams { /** * Screen Name * * This parameter is optional on web properties, and required on mobile properties for screenview hits, * where it is used for the 'Screen Name' of the screenview hit. * * Max length: 2048 Bytes * * Example value: `High Scores` */ cd?: string | undefined; /** * Application Name * * Specifies the application name. This field is required for any hit that has app related data * (i.e., app version, app ID, or app installer ID). For hits sent to web properties, this field is optional. * * Max length: 100 Bytes * * Example value: `My App` */ an?: string | undefined; /** * Application Version * * Specifies the application version. * * Max length: 100 Bytes * * Example value: `1.2` */ av?: string | undefined; /** * Application ID * * Application identifier. * * Max length: 150 Bytes * * Example value: `com.company.app` */ aid?: string | undefined; /** * Application Installer ID * * Application installer identifier. * * Max length: 150 Bytes * * Example value: `com.platform.vending` */ aiid?: string | undefined; [key: string]: any; } interface EventParams { /** * Event Category * * **Required for event hit type.** * * Specifies the event category. Must not be empty. * * Max length: 150 Bytes * * Example value: `Category` */ ec?: string | undefined; /** * Event Action * * **Required for event hit type.** * * Specifies the event action. Must not be empty. * * Max length: 500 Bytes * * Example value: `Action` */ ea?: string | undefined; /** * Event Label * * Specifies the event label. * * Max length: 500 Bytes * * Example value: `Label` */ el?: string | undefined; /** * Event Value * * Specifies the event value. Values must be non-negative. * * Example value: `55` */ ev?: string | number | undefined; p?: string | undefined; dp?: string | undefined; [key: string]: any; } interface TransactionParams { /** * Transaction ID * * **Required for transaction hit type.** * * * A unique identifier for the transaction. This value should be the same for both the Transaction * hit and Items hits associated to the particular transaction. * * Max length: 500 Bytes * * Example value: `OD564` */ ti?: string | undefined; /** * Transaction Revenue * * Specifies the total revenue associated with the transaction. This value should include any * shipping or tax costs. * * Example value: `15.47` */ tr?: string | number | undefined; /** * Transaction Shipping * * Specifies the total shipping cost of the transaction. * * Example value: `3.50` */ ts?: string | number | undefined; /** * Transaction Tax * * Specifies the total tax of the transaction. * * Example value: `11.20` */ tt?: string | number | undefined; /** * Transaction Affiliation * * Specifies the affiliation or store name. * * Max length: 500 Bytes * * Example value: `Member` */ ta?: string | undefined; p?: string | undefined; [key: string]: any; } interface ItemParams { /** * Item Price * * Specifies the price for a single item / unit. * * Example value: `3.50` */ ip?: string | number | undefined; /** * Item Quantity * * Specifies the number of items purchased. * * Example value: `4` */ iq?: string | number | undefined; /** * Item Code * * Specifies the SKU or item code. * * Max length: 500 Bytes * * Example value: `SKU47` */ ic?: string | undefined; /** * Item Name * * **Required for item hit type.** * * Specifies the item name. * * Max length: 500 Bytes * * Example value: `Shoe` */ in?: string | undefined; /** * Item Category * * Specifies the category that the item belongs to. * * Max length: 500 Bytes * * Example value: `Blue` */ iv?: string | undefined; p?: string | undefined; /** * Transaction ID * * **Required for item hit type.** * * A unique identifier for the transaction. This value should be the same for both the Transaction * hit and Items hits associated to the particular transaction. * * Max length: 500 Bytes * * Example value: `OD564` */ ti?: string | undefined; [key: string]: any; } interface ExceptionParams { /** * Exception Description * * Specifies the description of an exception. * * Max length: 150 Bytes * * Example value: `DatabaseError` */ exd?: string | undefined; /** * Is Exception Fatal? * * Specifies whether the exception was fatal. */ exf?: boolean | undefined; [key: string]: any; } interface TimingParams { /** * User timing category * * **Required for timing hit type.** * * Specifies the user timing category. * * Max length: 150 Bytes * * Example value: `category` */ utc?: string | undefined; /** * User timing variable name * * **Required for timing hit type.** * * Specifies the user timing variable. * * Max length: 500 Bytes * * Example value: `lookup` */ utv?: string | undefined; /** * User timing time * * **Required for timing hit type.** * * Specifies the user timing value. The value is in milliseconds. * * Example value: `123` */ utt?: string | number | undefined; /** * User timing label * * Specifies the user timing label. * * Max length: 500 Bytes * * Example value: `label` */ utl?: string | undefined; [key: string]: any; } interface Session { /** * Client ID */ cid?: string | undefined; } class Visitor { constructor(accountID: VisitorOptions | string); constructor( accountID: string, uuid: VisitorOptions | string, context?: { [key: string]: any }, persistentParams?: { [key: string]: any }, ); debug(debug?: boolean): Visitor; reset(): Visitor; set(key: string | number, value: any): void; pageview(path: PageviewParams | string, callback?: Callback): Visitor; pageview(path: string, hostname: string, callback?: Callback): Visitor; pageview(path: string, hostname: string, title: string, callback?: Callback): Visitor; pageview(path: string, hostname: string, title: string, params: PageviewParams, callback?: Callback): Visitor; pv(path: PageviewParams | string, callback?: Callback): Visitor; pv(path: string, hostname: string, callback?: Callback): Visitor; pv(path: string, hostname: string, title: string, callback?: Callback): Visitor; pv(path: string, hostname: string, title: string, params: PageviewParams, callback?: Callback): Visitor; screenview(params: ScreenviewParams, callback?: Callback): Visitor; screenview(screenName: string, appName: string, callback?: Callback): Visitor; screenview(screenName: string, appName: string, appVersion: string, callback?: Callback): Visitor; screenview( screenName: string, appName: string, appVersion: string, appId: string, callback?: Callback, ): Visitor; screenview( screenName: string, appName: string, appVersion: string, appId: string, appInstallerId: string, callback?: Callback, ): Visitor; screenview( screenName: string, appName: string, appVersion: string, appId: string, appInstallerId: string, params: ScreenviewParams, callback?: Callback, ): Visitor; event(params: EventParams, callback?: Callback): Visitor; event(category: string, action: string, callback?: Callback): Visitor; event(category: string, action: string, label: string, callback?: Callback): Visitor; event(category: string, action: string, label: string, value: string | number, callback?: Callback): Visitor; event( category: string, action: string, label: string, value: string | number, params: EventParams, callback?: Callback, ): Visitor; e(params: EventParams, callback?: Callback): Visitor; e(category: string, action: string, callback?: Callback): Visitor; e(category: string, action: string, label: string, callback?: Callback): Visitor; e(category: string, action: string, label: string, value: string | number, callback?: Callback): Visitor; e( category: string, action: string, label: string, value: string | number, params: EventParams, callback?: Callback, ): Visitor; transaction(id: TransactionParams | string, callback?: Callback): Visitor; transaction(id: string, revenue: string | number, callback?: Callback): Visitor; transaction(id: string, revenue: string | number, shipping: string | number, callback?: Callback): Visitor; transaction( id: string, revenue: string | number, shipping: string | number, tax: string | number, callback?: Callback, ): Visitor; transaction( id: string, revenue: string | number, shipping: string | number, tax: string | number, affiliation: string, callback?: Callback, ): Visitor; transaction( id: string, revenue: string | number, shipping: string | number, tax: string | number, affiliation: string, params: TransactionParams, callback?: Callback, ): Visitor; t(id: TransactionParams | string, callback?: Callback): Visitor; t(id: string, revenue: string | number, callback?: Callback): Visitor; t(id: string, revenue: string | number, shipping: string | number, callback?: Callback): Visitor; t( id: string, revenue: string | number, shipping: string | number, tax: string | number, callback?: Callback, ): Visitor; t( id: string, revenue: string | number, shipping: string | number, tax: string | number, affiliation: string, callback?: Callback, ): Visitor; t( id: string, revenue: string | number, shipping: string | number, tax: string | number, affiliation: string, params: TransactionParams, callback?: Callback, ): Visitor; item(price: ItemParams | string | number, callback?: Callback): Visitor; item(price: string | number, quantity: string | number, callback?: Callback): Visitor; item(price: string | number, quantity: string | number, sku: string, callback?: Callback): Visitor; item( price: string | number, quantity: string | number, sku: string, name: string, callback?: Callback, ): Visitor; item( price: string | number, quantity: string | number, sku: string, name: string, variation: string, callback?: Callback, ): Visitor; item( price: string | number, quantity: string | number, sku: string, name: string, variation: string, params: ItemParams, callback?: Callback, ): Visitor; i(price: ItemParams | string | number, callback?: Callback): Visitor; i(price: string | number, quantity: string | number, callback?: Callback): Visitor; i(price: string | number, quantity: string | number, sku: string, callback?: Callback): Visitor; i(price: string | number, quantity: string | number, sku: string, name: string, callback?: Callback): Visitor; i( price: string | number, quantity: string | number, sku: string, name: string, variation: string, callback?: Callback, ): Visitor; i( price: string | number, quantity: string | number, sku: string, name: string, variation: string, params: ItemParams, callback?: Callback, ): Visitor; exception(description: ExceptionParams | string, callback?: Callback): Visitor; exception(description: string, fatal: boolean, callback?: Callback): Visitor; exception(description: string, fatal: boolean, params: ExceptionParams, callback?: Callback): Visitor; timing(category: TimingParams | string, callback?: Callback): Visitor; timing(category: string, variable: string, callback?: Callback): Visitor; timing(category: string, variable: string, time: string | number, callback?: Callback): Visitor; timing(category: string, variable: string, time: string | number, label: string, callback?: Callback): Visitor; timing( category: string, variable: string, time: string | number, label: string, params: TimingParams, callback?: Callback, ): Visitor; send(fn?: (error: any, response: any, body: any) => void): void; } function createFromSession(session?: Session): Visitor; function middleware( tid: string, options?: MiddlewareOptions, ): (req: any, res: any, next: (err: any) => void) => void; } declare function ua(accountID: ua.VisitorOptions | string): ua.Visitor; declare function ua(accountID: string, uuid: ua.VisitorOptions | string): ua.Visitor; declare function ua(accountID: string, uuid: string, options: ua.VisitorOptions): ua.Visitor; export = ua;
the_stack
import * as cdk from '@aws-cdk/core'; import * as iam from '@aws-cdk/aws-iam'; import * as lambda from '@aws-cdk/aws-lambda'; import { CfnUserPoolGroup } from '@aws-cdk/aws-cognito'; import { AmplifyUserPoolGroupStackTemplate } from '@aws-amplify/cli-extensibility-helper'; import { AmplifyUserPoolGroupStackOptions } from './user-pool-group-stack-transform'; import { AmplifyStackTemplate } from 'amplify-cli-core'; import * as fs from 'fs-extra'; import { roleMapLambdaFilePath } from '../constants'; const CFN_TEMPLATE_FORMAT_VERSION = '2010-09-09'; const ROOT_CFN_DESCRIPTION = 'Root Stack for AWS Amplify CLI'; export type AmplifyAuthCognitoStackProps = { synthesizer: cdk.IStackSynthesizer; }; export class AmplifyUserPoolGroupStack extends cdk.Stack implements AmplifyUserPoolGroupStackTemplate, AmplifyStackTemplate { _scope: cdk.Construct; private _cfnParameterMap: Map<string, cdk.CfnParameter> = new Map(); private _cfnConditionMap: Map<string, cdk.CfnCondition> = new Map(); userPoolGroup: Record<string, CfnUserPoolGroup>; userPoolGroupRole: Record<string, iam.CfnRole>; roleMapCustomResource?: cdk.CustomResource; roleMapLambdaFunction?: lambda.CfnFunction; lambdaExecutionRole?: iam.CfnRole; constructor(scope: cdk.Construct, id: string, props: AmplifyAuthCognitoStackProps) { super(scope, id, props); this._scope = scope; this.templateOptions.templateFormatVersion = CFN_TEMPLATE_FORMAT_VERSION; this.templateOptions.description = ROOT_CFN_DESCRIPTION; this.userPoolGroup = {}; this.userPoolGroupRole = {}; } getCfnOutput(logicalId: string): cdk.CfnOutput { throw new Error('Method not implemented.'); } getCfnMapping(logicalId: string): cdk.CfnMapping { throw new Error('Method not implemented.'); } /** * * @param props :cdk.CfnOutputProps * @param logicalId: : lodicalId of the Resource */ addCfnOutput(props: cdk.CfnOutputProps, logicalId: string): void { try { new cdk.CfnOutput(this, logicalId, props); } catch (error) { throw new Error(error); } } /** * * @param props * @param logicalId */ addCfnMapping(props: cdk.CfnMappingProps, logicalId: string): void { try { new cdk.CfnMapping(this, logicalId, props); } catch (error) { throw new Error(error); } } /** * * @param props * @param logicalId */ addCfnResource(props: cdk.CfnResourceProps, logicalId: string): void { try { new cdk.CfnResource(this, logicalId, props); } catch (error) { throw new Error(error); } } /** * * @param props * @param logicalId */ addCfnParameter(props: cdk.CfnParameterProps, logicalId: string): void { try { if (this._cfnParameterMap.has(logicalId)) { throw new Error('logical Id already Exists'); } this._cfnParameterMap.set(logicalId, new cdk.CfnParameter(this, logicalId, props)); } catch (error) { throw new Error(error); } } /** * * @param props * @param logicalId */ addCfnCondition(props: cdk.CfnConditionProps, logicalId: string): void { try { if (this._cfnConditionMap.has(logicalId)) { throw new Error('logical Id already Exists'); } this._cfnConditionMap.set(logicalId, new cdk.CfnCondition(this, logicalId, props)); } catch (error) { throw new Error(error); } } getCfnParameter(logicalId: string): cdk.CfnParameter { if (this._cfnParameterMap.has(logicalId)) { return this._cfnParameterMap.get(logicalId)!; } else { throw new Error(`Cfn Parameter with LogicalId ${logicalId} doesnt exist`); } } getCfnCondition(logicalId: string): cdk.CfnCondition { if (this._cfnConditionMap.has(logicalId)) { return this._cfnConditionMap.get(logicalId)!; } else { throw new Error(`Cfn Parameter with LogicalId ${logicalId} doesnt exist`); } } // add Function for Custom Resource in Root stack /** * * @param _ * @returns */ public renderCloudFormationTemplate = (_: cdk.ISynthesisSession): string => { return JSON.stringify(this._toCloudFormation(), undefined, 2); }; generateUserPoolGroupResources = async (props: AmplifyUserPoolGroupStackOptions) => { props.groups.forEach(group => { this.userPoolGroup[`${group.groupName}`] = new CfnUserPoolGroup(this, `${group.groupName}Group`, { userPoolId: this.getCfnParameter(getCfnParamslogicalId(props.cognitoResourceName, 'UserPoolId'))!.valueAsString, groupName: group.groupName, precedence: group.precedence, }); this.userPoolGroup[`${group.groupName}`].description = 'override success'; if (props.identityPoolName) { this.userPoolGroup[`${group.groupName}`].addPropertyOverride( 'RoleArn', cdk.Fn.getAtt(`${group.groupName}GroupRole`, 'Arn').toString(), ); this.userPoolGroupRole[`${group.groupName}`] = new iam.CfnRole(this, `${group.groupName}GroupRole`, { roleName: cdk.Fn.join('', [ this.getCfnParameter(getCfnParamslogicalId(props.cognitoResourceName, 'UserPoolId'))!.valueAsString, `-${group.groupName}GroupRole`, ]), assumeRolePolicyDocument: { Version: '2012-10-17', Statement: [ { Sid: '', Effect: 'Allow', Principal: { Federated: 'cognito-identity.amazonaws.com', }, Action: 'sts:AssumeRoleWithWebIdentity', Condition: { StringEquals: { 'cognito-identity.amazonaws.com:aud': { Ref: `auth${props.cognitoResourceName}IdentityPoolId`, }, }, 'ForAnyValue:StringLike': { 'cognito-identity.amazonaws.com:amr': 'authenticated' }, }, }, ], }, }); if (group.customPolicies && group.customPolicies.length > 0) { this.userPoolGroupRole[`${group.groupName}`].addPropertyOverride('Policies', JSON.stringify(group.customPolicies, null, 4)); } } }); if (props.identityPoolName) { this.lambdaExecutionRole = new iam.CfnRole(this, 'LambdaExecutionRole', { roleName: cdk.Fn.conditionIf( 'ShouldNotCreateEnvResources', props.cognitoResourceName, cdk.Fn.join('', [`${props.cognitoResourceName}-ExecutionRole-`, cdk.Fn.ref('env')]).toString(), ).toString(), assumeRolePolicyDocument: { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Principal: { Service: ['lambda.amazonaws.com'], }, Action: ['sts:AssumeRole'], }, ], }, policies: [ { policyName: 'UserGroupLogPolicy', policyDocument: { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Action: ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'], Resource: 'arn:aws:logs:*:*:*', }, ], }, }, { policyName: 'UserGroupExecutionPolicy', policyDocument: { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Action: [ 'cognito-identity:SetIdentityPoolRoles', 'cognito-identity:ListIdentityPools', 'cognito-identity:describeIdentityPool', ], Resource: '*', }, ], }, }, { policyName: 'UserGroupPassRolePolicy', policyDocument: { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Action: ['iam:PassRole'], Resource: [ { Ref: 'AuthRoleArn', }, { Ref: 'UnauthRoleArn', }, ], }, ], }, }, ], }); // lambda function for RoleMap Custom Resource this.roleMapLambdaFunction = new lambda.CfnFunction(this, 'RoleMapFunction', { code: { zipFile: fs.readFileSync(roleMapLambdaFilePath, 'utf-8'), }, handler: 'index.handler', runtime: 'nodejs12.x', timeout: 300, role: cdk.Fn.getAtt('LambdaExecutionRole', 'Arn').toString(), }); // adding custom trigger roleMap function this.roleMapCustomResource = new cdk.CustomResource(this, 'RoleMapFunctionInput', { serviceToken: this.roleMapLambdaFunction.attrArn, resourceType: 'Custom::LambdaCallout', properties: { AuthRoleArn: cdk.Fn.ref('AuthRoleArn'), UnauthRoleArn: cdk.Fn.ref('UnauthRoleArn'), identityPoolId: cdk.Fn.ref(getCfnParamslogicalId(props.cognitoResourceName, 'IdentityPoolId')), userPoolId: cdk.Fn.ref(getCfnParamslogicalId(props.cognitoResourceName, 'UserPoolId')), appClientIDWeb: cdk.Fn.ref(getCfnParamslogicalId(props.cognitoResourceName, 'AppClientIDWeb')), appClientID: cdk.Fn.ref(getCfnParamslogicalId(props.cognitoResourceName, 'AppClientID')), region: cdk.Fn.ref('AWS::Region'), env: cdk.Fn.ref('env'), }, }); this.roleMapCustomResource.node.addDependency(this.roleMapLambdaFunction); } }; } export const getCfnParamslogicalId = (cognitoResourceName: string, cfnParamName: string): string => { return `auth${cognitoResourceName}${cfnParamName}`; }; /** * additional class to merge CFN parameters and CFN outputs as cdk doesnt allow same logical ID of constructs in same stack */ export class AmplifyUserPoolGroupStackOutputs extends cdk.Stack implements AmplifyStackTemplate { constructor(scope: cdk.Construct, id: string, props: AmplifyAuthCognitoStackProps) { super(scope, id, props); } getCfnParameter(logicalId: string): cdk.CfnParameter { throw new Error('Method not implemented.'); } getCfnOutput(logicalId: string): cdk.CfnOutput { throw new Error('Method not implemented.'); } getCfnMapping(logicalId: string): cdk.CfnMapping { throw new Error('Method not implemented.'); } getCfnCondition(logicalId: string): cdk.CfnCondition { throw new Error('Method not implemented.'); } addCfnParameter(props: cdk.CfnParameterProps, logicalId: string): void { throw new Error('Method not implemented.'); } addCfnOutput(props: cdk.CfnOutputProps, logicalId: string): void { try { new cdk.CfnOutput(this, logicalId, props); } catch (error) { throw new Error(error); } } addCfnMapping(props: cdk.CfnMappingProps, logicalId: string): void { throw new Error('Method not implemented.'); } addCfnCondition(props: cdk.CfnConditionProps, logicalId: string): void { throw new Error('Method not implemented.'); } addCfnResource(props: cdk.CfnResourceProps, logicalId: string): void { throw new Error('Method not implemented.'); } public renderCloudFormationTemplate = (_: cdk.ISynthesisSession): string => { return JSON.stringify((this as any)._toCloudFormation(), undefined, 2); }; }
the_stack
export class ToDoItemClient { private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) { this.http = http ? http : <any>window; this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "https://localhost:5001"; } /** * Get all */ getAll(): Promise<SwaggerResponse<ToDoItemModel[]>> { let url_ = this.baseUrl + "/api/ToDoItem"; url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.http.fetch(url_, options_).then((_response: Response) => { return this.processGetAll(_response); }); } protected processGetAll(response: Response): Promise<SwaggerResponse<ToDoItemModel[]>> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 404) { return response.text().then((_responseText) => { let result404: any = null; result404 = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, result404); }); } else if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; result200 = _responseText === "" ? null : <ToDoItemModel[]>JSON.parse(_responseText, this.jsonParseReviver); return new SwaggerResponse(status, _headers, result200); }); } else { return response.text().then((_responseText) => { let resultdefault: any = null; resultdefault = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, resultdefault); }); } } /** * Create */ create(command: CreateToDoItemCommand): Promise<SwaggerResponse<void>> { let url_ = this.baseUrl + "/api/ToDoItem"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(command); let options_ = <RequestInit>{ body: content_, method: "POST", headers: { "Content-Type": "application/json", } }; return this.http.fetch(url_, options_).then((_response: Response) => { return this.processCreate(_response); }); } protected processCreate(response: Response): Promise<SwaggerResponse<void>> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 400) { return response.text().then((_responseText) => { let result400: any = null; result400 = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, result400); }); } else if (status === 201) { return response.text().then((_responseText) => { return new SwaggerResponse(status, _headers, <any>null); }); } else { return response.text().then((_responseText) => { let resultdefault: any = null; resultdefault = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, resultdefault); }); } } /** * Get by id */ get(id: string | null): Promise<SwaggerResponse<ToDoItemModel>> { let url_ = this.baseUrl + "/api/ToDoItem/{id}"; if (id === undefined || id === null) throw new Error("The parameter 'id' must be defined."); url_ = url_.replace("{id}", encodeURIComponent("" + id)); url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.http.fetch(url_, options_).then((_response: Response) => { return this.processGet(_response); }); } protected processGet(response: Response): Promise<SwaggerResponse<ToDoItemModel>> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 404) { return response.text().then((_responseText) => { let result404: any = null; result404 = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, result404); }); } else if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; result200 = _responseText === "" ? null : <ToDoItemModel>JSON.parse(_responseText, this.jsonParseReviver); return new SwaggerResponse(status, _headers, result200); }); } else { return response.text().then((_responseText) => { let resultdefault: any = null; resultdefault = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, resultdefault); }); } } /** * Update */ update(id: string | null, command: UpdateCommand): Promise<SwaggerResponse<void>> { let url_ = this.baseUrl + "/api/ToDoItem/{id}"; if (id === undefined || id === null) throw new Error("The parameter 'id' must be defined."); url_ = url_.replace("{id}", encodeURIComponent("" + id)); url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(command); let options_ = <RequestInit>{ body: content_, method: "PUT", headers: { "Content-Type": "application/json", } }; return this.http.fetch(url_, options_).then((_response: Response) => { return this.processUpdate(_response); }); } protected processUpdate(response: Response): Promise<SwaggerResponse<void>> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 204) { return response.text().then((_responseText) => { return new SwaggerResponse(status, _headers, <any>null); }); } else if (status === 404) { return response.text().then((_responseText) => { let result404: any = null; result404 = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, result404); }); } else if (status === 400) { return response.text().then((_responseText) => { let result400: any = null; result400 = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, result400); }); } else { return response.text().then((_responseText) => { let resultdefault: any = null; resultdefault = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, resultdefault); }); } } /** * Delete */ delete(id: string | null): Promise<SwaggerResponse<void>> { let url_ = this.baseUrl + "/api/ToDoItem/{id}"; if (id === undefined || id === null) throw new Error("The parameter 'id' must be defined."); url_ = url_.replace("{id}", encodeURIComponent("" + id)); url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "DELETE", headers: { } }; return this.http.fetch(url_, options_).then((_response: Response) => { return this.processDelete(_response); }); } protected processDelete(response: Response): Promise<SwaggerResponse<void>> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 404) { return response.text().then((_responseText) => { let result404: any = null; result404 = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, result404); }); } else if (status === 200) { return response.text().then((_responseText) => { return new SwaggerResponse(status, _headers, <any>null); }); } else if (status === 400) { return response.text().then((_responseText) => { let result400: any = null; result400 = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, result400); }); } else { return response.text().then((_responseText) => { let resultdefault: any = null; resultdefault = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, resultdefault); }); } } /** * Get audit history of an item by id */ getAuditHistory(id: string | null): Promise<SwaggerResponse<ToDoItemAuditModel[]>> { let url_ = this.baseUrl + "/api/ToDoItem/{id}/AuditHistory"; if (id === undefined || id === null) throw new Error("The parameter 'id' must be defined."); url_ = url_.replace("{id}", encodeURIComponent("" + id)); url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.http.fetch(url_, options_).then((_response: Response) => { return this.processGetAuditHistory(_response); }); } protected processGetAuditHistory(response: Response): Promise<SwaggerResponse<ToDoItemAuditModel[]>> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 404) { return response.text().then((_responseText) => { let result404: any = null; result404 = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, result404); }); } else if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; result200 = _responseText === "" ? null : <ToDoItemAuditModel[]>JSON.parse(_responseText, this.jsonParseReviver); return new SwaggerResponse(status, _headers, result200); }); } else { return response.text().then((_responseText) => { let resultdefault: any = null; resultdefault = _responseText === "" ? null : <ProblemDetails>JSON.parse(_responseText, this.jsonParseReviver); return throwException("A server side error occurred.", status, _responseText, _headers, resultdefault); }); } } /** * Search */ search(query: SearchToDoItemQuery): Promise<SwaggerResponse<DataTablesResponse>> { let url_ = this.baseUrl + "/api/ToDoItem/Search"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(query); let options_ = <RequestInit>{ body: content_, method: "POST", headers: { "Content-Type": "application/json", "Accept": "application/json" } }; return this.http.fetch(url_, options_).then((_response: Response) => { return this.processSearch(_response); }); } protected processSearch(response: Response): Promise<SwaggerResponse<DataTablesResponse>> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; result200 = _responseText === "" ? null : <DataTablesResponse>JSON.parse(_responseText, this.jsonParseReviver); return new SwaggerResponse(status, _headers, result200); }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<SwaggerResponse<DataTablesResponse>>(new SwaggerResponse(status, _headers, <any>null)); } } export interface ProblemDetails { type?: string | undefined; title?: string | undefined; status?: number | undefined; detail?: string | undefined; instance?: string | undefined; extensions?: { [key: string]: any; } | undefined; } /** ToDoItem Api Model */ export interface ToDoItemModel { /** ToDoItem Id */ id: string; /** Category which the To-Do-Item belongs to */ category: string; /** Title of the To-Do-Item */ title: string; /** Whether the To-Do-Item is done */ isCompleted: boolean; } /** Model to create an entity */ export interface CreateToDoItemCommand { /** Category */ category: string; /** Title */ title: string; } /** Model to Update an entity */ export interface UpdateCommand { /** Id */ id: string; /** Category */ category: string; /** Title */ title: string; } /** ToDoItem audit Model */ export interface ToDoItemAuditModel { /** Snapshot of the ToDoItem */ toDoItemModel: ToDoItemModel; /** Date audit record created */ dateCreatedUTC: Date; } export interface DataTablesResponse { /** Total number of records available */ totalRecords: number; /** Data object */ data: any; /** Current page index */ page: number; } /** Model to Search */ export interface SearchToDoItemQuery { /** Starting point (translates to OFFSET) */ start?: number; /** Page Size (translates to LIMIT) */ pageSize: number; /** Sort by Column */ sortColumn?: string | undefined; /** Sort direction */ sortDirection?: SortDirection | undefined; /** Title */ titleFilter?: string | undefined; } export type SortDirection = "Ascending" | "Descending"; export class SwaggerResponse<TResult> { status: number; headers: { [key: string]: any; }; result: TResult; constructor(status: number, headers: { [key: string]: any; }, result: TResult) { this.status = status; this.headers = headers; this.result = result; } } export class ApiException extends Error { message: string; status: number; response: string; headers: { [key: string]: any; }; result: any; constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) { super(); this.message = message; this.status = status; this.response = response; this.headers = headers; this.result = result; } protected isApiException = true; static isApiException(obj: any): obj is ApiException { return obj.isApiException === true; } } function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): any { if (result !== null && result !== undefined) throw result; else throw new ApiException(message, status, response, headers, null); }
the_stack
import { GatewayVpcEndpoint, InterfaceVpcEndpoint, SubnetSelection, ISecurityGroup } from '@aws-cdk/aws-ec2'; import { ContainerDefinition, FargatePlatformVersion, FargateTaskDefinition, ICluster, LogDrivers } from '@aws-cdk/aws-ecs'; import { Effect, PolicyStatement } from '@aws-cdk/aws-iam'; import { ILogGroup, LogGroup, RetentionDays } from '@aws-cdk/aws-logs'; import { IBucket } from '@aws-cdk/aws-s3'; import { IntegrationPattern, JsonPath, TaskStateBaseProps } from '@aws-cdk/aws-stepfunctions'; import { EcsFargateLaunchTarget, EcsRunTask } from '@aws-cdk/aws-stepfunctions-tasks'; import { ArnFormat, Construct, Duration, Fn, Stack } from '@aws-cdk/core'; import { Repository } from '../../codeartifact/repository'; import { Monitoring } from '../../monitoring'; import * as s3 from '../../s3'; import * as constants from '../shared/constants'; import { DocumentationLanguage } from '../shared/language'; import { Transliterator as Container } from './transliterator'; export interface TransliteratorProps { /** * The bucket in which to source assemblies to transliterate. */ readonly bucket: IBucket; /** * The CodeArtifact registry to use for regular operations. */ readonly codeArtifact?: Repository; /** * The monitoring handler to register alarms with. */ readonly monitoring: Monitoring; /** * VPC endpoints to use for interacting with CodeArtifact and S3. */ readonly vpcEndpoints?: TransliteratorVpcEndpoints; /** * How long should execution logs be retained? * * @default RetentionDays.TEN_YEARS */ readonly logRetention?: RetentionDays; } export interface TransliteratorVpcEndpoints { /** * The VPC endpoint for the CloudWatch Logs API. */ readonly cloudWatchLogs: InterfaceVpcEndpoint; /** * The VPC endpoint for the CodeArtifact API (service: 'codeartifact.api') */ readonly codeArtifactApi?: InterfaceVpcEndpoint; /** * The VPC endpoint for the CodeArtifact repositories (service: 'codeartifact.repositories') */ readonly codeArtifact?: InterfaceVpcEndpoint; /** * The VPC endpoint to interact with ECR. */ readonly ecrApi: InterfaceVpcEndpoint; /** * The VPC endpoint to interact with ECR. */ readonly ecr: InterfaceVpcEndpoint; /** * The VPC endpoint for the S3 */ readonly s3: GatewayVpcEndpoint; /** * The VPC endpoint for StepFunctions. */ readonly stepFunctions: InterfaceVpcEndpoint; } /** * Transliterates jsii assemblies to various other languages. */ export class Transliterator extends Construct { public readonly containerDefinition: ContainerDefinition; public readonly logGroup: ILogGroup; public get taskDefinition() { return this.containerDefinition.taskDefinition; } public constructor(scope: Construct, id: string, props: TransliteratorProps) { super(scope, id); const repository = props.vpcEndpoints?.codeArtifact && props.vpcEndpoints.codeArtifactApi ? props.codeArtifact?.throughVpcEndpoint(props.vpcEndpoints.codeArtifactApi, props.vpcEndpoints.codeArtifact) : props.codeArtifact; const bucket = props.vpcEndpoints ? s3.throughVpcEndpoint(props.bucket, props.vpcEndpoints.s3) : props.bucket; const environment: Record<string, string> = { // temporaty hack to generate construct-hub compliant markdown. // see https://github.com/cdklabs/jsii-docgen/blob/master/src/docgen/render/markdown.ts#L172 HEADER_SPAN: 'true', // Set embedded metrics format environment to "Local", to have a consistent experience. AWS_EMF_ENVIRONMENT: 'Local', }; if (props.vpcEndpoints?.codeArtifactApi) { // Those are returned as an array of HOSTED_ZONE_ID:DNS_NAME... We care // only about the DNS_NAME of the first entry in that array (which is // the AZ-agnostic DNS name). environment.CODE_ARTIFACT_API_ENDPOINT = Fn.select(1, Fn.split(':', Fn.select(0, props.vpcEndpoints.codeArtifactApi.vpcEndpointDnsEntries), ), ); } if (props.codeArtifact) { environment.CODE_ARTIFACT_DOMAIN_NAME = props.codeArtifact.repositoryDomainName; environment.CODE_ARTIFACT_DOMAIN_OWNER = props.codeArtifact.repositoryDomainOwner; environment.CODE_ARTIFACT_REPOSITORY_ENDPOINT = props.codeArtifact.repositoryNpmEndpoint; } this.logGroup = new LogGroup(this, 'LogGroup', { retention: props.logRetention }); this.containerDefinition = new Container(this, 'Resource', { environment, logging: LogDrivers.awsLogs({ logGroup: this.logGroup, streamPrefix: 'transliterator' }), taskDefinition: new FargateTaskDefinition(this, 'TaskDefinition', { cpu: 4_096, memoryLimitMiB: 8_192, }), }); repository?.grantReadFromRepository(this.taskDefinition.taskRole); // The task handler reads & writes to this bucket. bucket.grantRead(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.ASSEMBLY_KEY_SUFFIX}`); bucket.grantRead(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.PACKAGE_KEY_SUFFIX}`); bucket.grantWrite(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.UNINSTALLABLE_PACKAGE_SUFFIX}`); bucket.grantDelete(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.UNINSTALLABLE_PACKAGE_SUFFIX}`); for (const language of DocumentationLanguage.ALL) { bucket.grantWrite(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.docsKeySuffix(language)}`); bucket.grantWrite(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.docsKeySuffix(language, '*')}`); bucket.grantWrite(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.docsKeySuffix(language)}${constants.NOT_SUPPORTED_SUFFIX}`); bucket.grantWrite(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.docsKeySuffix(language, '*')}${constants.NOT_SUPPORTED_SUFFIX}`); bucket.grantWrite(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.docsKeySuffix(language)}${constants.CORRUPT_ASSEMBLY_SUFFIX}`); bucket.grantWrite(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.docsKeySuffix(language, '*')}${constants.CORRUPT_ASSEMBLY_SUFFIX}`); bucket.grantDelete(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.docsKeySuffix(language)}${constants.CORRUPT_ASSEMBLY_SUFFIX}`); bucket.grantDelete(this.taskDefinition.taskRole, `${constants.STORAGE_KEY_PREFIX}*${constants.docsKeySuffix(language, '*')}${constants.CORRUPT_ASSEMBLY_SUFFIX}`); } const executionRole = this.taskDefinition.obtainExecutionRole(); props.vpcEndpoints?.ecrApi.addToPolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'ecr:GetAuthorizationToken', ], resources: ['*'], // Action does not support resource scoping principals: [executionRole], sid: 'Allow-ECR-ReadOnly', })); props.vpcEndpoints?.ecr.addToPolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'ecr:BatchCheckLayerAvailability', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', ], // We cannot get the ECR repository info from an asset... So scoping down to same-account repositories instead... resources: [Stack.of(this).formatArn({ service: 'ecr', resource: 'repository', arnFormat: ArnFormat.SLASH_RESOURCE_NAME, resourceName: '*' })], principals: [executionRole], sid: 'Allow-ECR-ReadOnly', })); props.vpcEndpoints?.cloudWatchLogs.addToPolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'logs:CreateLogStream', 'logs:PutLogEvents', ], resources: [ Stack.of(this).formatArn({ service: 'logs', resource: 'log-group', arnFormat: ArnFormat.COLON_RESOURCE_NAME, resourceName: this.logGroup.logGroupName }), Stack.of(this).formatArn({ service: 'logs', resource: 'log-group', arnFormat: ArnFormat.COLON_RESOURCE_NAME, resourceName: `${this.logGroup.logGroupName}:log-stream:*` }), ], principals: [executionRole], sid: 'Allow-Logging', })); props.vpcEndpoints?.stepFunctions.addToPolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'states:SendTaskFailure', 'states:SendTaskHeartbeat', 'states:SendTaskSuccess', ], resources: ['*'], // Actions don't support resource scoping principals: [this.taskDefinition.taskRole], sid: 'Allow-StepFunctions-Callbacks', })); } public createEcsRunTask( scope: Construct, id: string, opts: CreateEcsRunTaskOpts, ): EcsRunTask { return new EcsRunTask(scope, id, { // The container sends heartbeats every minute, but when the runloop will // actually get to submitting it is fairly dependent on the async // workload's nature... so we don't rely on it all too strongly, and // default to a 5 minutes timeout here as a minimal protection. Options // may override this liberally if they know better. heartbeat: Duration.minutes(5), ...opts, containerOverrides: [{ containerDefinition: this.containerDefinition, command: JsonPath.listAt('$'), environment: [ { name: 'SFN_TASK_TOKEN', value: JsonPath.taskToken }, ], }], integrationPattern: IntegrationPattern.WAIT_FOR_TASK_TOKEN, launchTarget: new EcsFargateLaunchTarget({ platformVersion: FargatePlatformVersion.VERSION1_4 }), subnets: opts.vpcSubnets, securityGroups: opts.securityGroups, taskDefinition: this.taskDefinition, }); } } export interface CreateEcsRunTaskOpts extends TaskStateBaseProps { /** * The ECS cluster to use for running the task (must support Fargate) */ readonly cluster: ICluster; /** * The input path to the transliterator input object, presented as an array * containing a single JSON-encoded object. * * This is due to the lack of an ability to "cleanly" model an API where the * `createEcsRunTask` method could do the input processing properly... */ readonly inputPath: string; /** * VPC Subnet placement options, if relevant. */ readonly vpcSubnets?: SubnetSelection; /** * Existing security groups to use for the tasks. * * @default - A new security group is created */ readonly securityGroups?: ISecurityGroup[]; }
the_stack
import { select } from 'd3-selection'; import { getTextWidth } from './textHelpers'; import { prepareBitmap, addToBitmap } from './vega-label/BitMap'; // printBitMap import LabelPlacer from './vega-label/LabelPlacers/LabelPlacer'; import { getBrowser } from './browser-util'; import { polyfillGetAttributeNames } from './customPolyfills'; const browser = getBrowser(); const isIE11 = browser === 'IE'; // ua.includes('rv:11.0'); if (isIE11) { polyfillGetAttributeNames(); } // 8-bit representation of anchors // obtained from vega-label const TOP = 0x0, MIDDLE = 0x1 << 0x2, BOTTOM = 0x2 << 0x2, LEFT = 0x0, CENTER = 0x1, RIGHT = 0x2; // Dictionary mapping from text anchor to its number representation // obtained from vega-label const anchorTextToNumber = { 'top-left': TOP + LEFT, top: TOP + CENTER, 'top-right': TOP + RIGHT, left: MIDDLE + LEFT, middle: MIDDLE + CENTER, right: MIDDLE + RIGHT, 'bottom-left': BOTTOM + LEFT, bottom: BOTTOM + CENTER, 'bottom-right': BOTTOM + RIGHT }; export const findCollision = (bbox1: any, bbox2: any) => bbox1.x <= bbox2.x + bbox2.width && bbox2.x <= bbox1.x + bbox1.width && bbox2.y <= bbox1.y + bbox1.height && bbox1.y <= bbox2.y + bbox2.height; // NOTE: resolveCollision assumes a TRANSITION selection (aka selection.transition().duration()... etc) // results outside of a transition are untested! export const resolveLabelCollision = ({ labelSelection, // this is a set of selections determined by component avoidMarks, // marks to draw to bitmap and then avoid when placing a label validPositions, // this the list of anchor positions to allow (e.g., series label should be middle, top, bottom, right/left?) offsets, // these offsets should be predetermined, but allowing components to specify could be helpful at some point attributes, // can be removed // these are the label placement attributes to set (x, y, text-anchor should be all we need) accessors, // these are the accessors to check when building the key:value hash for mark boundaries size, // an array with chart [ width, height ] boundsScope, // used in getting mark bounds, can help more specifically define placment of labels bitmaps, // outputted/inputted bitmap created, used to speed up subsequent calls to this function hideOnly, // a boolean that will be off by default, but when true is passed it will not place, only hide overlapping removeOnly, // a boolean that will be off by default, but when true is passed it will only remove labels passed from bitmap suppressMarkDraw // a boolean that will be off by default, but when true is passed it will skip drawing chart marks to canvas/bitmap }: { labelSelection: any; avoidMarks: any; attributes?: any; validPositions?: string[]; offsets?: number[]; accessors?: string[]; size: [number, number]; boundsScope?: string; bitmaps?: any; hideOnly?: boolean; removeOnly?: boolean; suppressMarkDraw?: boolean; }) => { const anchors = validPositions; // this should be the allowed placements // const padding = 100; // The padding in pixels (default 0) by which a label may extend past the chart bounding box. const labelsArray = []; // we will populate this with labels to add to bitmap const marksArray = []; // we will populate this with marks to add to bitmap const boundsHash = {}; // hash lookup used to match bounds to labels // check size is there if (!size || size.length !== 2) { throw Error('Size of chart should be specified as an array of width and height'); } // step 1a: map d3 mark selections in preperation for vega-label, an array of multiple selections if (avoidMarks && avoidMarks.length) { avoidMarks.forEach(marks => { const innerMarkArray = []; marks.each((d, i, n) => { const item = {}; item['node'] = n[i]; item['nodeName'] = n[i].nodeName; item['datum'] = d && d.data && d.data.data ? d.data.data : d && d.data ? d.data : d ? d : {}; n[i].getAttributeNames().forEach(attrName => { item[attrName] = select(n[i]).attr(attrName); }); item['boundsScope'] = boundsScope; item['bounds'] = getMarkItemBounds(item); const accessorValues = accessors.map(key => item['datum'][key] || 'Not Found'); boundsHash[accessorValues.join('-')] = item['bounds']; item['key'] = accessorValues.join('-'); innerMarkArray.push(item); }); marksArray.push(innerMarkArray); }); } // step 1b: map d3 label selections in preperation for vega-label, a single label selection if (labelSelection) { labelSelection.each((d, i, n) => { const item = {}; const textElement = n[i]; const style = getComputedStyle(textElement); const fontSize = parseFloat(style.fontSize); const fontFamily = style.fontFamily; item['node'] = n[i]; item['i'] = i; item['nodeName'] = textElement.nodeName; item['fontSize'] = fontSize; // d.fontSize in Vega item['font'] = style.fontFamily; item['text'] = textElement.textContent; item['sort'] = false; item['originalOpacity'] = 1; // should be opacity of the element ultimately item['datum'] = d && d.data && d.data.data ? d.data.data : d && d.data ? d.data : d ? d : {}; textElement.getAttributeNames().forEach(attrName => { item[attrName] = select(textElement).attr(attrName); }); item['textWidth'] = textElement.nodeName === 'rect' ? +item['width'] : getTextWidth(textElement.textContent, fontSize, true, fontFamily); item['textHeight'] = textElement.nodeName === 'rect' ? +item['height'] : Math.max(fontSize - 1, 1); // clone.getBBox().height; const accessorValues = accessors.map(key => item['datum'][key] || 'Not Found'); // we check our has to try and find the corresponding mark boundaries // if we do not find them we fall back to our label boundaries // but the success of this algorithm seems very reliant on mark boundaries item['key'] = accessorValues.join('-'); item['boundsScope'] = boundsScope; const oldDataX = item['data-x']; const oldDataY = item['data-y']; if (removeOnly && item['x'] && item['y'] && !(item['keep-data-y'] === 'true')) { item['data-x'] = item['x']; item['data-y'] = item['y']; } item['markBound'] = boundsHash[accessorValues.join('-')] && !hideOnly // if hide only, we need to use text as is ? boundsHash[accessorValues.join('-')] : getMarkItemBounds(item); if (removeOnly) { item['data-x'] = oldDataX; item['data-y'] = oldDataY; } labelsArray.push(item); }); } // step 2: create bitmaps via vega-label // VCC does not use avoidBaseMark or markType and leverage marksArray directly instead // VCC does not leverage padding yet either, defaulted to 1 for the time being const avoidBaseMark = false; // marksArray && marksArray.length > 0; // we only use basemark if matching markers are passed // console.log('calling bitmap', bitmaps, labelsArray, size, 'markType_unused', avoidBaseMark, marksArray, false, 1); // if we received an inputted bitmap, add to it, otherwise, create a new one from scratch if (bitmaps && bitmaps.length === 2 && !removeOnly && !suppressMarkDraw) { addToBitmap(bitmaps, labelsArray, size, 'markType_unused', avoidBaseMark, marksArray, false, 1); } else if (!removeOnly && !suppressMarkDraw) { bitmaps = prepareBitmap(labelsArray, size, 'markType_unused', avoidBaseMark, marksArray, false, 1); } // useful examples and debugging info from vega-label // this call is an example that will only draw marks into the bitmap and not place any labels // const bitmaps = prepareBitmap([], size, 'markType_unused', true, marksArray, false, 1); // this call is an example that will ignore any base marks passed to the util // const bitmaps = prepareBitmap(labelsArray, size, 'circle', false, [], false, 1); // debugging code // printBitMap(bitmaps[0], 'bitmap-render'); // debug the bitmap being created // console.log('getting bitmap', bitmaps, labelsArray, marksArray); // step 3: place or hide labels... // alignMap is used to reset the text anchor based on the position result from the // occupancy bitmap check const alignMap = { right: 'end', center: 'middle', left: 'start' }; const anchorPositions = anchors.map(anchor => anchorTextToNumber[anchor]); const labelPlacer = new LabelPlacer(bitmaps, size, anchorPositions, offsets); const attributeHash = {}; if (removeOnly) { // removeOnly will circumvent anything done below as it relates to stuff outside // of this utility labelsArray.forEach((item, i) => { const itemKey = item.key === 'Not Found' ? i : `${item.i}-${item.key}`; // console.log('remove-item-from-bitmap', item.i, item.key, item); // call the bitmap remover function we added (tweaked copy of .place()) // we only do this if the label was not already hidden if (item['data-label-hidden'] !== 'true') labelPlacer.unplace(item); // we don't do anything when we remove from bitmap only attributeHash[itemKey] = { 'do-nothing': true }; }); } else { labelsArray.forEach((item, i) => { // this handles when we don't have a data match // requires the lowest level selection in d3 const itemKey = item.key === 'Not Found' ? i : `${item.i}-${item.key}`; if (item['data-hidden'] === 'true') { // console.log('data-hidden', item.i, item.key, item); attributeHash[itemKey] = { 'do-nothing': true }; } else if (+item['opacity'] === 0) { // console.log('opacity-0', item); attributeHash[itemKey] = { 'do-nothing': true }; } else if (!item['data-hidden'] && labelPlacer.place(item)) { // console.log( // 'placing node', // i, // item.key, // item.key === 'Not Found' ? i : item.key, // item, // item.baseline === 'top' // ? item['textHeight'] // : item.baseline === 'bottom' // ? -item['textHeight'] / 5 // : item['textHeight'] / 3, // select(item.node).attr('x'), // item.x, // select(item.node).attr('y'), // item.y // ); attributeHash[itemKey] = { visibility: null, x: item.x, y: item.y, translateX: !+item['data-translate-x'] ? 0 : +item['data-translate-x'], translateY: !+item['data-translate-y'] ? 0 : +item['data-translate-y'], // this adjusts the placement of text based on LabelPlacer logic from vega-label translateHeight: !item['data-no-text-anchor'] ? item.baseline === 'top' ? +item['textHeight'] // / 3 : item.baseline === 'middle' ? +item['textHeight'] / 3 : 0 : 0, 'text-anchor': !item['data-no-text-anchor'] ? alignMap[item.align] : null, 'data-align': item.align, 'data-baseline': item.baseline, 'data-label-moved': true, 'data-label-hidden': false, textHeight: item.textHeight }; // we will have to place item here based on whats comes back } else { // console.log('hiding node', i, item.key, item.key === 'Not Found' ? i : item.key, item); attributeHash[itemKey] = { visibility: 'hidden', x: item.x, y: item.y, translateX: !+item['data-translate-x'] ? 0 : +item['data-translate-x'], translateY: !+item['data-translate-y'] ? 0 : +item['data-translate-y'], // this adjusts the placement of text based on LabelPlacer logic from vega-label translateHeight: !item['data-no-text-anchor'] ? item.baseline === 'top' ? +item['textHeight'] // / 3 : item.baseline === 'middle' ? +item['textHeight'] / 3 : 0 : 0, 'text-anchor': !item['data-no-text-anchor'] ? alignMap[item.align] : null, 'data-align': item.align, 'data-baseline': item.baseline, textHeight: item.textHeight, 'data-label-moved': true, 'data-label-hidden': true }; } }); // now that we are done we set the selection values onto the transition labelSelection.style('visibility', (d, i, n) => { const innerD = d && d.data && d.data.data ? d.data.data : d && d.data ? d.data : d ? d : {}; const accessorValues = accessors.map(key => innerD[key] || 'Not Found'); const attributes = accessorValues.join('-') === 'Not Found' ? attributeHash[i] : attributeHash[`${i}-${accessorValues.join('-')}`]; // first we check if we are not supposed to do anything if (accessors && accessors.length && attributes && attributes['do-nothing']) { // console.log('we are in do nothing', i, d, n[i], attributes); return select(n[i]).style('visibility'); } else { // console.log('we are in do something', i, d, n[i], attributes); // if we get past that, then we can apply visibility update select(n[i]) .attr('data-label-hidden', accessors && accessors.length && attributes && attributes['data-label-hidden']) .attr('data-label-moved', accessors && accessors.length && attributes && attributes['data-label-moved']) .attr('data-align', attributes['data-align']) .attr('data-baseline', attributes['data-baseline']) .attr('dx', !(select(n[i]).attr('data-use-dx') === 'true') ? null : select(n[i]).attr('dx')) .attr('dy', !(select(n[i]).attr('data-use-dy') === 'true') ? null : select(n[i]).attr('dy')) .attr('data-use-dx', null) .attr('data-use-dy', null); // we may still need these, but it was causing a blip of placement on world-map during hideOnly mode return accessors && accessors.length && attributes && (attributes.visibility === null || !attributes.visibility) ? null : 'hidden'; } }); // we only update placement if hideOnly is not passed/truthy, which should be default // matching the selection to the array above has lead to a lot of repeated code // we can likely improve the performance, conciseness and readibility of this code // in future revisions if (!hideOnly) { labelSelection // .each((d, i, n) => { // const innerD = d && d.data && d.data.data ? d.data.data : d && d.data ? d.data : d ? d : {}; // const accessorValues = accessors.map(key => innerD[key] || 'Not Found'); // const attributes = // accessorValues.join('-') === 'Not Found' // ? attributeHash[i] // : attributeHash[`${i}-${accessorValues.join('-')}`]; // this is more concise, but since it is a different selection it doesn't transition // we would have to get transition info from the passed selection somehow to do it this way // select(n[i]) // .transition('collision-update') // this does not work // .ease(labelSelection.ease()) // .duration(labelSelection.duration()) // .style('visibility', attributes && attributes.visibility === null ? null : 'hidden') // .attr('x', attributes && attributes.x ? attributes.x : select(n[i]).attr('x')) // .attr('y', attributes && attributes.y ? attributes.y : select(n[i]).attr('y')) // .attr('dx', (_, i, n) => (!select(n[i]).attr('data-use-dx') ? null : select(n[i]).attr('dx'))) // .attr('dy', (_, i, n) => (!select(n[i]).attr('data-use-dy') ? null : select(n[i]).attr('dy'))); // }) .attr('x', (d, i, n) => { const innerD = d && d.data && d.data.data ? d.data.data : d && d.data ? d.data : d ? d : {}; const accessorValues = accessors.map(key => innerD[key] || 'Not Found'); const attributes = accessorValues.join('-') === 'Not Found' ? attributeHash[i] : attributeHash[`${i}-${accessorValues.join('-')}`]; // console.log('checking stuff', n[i], accessorValues, attributeHash, attributes, accessors && accessors.length && attributes && attributes.x); return accessors && accessors.length && attributes && attributes.x ? attributes.x - attributes.translateX : select(n[i]).attr('data-x'); }) .attr('y', (d, i, n) => { const innerD = d && d.data && d.data.data ? d.data.data : d && d.data ? d.data : d ? d : {}; const accessorValues = accessors.map(key => innerD[key] || 'Not Found'); const attributes = accessorValues.join('-') === 'Not Found' ? attributeHash[i] : attributeHash[`${i}-${accessorValues.join('-')}`]; const translateTextHeight = accessors && accessors.length && attributes && attributes['translateHeight']; return accessors && accessors.length && attributes && attributes.y ? attributes.y - attributes.translateY + translateTextHeight : select(n[i]).attr('data-y'); }) .attr('text-anchor', (d, i, n) => { const innerD = d && d.data && d.data.data ? d.data.data : d && d.data ? d.data : d ? d : {}; const accessorValues = accessors.map(key => innerD[key] || 'Not Found'); const attributes = accessorValues.join('-') === 'Not Found' ? attributeHash[i] : attributeHash[`${i}-${accessorValues.join('-')}`]; return accessors && accessors.length && attributes && attributes['text-anchor'] ? attributes['text-anchor'] : select(n[i]).attr('text-anchor'); }); } } // this print is super userful for debugging, it is coupled with the commented out // canvas element on each VCC component // printBitMap(bitmaps[0], 'bitmap-render'); return bitmaps; }; // function created for VCC to get the 6 point bounds for vega-label algorithm export const getMarkItemBounds = markItem => { const translateX = !+markItem['data-translate-x'] ? 0 : +markItem['data-translate-x']; const translateY = !+markItem['data-translate-y'] ? 0 : +markItem['data-translate-y']; switch (markItem['nodeName']) { case 'text': // this could come through as textWidth or data-width depending on the component const textWidth = (!markItem['textWidth'] ? +markItem['data-width'] : +markItem['textWidth']) || 0; const textHeight = (!markItem['textHeight'] ? +markItem['data-height'] : +markItem['textHeight']) || 0; const fontSize = +markItem['fontSize'] || textHeight; // if we have textHeight, we should always have fontSize const translateTextAnchor = markItem['data-text-anchor'] // if data-text-anchor is passed, we need to use it first ? !markItem['data-text-anchor'] || markItem['data-text-anchor'] === 'start' ? 0 : markItem['data-text-anchor'] === 'middle' ? textWidth / 2 : textWidth : markItem['text-anchor'] ? !markItem['text-anchor'] || markItem['text-anchor'] === 'start' ? 0 : markItem['text-anchor'] === 'middle' ? textWidth / 2 : textWidth : 0; const dx = markItem['data-use-dx'] !== 'true' ? 0 : +markItem['dx'] ? +markItem['dx'] : markItem['dx'] && markItem['dx'].indexOf('em') >= 0 ? +markItem['dx'].replace('em', '') * fontSize : 0; const dy = markItem['data-use-dy'] !== 'true' ? 0 : +markItem['dy'] ? +markItem['dy'] : markItem['dy'] && markItem['dy'].indexOf('em') >= 0 ? +markItem['dy'].replace('em', '') * fontSize : 0; // console.log('creating text bounds for', markItem, textHeight, textWidth, translateTextAnchor); switch (markItem['boundsScope']) { case 'centroid': return [ +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-y'] + dy + translateY + textHeight / 2, +markItem['data-y'] + dy + translateY + textHeight / 2, +markItem['data-y'] + dy + translateY + textHeight / 2 ]; case 'top': return [ +markItem['data-x'] + dx + translateX - translateTextAnchor, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth, +markItem['data-y'] + dy + translateY, +markItem['data-y'] + dy + translateY, +markItem['data-y'] + dy + translateY ]; case 'middle': return [ +markItem['data-x'] + dx + translateX - translateTextAnchor, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth, +markItem['data-y'] + dy + translateY + textHeight / 2, +markItem['data-y'] + dy + translateY + textHeight / 2, +markItem['data-y'] + dy + translateY + textHeight / 2 ]; case 'bottom': return [ +markItem['data-x'] + dx + translateX - translateTextAnchor, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth, +markItem['data-y'] + dy + translateY + textHeight, +markItem['data-y'] + dy + translateY + textHeight, +markItem['data-y'] + dy + translateY + textHeight ]; case 'center': return [ +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-y'] + dy + translateY, +markItem['data-y'] + dy + translateY + textHeight / 2, +markItem['data-y'] + dy + translateY + textHeight ]; case 'right': return [ +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth, +markItem['data-y'] + dy + translateY, +markItem['data-y'] + dy + translateY + textHeight / 2, +markItem['data-y'] + dy + translateY + textHeight ]; case 'left': return [ +markItem['data-x'] + dx + translateX - translateTextAnchor, +markItem['data-x'] + dx + translateX - translateTextAnchor, +markItem['data-x'] + dx + translateX - translateTextAnchor, +markItem['data-y'] + dy + translateY, +markItem['data-y'] + dy + translateY + textHeight / 2, +markItem['data-y'] + dy + translateY + textHeight ]; default: // for default bounds we push text up as this matches how text is rendered on DOM based on bottom left corner return [ +markItem['data-x'] + dx + translateX - translateTextAnchor, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth, +markItem['data-y'] + dy + translateY - textHeight, +markItem['data-y'] + dy + translateY - textHeight / 2, +markItem['data-y'] + dy + translateY ]; // return [ // this will render text with the location centered on the Y axis // +markItem['data-x'] + dx + translateX - translateTextAnchor, // +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth / 2, // +markItem['data-x'] + dx + translateX - translateTextAnchor + textWidth, // +markItem['data-y'] + dy + translateY - textHeight / 2, // +markItem['data-y'] + dy + translateY, // +markItem['data-y'] + dy + translateY + textHeight / 2 // ]; } case 'circle': // cx/cy is center point return [ +markItem['data-cx'] + translateX - +markItem['data-r'], +markItem['data-cx'] + translateX, +markItem['data-cx'] + translateX + +markItem['data-r'], +markItem['data-cy'] + translateY - +markItem['data-r'], +markItem['data-cy'] + translateY, +markItem['data-cy'] + translateY + +markItem['data-r'] ]; case 'rect': // x/y is top left corner switch (markItem['boundsScope']) { case 'annotation': return [ +markItem['data-x'] + translateX - +markItem['data-width'] / 2, +markItem['data-x'] + translateX, +markItem['data-x'] + translateX + +markItem['data-width'] / 2, +markItem['data-y'] + translateY - +markItem['data-height'] / 2, +markItem['data-y'] + translateY, +markItem['data-y'] + translateY + +markItem['data-height'] / 2 ]; case 'top': return [ +markItem['data-x'] + translateX, +markItem['data-x'] + translateX + +markItem['data-width'] / 2, +markItem['data-x'] + translateX + +markItem['data-width'], +markItem['data-y'] + translateY, +markItem['data-y'] + translateY, +markItem['data-y'] + translateY ]; case 'middle': return [ +markItem['data-x'] + translateX + +markItem['data-width'] / 2, +markItem['data-x'] + translateX + +markItem['data-width'] / 2, +markItem['data-x'] + translateX + +markItem['data-width'] / 2, +markItem['data-y'] + translateY + +markItem['data-height'] / 2, +markItem['data-y'] + translateY + +markItem['data-height'] / 2, +markItem['data-y'] + translateY + +markItem['data-height'] / 2 ]; case 'bottom': return [ +markItem['data-x'] + translateX, +markItem['data-x'] + translateX + +markItem['data-width'] / 2, +markItem['data-x'] + translateX + +markItem['data-width'], +markItem['data-y'] + translateY + +markItem['data-height'] - 6, +markItem['data-y'] + translateY + +markItem['data-height'] - 6, +markItem['data-y'] + translateY + +markItem['data-height'] - 6 ]; case 'right': return [ +markItem['data-x'] + translateX + +markItem['data-width'], +markItem['data-x'] + translateX + +markItem['data-width'], +markItem['data-x'] + translateX + +markItem['data-width'], +markItem['data-y'] + translateY, +markItem['data-y'] + translateY + +markItem['data-height'] / 2, +markItem['data-y'] + translateY + +markItem['data-height'] ]; case 'left': return [ +markItem['data-x'] + translateX, +markItem['data-x'] + translateX, +markItem['data-x'] + translateX, +markItem['data-y'] + translateY, +markItem['data-y'] + translateY + +markItem['data-height'] / 2, +markItem['data-y'] + translateY + +markItem['data-height'] ]; default: return [ +markItem['data-x'] + translateX, +markItem['data-x'] + translateX + +markItem['data-width'] / 2, +markItem['data-x'] + translateX + +markItem['data-width'], +markItem['data-y'] + translateY, +markItem['data-y'] + translateY + +markItem['data-height'] / 2, +markItem['data-y'] + translateY + +markItem['data-height'] ]; } case 'path': // console.log('we are getting path bounds', markItem); return +markItem['data-fake-x'] ? [ +markItem['data-fake-x'] + translateX - (+markItem['data-r'] || 0), +markItem['data-fake-x'] + translateX, +markItem['data-fake-x'] + translateX + (+markItem['data-r'] || 0), +markItem['data-fake-y'] + translateY - (+markItem['data-r'] || 0), +markItem['data-fake-y'] + translateY, +markItem['data-fake-y'] + translateY + (+markItem['data-r'] || 0) ] : +markItem['data-centerX1'] ? [ +markItem['data-centerX1'] + translateX, +markItem['data-centerX1'] + (+markItem['data-centerX2'] - +markItem['data-centerX1']) / 2 + translateX, +markItem['data-centerX2'] + translateX, +markItem['data-centerY1'] + translateY, +markItem['data-centerY1'] + (+markItem['data-centerY2'] - +markItem['data-centerY1']) / 2 + translateY, +markItem['data-centerY2'] + translateY ] : [ +markItem['data-x'] + translateX - (+markItem['data-r'] || 0), +markItem['data-x'] + translateX, +markItem['data-x'] + translateX + (+markItem['data-r'] || 0), +markItem['data-y'] + translateY - (+markItem['data-r'] || 0), +markItem['data-y'] + translateY, +markItem['data-y'] + translateY + (+markItem['data-r'] || 0) ]; default: // we should not really be hitting default with anything at this point return [ +markItem['data-x'] + translateX, +markItem['data-x'] + translateX + +markItem['data-width'] / 2, +markItem['data-x'] + translateX + +markItem['data-width'], +markItem['data-y'] + translateY, +markItem['data-y'] + translateY + +markItem['data-height'] / 2, +markItem['data-y'] + translateY + +markItem['data-height'] ]; // remove bbox from algorithm because it is slow and we don't need it // return [ // bbox.x, // bbox.x + bbox.width / 2.0, // bbox.x + bbox.width, // bbox.y, // bbox.y + bbox.height / 2.0, // bbox.y + bbox.height // ]; } };
the_stack
import { Match, Template } from '@aws-cdk/assertions'; import { Stack } from '@aws-cdk/core'; import { behavior, LegacyTestGitHubNpmPipeline, OneStackApp, PIPELINE_ENV, TestApp, ModernTestGitHubNpmPipeline, stringLike } from '../testhelpers'; let app: TestApp; let pipelineStack: Stack; beforeEach(() => { app = new TestApp(); pipelineStack = new Stack(app, 'PipelineStack', { env: PIPELINE_ENV }); }); afterEach(() => { app.cleanup(); }); behavior('action has right settings for same-env deployment', (suite) => { suite.legacy(() => { const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk'); pipeline.addApplicationStage(new OneStackApp(app, 'Same')); THEN_codePipelineExpection(agnosticRole); }); suite.additional('legacy: even if env is specified but the same as the pipeline', () => { const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk'); pipeline.addApplicationStage(new OneStackApp(app, 'Same', { env: PIPELINE_ENV, })); THEN_codePipelineExpection(pipelineEnvRole); }); suite.modern(() => { const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk'); pipeline.addStage(new OneStackApp(app, 'Same')); THEN_codePipelineExpection(agnosticRole); }); suite.additional('modern: even if env is specified but the same as the pipeline', () => { const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk'); pipeline.addStage(new OneStackApp(app, 'Same', { env: PIPELINE_ENV, })); THEN_codePipelineExpection(pipelineEnvRole); }); function THEN_codePipelineExpection(roleArn: (x: string) => any) { // THEN: pipeline structure is correct Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', { Stages: Match.arrayWith([{ Name: 'Same', Actions: [ Match.objectLike({ Name: stringLike('*Prepare'), RoleArn: roleArn('deploy-role'), Configuration: Match.objectLike({ StackName: 'Same-Stack', RoleArn: roleArn('cfn-exec-role'), }), }), Match.objectLike({ Name: stringLike('*Deploy'), RoleArn: roleArn('deploy-role'), Configuration: Match.objectLike({ StackName: 'Same-Stack', }), }), ], }]), }); // THEN: artifact bucket can be read by deploy role Template.fromStack(pipelineStack).hasResourceProperties('AWS::S3::BucketPolicy', { PolicyDocument: { Statement: Match.arrayWith([Match.objectLike({ Action: ['s3:GetObject*', 's3:GetBucket*', 's3:List*'], Principal: { AWS: roleArn('deploy-role'), }, })]), }, }); } }); behavior('action has right settings for cross-account deployment', (suite) => { suite.legacy(() => { // WHEN const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk'); pipeline.addApplicationStage(new OneStackApp(app, 'CrossAccount', { env: { account: 'you' } })); THEN_codePipelineExpectation(); }); suite.modern(() => { // WHEN const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk', { crossAccountKeys: true, }); pipeline.addStage(new OneStackApp(app, 'CrossAccount', { env: { account: 'you' } })); THEN_codePipelineExpectation(); }); function THEN_codePipelineExpectation() { // THEN: Pipelien structure is correct Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', { Stages: Match.arrayWith([{ Name: 'CrossAccount', Actions: [ Match.objectLike({ Name: stringLike('*Prepare'), RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::you:role/cdk-hnb659fds-deploy-role-you-', { Ref: 'AWS::Region' }, ]], }, Configuration: Match.objectLike({ StackName: 'CrossAccount-Stack', RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::you:role/cdk-hnb659fds-cfn-exec-role-you-', { Ref: 'AWS::Region' }, ]], }, }), }), Match.objectLike({ Name: stringLike('*Deploy'), RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::you:role/cdk-hnb659fds-deploy-role-you-', { Ref: 'AWS::Region' }, ]], }, Configuration: Match.objectLike({ StackName: 'CrossAccount-Stack', }), }), ], }]), }); // THEN: Artifact bucket can be read by deploy role Template.fromStack(pipelineStack).hasResourceProperties('AWS::S3::BucketPolicy', { PolicyDocument: { Statement: Match.arrayWith([Match.objectLike({ Action: ['s3:GetObject*', 's3:GetBucket*', 's3:List*'], Principal: { AWS: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, stringLike('*-deploy-role-*'), { Ref: 'AWS::Region' }, ]], }, }, })]), }, }); } }); behavior('action has right settings for cross-region deployment', (suite) => { suite.legacy(() => { // WHEN const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk'); pipeline.addApplicationStage(new OneStackApp(app, 'CrossRegion', { env: { region: 'elsewhere' } })); THEN_codePipelineExpectation(); }); suite.modern(() => { const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk', { crossAccountKeys: true, }); pipeline.addStage(new OneStackApp(app, 'CrossRegion', { env: { region: 'elsewhere' } })); THEN_codePipelineExpectation(); }); function THEN_codePipelineExpectation() { // THEN Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', { Stages: Match.arrayWith([{ Name: 'CrossRegion', Actions: [ Match.objectLike({ Name: stringLike('*Prepare'), RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::', { Ref: 'AWS::AccountId' }, ':role/cdk-hnb659fds-deploy-role-', { Ref: 'AWS::AccountId' }, '-elsewhere', ]], }, Region: 'elsewhere', Configuration: Match.objectLike({ StackName: 'CrossRegion-Stack', RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::', { Ref: 'AWS::AccountId' }, ':role/cdk-hnb659fds-cfn-exec-role-', { Ref: 'AWS::AccountId' }, '-elsewhere', ]], }, }), }), Match.objectLike({ Name: stringLike('*Deploy'), RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::', { Ref: 'AWS::AccountId' }, ':role/cdk-hnb659fds-deploy-role-', { Ref: 'AWS::AccountId' }, '-elsewhere', ]], }, Region: 'elsewhere', Configuration: Match.objectLike({ StackName: 'CrossRegion-Stack', }), }), ], }]), }); } }); behavior('action has right settings for cross-account/cross-region deployment', (suite) => { suite.legacy(() => { // WHEN const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk'); pipeline.addApplicationStage(new OneStackApp(app, 'CrossBoth', { env: { account: 'you', region: 'elsewhere', }, })); THEN_codePipelineExpectations(); }); suite.modern(() => { // WHEN const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk', { crossAccountKeys: true, }); pipeline.addStage(new OneStackApp(app, 'CrossBoth', { env: { account: 'you', region: 'elsewhere', }, })); THEN_codePipelineExpectations(); }); function THEN_codePipelineExpectations() { // THEN: pipeline structure must be correct const stack = app.stackArtifact(pipelineStack); expect(stack).toBeDefined(); Template.fromStack(stack!).hasResourceProperties('AWS::CodePipeline::Pipeline', { Stages: Match.arrayWith([{ Name: 'CrossBoth', Actions: [ Match.objectLike({ Name: stringLike('*Prepare'), RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::you:role/cdk-hnb659fds-deploy-role-you-elsewhere', ]], }, Region: 'elsewhere', Configuration: Match.objectLike({ StackName: 'CrossBoth-Stack', RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::you:role/cdk-hnb659fds-cfn-exec-role-you-elsewhere', ]], }, }), }), Match.objectLike({ Name: stringLike('*Deploy'), RoleArn: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::you:role/cdk-hnb659fds-deploy-role-you-elsewhere', ]], }, Region: 'elsewhere', Configuration: Match.objectLike({ StackName: 'CrossBoth-Stack', }), }), ], }]), }); // THEN: artifact bucket can be read by deploy role const supportStack = app.stackArtifact('PipelineStack-support-elsewhere'); expect(supportStack).toBeDefined(); Template.fromStack(supportStack!).hasResourceProperties('AWS::S3::BucketPolicy', { PolicyDocument: { Statement: Match.arrayWith([Match.objectLike({ Action: Match.arrayWith(['s3:GetObject*', 's3:GetBucket*', 's3:List*']), Principal: { AWS: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, stringLike('*-deploy-role-*'), ]], }, }, })]), }, }); // And the key to go along with it Template.fromStack(supportStack!).hasResourceProperties('AWS::KMS::Key', { KeyPolicy: { Statement: Match.arrayWith([Match.objectLike({ Action: Match.arrayWith(['kms:Decrypt', 'kms:DescribeKey']), Principal: { AWS: { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, stringLike('*-deploy-role-*'), ]], }, }, })]), }, }); } }); function agnosticRole(roleName: string) { return { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::', { Ref: 'AWS::AccountId' }, `:role/cdk-hnb659fds-${roleName}-`, { Ref: 'AWS::AccountId' }, '-', { Ref: 'AWS::Region' }, ]], }; } function pipelineEnvRole(roleName: string) { return { 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, `:iam::${PIPELINE_ENV.account}:role/cdk-hnb659fds-${roleName}-${PIPELINE_ENV.account}-${PIPELINE_ENV.region}`, ]], }; }
the_stack
import { EventEmitter } from 'events'; import { ChildProcess, spawn, SpawnOptions, exec, execSync } from 'child_process'; import { EOL as newline, tmpdir } from 'os'; import { join, sep } from 'path' import { Readable, Transform, TransformCallback, Writable } from 'stream' import { writeFile, writeFileSync } from 'fs'; import { promisify } from 'util'; function toArray<T>(source?: T | T[]): T[] { if (typeof source === 'undefined' || source === null) { return []; } else if (!Array.isArray(source)) { return [source]; } return source; } /** * adds arguments as properties to obj */ function extend(obj: {}, ...args) { Array.prototype.slice.call(arguments, 1).forEach(function (source) { if (source) { for (let key in source) { obj[key] = source[key]; } } }); return obj; } /** * gets a random int from 0-10000000000 */ function getRandomInt() { return Math.floor(Math.random() * 10000000000); } const execPromise = promisify(exec) export interface Options extends SpawnOptions { /** * if binary is enabled message and stderr events will not be emitted */ mode?: 'text' | 'json' | 'binary' formatter?: string | ((param: string) => any) parser?: string | ((param: string) => any) stderrParser?: string | ((param: string) => any) encoding?: BufferEncoding pythonPath?: string /** * see https://docs.python.org/3.7/using/cmdline.html */ pythonOptions?: string[] /** * overrides scriptPath passed into PythonShell constructor */ scriptPath?: string /** * arguments to your program */ args?: string[] } export class PythonShellError extends Error { traceback: string | Buffer; exitCode?: number; } /** * Takes in a string stream and emits batches seperated by newlines */ export class NewlineTransformer extends Transform { // NewlineTransformer: Megatron's little known once-removed cousin private _lastLineData: string; _transform(chunk: any, encoding: string, callback: TransformCallback){ let data: string = chunk.toString() if (this._lastLineData) data = this._lastLineData + data const lines = data.split(newline) this._lastLineData = lines.pop() //@ts-ignore this works, node ignores the encoding if it's a number lines.forEach(this.push.bind(this)) callback() } _flush(done: TransformCallback){ if (this._lastLineData) this.push(this._lastLineData) this._lastLineData = null; done() } } /** * An interactive Python shell exchanging data through stdio * @param {string} script The python script to execute * @param {object} [options] The launch options (also passed to child_process.spawn) * @param [stdoutSplitter] Optional. Splits stdout into chunks, defaulting to splitting into newline-seperated lines * @param [stderrSplitter] Optional. splits stderr into chunks, defaulting to splitting into newline-seperated lines * @constructor */ export class PythonShell extends EventEmitter { scriptPath: string command: string[] mode: string formatter: (param: string | Object) => any parser: (param: string) => any stderrParser: (param: string) => any terminated: boolean childProcess: ChildProcess stdin: Writable; stdout: Readable; stderr: Readable; exitSignal: string; exitCode: number; private stderrHasEnded: boolean; private stdoutHasEnded: boolean; private _remaining: string private _endCallback: (err: PythonShellError, exitCode: number, exitSignal: string) => any // starting 2020 python2 is deprecated so we choose 3 as default static defaultPythonPath = process.platform != "win32" ? "python3" : "python"; static defaultOptions: Options = {}; //allow global overrides for options /** * spawns a python process * @param scriptPath path to script. Relative to current directory or options.scriptFolder if specified * @param options * @param stdoutSplitter Optional. Splits stdout into chunks, defaulting to splitting into newline-seperated lines * @param stderrSplitter Optional. splits stderr into chunks, defaulting to splitting into newline-seperated lines */ constructor(scriptPath: string, options?: Options, stdoutSplitter: Transform = null, stderrSplitter: Transform = null) { super(); /** * returns either pythonshell func (if val string) or custom func (if val Function) */ function resolve(type, val: string | Function) { if (typeof val === 'string') { // use a built-in function using its name return PythonShell[type][val]; } else if (typeof val === 'function') { // use a custom function return val; } } if (scriptPath.trim().length == 0) throw Error("scriptPath cannot be empty! You must give a script for python to run") let self = this; let errorData = ''; EventEmitter.call(this); options = <Options>extend({}, PythonShell.defaultOptions, options); let pythonPath: string; if (!options.pythonPath) { pythonPath = PythonShell.defaultPythonPath; } else pythonPath = options.pythonPath; let pythonOptions = toArray(options.pythonOptions); let scriptArgs = toArray(options.args); this.scriptPath = join(options.scriptPath || '', scriptPath); this.command = pythonOptions.concat(this.scriptPath, scriptArgs); this.mode = options.mode || 'text'; this.formatter = resolve('format', options.formatter || this.mode); this.parser = resolve('parse', options.parser || this.mode); // We don't expect users to ever format stderr as JSON so we default to text mode this.stderrParser = resolve('parse', options.stderrParser || 'text'); this.terminated = false; this.childProcess = spawn(pythonPath, this.command, options); ['stdout', 'stdin', 'stderr'].forEach(function (name) { self[name] = self.childProcess[name]; self.parser && self[name] && self[name].setEncoding(options.encoding || 'utf8'); }); // Node buffers stdout&stderr in batches regardless of newline placement // This is troublesome if you want to recieve distinct individual messages // for example JSON parsing breaks if it recieves partial JSON // so we use newlineTransformer to emit each batch seperated by newline if (this.parser && this.stdout) { if(!stdoutSplitter) stdoutSplitter = new NewlineTransformer() // note that setting the encoding turns the chunk into a string stdoutSplitter.setEncoding(options.encoding || 'utf8') this.stdout.pipe(stdoutSplitter).on('data', (chunk: string) => { this.emit('message', self.parser(chunk)); }); } // listen to stderr and emit errors for incoming data if (this.stderrParser && this.stderr) { if(!stderrSplitter) stderrSplitter = new NewlineTransformer() // note that setting the encoding turns the chunk into a string stderrSplitter.setEncoding(options.encoding || 'utf8') this.stderr.pipe(stderrSplitter).on('data', (chunk: string) => { this.emit('stderr', self.stderrParser(chunk)); }); } if (this.stderr) { this.stderr.on('data', function (data) { errorData += '' + data; }); this.stderr.on('end', function () { self.stderrHasEnded = true; terminateIfNeeded(); }); } else { self.stderrHasEnded = true; } if (this.stdout) { this.stdout.on('end', function () { self.stdoutHasEnded = true; terminateIfNeeded(); }); } else { self.stdoutHasEnded = true; } this.childProcess.on('error', function (err: NodeJS.ErrnoException) { self.emit('error', err); }) this.childProcess.on('exit', function (code, signal) { self.exitCode = code; self.exitSignal = signal; terminateIfNeeded(); }); function terminateIfNeeded() { if (!self.stderrHasEnded || !self.stdoutHasEnded || (self.exitCode == null && self.exitSignal == null)) return; let err: PythonShellError; if (self.exitCode && self.exitCode !== 0) { if (errorData) { err = self.parseError(errorData); } else { err = new PythonShellError('process exited with code ' + self.exitCode); } err = <PythonShellError>extend(err, { executable: pythonPath, options: pythonOptions.length ? pythonOptions : null, script: self.scriptPath, args: scriptArgs.length ? scriptArgs : null, exitCode: self.exitCode }); // do not emit error if only a callback is used if (self.listeners('pythonError').length || !self._endCallback) { self.emit('pythonError', err); } } self.terminated = true; self.emit('close'); self._endCallback && self._endCallback(err, self.exitCode, self.exitSignal); }; } // built-in formatters static format = { text: function toText(data): string { if (!data) return ''; else if (typeof data !== 'string') return data.toString(); return data; }, json: function toJson(data) { return JSON.stringify(data); } }; //built-in parsers static parse = { text: function asText(data): string { return data; }, json: function asJson(data: string) { return JSON.parse(data); } }; /** * checks syntax without executing code * @returns rejects promise w/ string error output if syntax failure */ static async checkSyntax(code: string) { const randomInt = getRandomInt(); const filePath = tmpdir() + sep + `pythonShellSyntaxCheck${randomInt}.py` const writeFilePromise = promisify(writeFile) return writeFilePromise(filePath, code).then(() => { return this.checkSyntaxFile(filePath) }) } static getPythonPath() { return this.defaultOptions.pythonPath ? this.defaultOptions.pythonPath : this.defaultPythonPath; } /** * checks syntax without executing code * @returns {Promise} rejects w/ stderr if syntax failure */ static async checkSyntaxFile(filePath: string) { const pythonPath = this.getPythonPath() let compileCommand = `${pythonPath} -m py_compile ${filePath}` return execPromise(compileCommand) } /** * Runs a Python script and returns collected messages * @param {string} scriptPath The path to the script to execute * @param {Options} options The execution options * @param {Function} callback The callback function to invoke with the script results * @return {PythonShell} The PythonShell instance */ static run(scriptPath: string, options?: Options, callback?: (err?: PythonShellError, output?: any[]) => any) { let pyshell = new PythonShell(scriptPath, options); let output = []; return pyshell.on('message', function (message) { output.push(message); }).end(function (err) { return callback(err ? err : null, output.length ? output : null); }); }; /** * Runs the inputted string of python code and returns collected messages. DO NOT ALLOW UNTRUSTED USER INPUT HERE! * @param {string} code The python code to execute * @param {Options} options The execution options * @param {Function} callback The callback function to invoke with the script results * @return {PythonShell} The PythonShell instance */ static runString(code: string, options?: Options, callback?: (err: PythonShellError, output?: any[]) => any) { // put code in temp file const randomInt = getRandomInt(); const filePath = tmpdir + sep + `pythonShellFile${randomInt}.py` writeFileSync(filePath, code); return PythonShell.run(filePath, options, callback); }; static getVersion(pythonPath?: string) { if (!pythonPath) pythonPath = this.getPythonPath() return execPromise(pythonPath + " --version"); } static getVersionSync(pythonPath?: string) { if (!pythonPath) pythonPath = this.getPythonPath() return execSync(pythonPath + " --version").toString() } /** * Parses an error thrown from the Python process through stderr * @param {string|Buffer} data The stderr contents to parse * @return {Error} The parsed error with extended stack trace when traceback is available */ private parseError(data: string | Buffer) { let text = '' + data; let error: PythonShellError; if (/^Traceback/.test(text)) { // traceback data is available let lines = text.trim().split(newline); let exception = lines.pop(); error = new PythonShellError(exception); error.traceback = data; // extend stack trace error.stack += newline + ' ----- Python Traceback -----' + newline + ' '; error.stack += lines.slice(1).join(newline + ' '); } else { // otherwise, create a simpler error with stderr contents error = new PythonShellError(text); } return error; }; /** * Sends a message to the Python shell through stdin * Override this method to format data to be sent to the Python process * @returns {PythonShell} The same instance for chaining calls */ send(message: string | Object) { if (!this.stdin) throw new Error("stdin not open for writing"); let data = this.formatter ? this.formatter(message) : message; if (this.mode !== 'binary') data += newline; this.stdin.write(data); return this; }; /** * Closes the stdin stream. Unless python is listening for stdin in a loop * this should cause the process to finish its work and close. * @returns {PythonShell} The same instance for chaining calls */ end(callback: (err: PythonShellError, exitCode: number, exitSignal: string) => any) { if (this.childProcess.stdin) { this.childProcess.stdin.end(); } this._endCallback = callback; return this; }; /** * Sends a kill signal to the process * @returns {PythonShell} The same instance for chaining calls */ kill(signal?: NodeJS.Signals) { this.terminated = this.childProcess.kill(signal); return this; }; /** * Alias for kill. * @deprecated */ terminate(signal?: NodeJS.Signals) { // todo: remove this next breaking release return this.kill(signal) } }; // This interface is merged in with the above class definition export interface PythonShell { addListener(event: string, listener: (...args: any[]) => void): this; emit(event: string | symbol, ...args: any[]): boolean; on(event: string, listener: (...args: any[]) => void): this; once(event: string, listener: (...args: any[]) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "message", listener: (parsedChunk: any) => void): this; emit(event: "message", parsedChunk: any): boolean; on(event: "message", listener: (parsedChunk: any) => void): this; once(event: "message", listener: (parsedChunk: any) => void): this; prependListener(event: "message", listener: (parsedChunk: any) => void): this; prependOnceListener(event: "message", listener: (parsedChunk: any) => void): this; addListener(event: "stderr", listener: (parsedChunk: any) => void): this; emit(event: "stderr", parsedChunk: any): boolean; on(event: "stderr", listener: (parsedChunk: any) => void): this; once(event: "stderr", listener: (parsedChunk: any) => void): this; prependListener(event: "stderr", listener: (parsedChunk: any) => void): this; prependOnceListener(event: "stderr", listener: (parsedChunk: any) => void): this; addListener(event: "close", listener: () => void): this; emit(event: "close",): boolean; on(event: "close", listener: () => void): this; once(event: "close", listener: () => void): this; prependListener(event: "close", listener: () => void): this; prependOnceListener(event: "close", listener: () => void): this; addListener(event: "error", listener: (error: NodeJS.ErrnoException) => void): this; emit(event: "error", error: NodeJS.ErrnoException): boolean; on(event: "error", listener: (error: NodeJS.ErrnoException) => void): this; once(event: "error", listener: (error: NodeJS.ErrnoException) => void): this; prependListener(event: "error", listener: (error: NodeJS.ErrnoException) => void): this; prependOnceListener(event: "error", listener: (error: NodeJS.ErrnoException) => void): this; addListener(event: "pythonError", listener: (error: PythonShellError) => void): this; emit(event: "pythonError", error: PythonShellError): boolean; on(event: "pythonError", listener: (error: PythonShellError) => void): this; once(event: "pythonError", listener: (error: PythonShellError) => void): this; prependListener(event: "pythonError", listener: (error: PythonShellError) => void): this; prependOnceListener(event: "pythonError", listener: (error: PythonShellError) => void): this; }
the_stack
import * as jv from "jsverify" import * as inst from "./instances" import * as assert from "./asserts" import { is, Try, Success, Failure, Left, Right, DummyError, Some, None, Option } from "funfix-core" import { HK } from "funland" import { Equiv } from "funland-laws" import { monadCheck } from "../../../../test-common" import { TestScheduler, Future, ExecutionModel, Duration } from "funfix-exec" import { IO, IOModule } from "../../src/" describe("IOPure", () => { it("evaluates IO.pure(v).run() to Future.pure(v)", () => { const io = IO.pure(1) assert.equal(io.run().value(), Some(Success(1))) }) it("evaluates IO.raise(e).run() to Future.raise(e)", () => { const io = IO.raise("dummy") assert.equal(io.run().value(), Some(Failure("dummy"))) }) it("evaluates IO.pure(v).runOnComplete()", () => { let result: Option<Try<number>> = None IO.pure(1).runOnComplete(r => { result = Some(r as any) }) assert.equal(result, Some(Success(1))) }) it("evaluates IO.raise(e).runOnComplete()", () => { let result: Option<Try<number>> = None IO.raise("error").runOnComplete(r => { result = Some(r as any) }) assert.equal(result, Some(Failure("error"))) }) it("is stack safe in flatMap shallow loop (run)", () => { const ec = scheduler() const io = flatShallowLoop(10000, x => IO.pure(x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("is stack safe in flatMap shallow loop (runOnComplete)", () => { const ec = scheduler() const io = flatShallowLoop(5000, x => IO.pure(x)) let result: Option<Try<any>> = None io.runOnComplete(r => { result = Some(r) }, ec) assert.equal(result, None); ec.tick() assert.equal(result, Some(Success(0))) }) it("is stack safe in flatMap eager loop (run)", () => { const ec = scheduler() const io = flatEagerLoop(2000, x => IO.pure(x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("is stack safe in flatMap eager loop (runOnComplete)", () => { const ec = scheduler() const io = flatEagerLoop(5000, x => IO.pure(x)) let result: Option<Try<any>> = None io.runOnComplete(r => { result = Some(r) }, ec) assert.equal(result, None); ec.tick() assert.equal(result, Some(Success(0))) }) it("is stack safe in suspend loop", () => { const ec = scheduler() const io = suspendLoop(10000, x => IO.pure(x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) }) describe("IO.always", () => { it("is stack safe in flatMap shallow loop", () => { const ec = scheduler() const io = flatShallowLoop(10000, x => IO.always(() => x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("is stack safe in flatMap eager loop", () => { const ec = scheduler() const io = flatEagerLoop(2000, x => IO.always(() => x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("is stack safe in suspend loop", () => { const ec = scheduler() const io = suspendLoop(10000, x => IO.always(() => x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) }) describe("IO.once", () => { let ec: TestScheduler before(() => { ec = scheduler() }) it("is stack safe in flatMap shallow loop", () => { const io = flatShallowLoop(10000, x => IO.once(() => x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("is stack safe in flatMap eager loop", () => { const io = flatEagerLoop(2000, x => IO.once(() => x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("is stack safe in suspend loop", () => { const io = suspendLoop(10000, x => IO.once(() => x)) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) }) describe("IO.async", () => { let ec: TestScheduler before(() => { ec = scheduler() }) it("is stack safe in flatMap shallow loop", () => { const io = flatShallowLoop(10000, x => IO.async<number>((ec, cb) => cb(Success(x)))) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("is stack safe in flatMap eager loop", () => { const io = flatEagerLoop(2000, x => IO.async<number>((ec, cb) => cb(Success(x)))) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("is stack safe in suspend loop", () => { const io = suspendLoop(10000, x => IO.async<number>((ec, cb) => cb(Success(x)))) const f = io.run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(0))) }) it("protects against multiple callback calls", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.async((ec, cb) => { cb(Success(1)) cb(Success(2)) cb(Failure(dummy)) }) const f = io.run(ec); ec.tick() assert.equal(f.value(), Some(Success(1))) assert.ok(ec.triggeredFailures().length > 0) assert.equal(ec.triggeredFailures()[0], dummy) }) it("protects against user error", () => { const ec = scheduler() const dummy = new DummyError("registration1") const io = IO.async(() => { throw dummy }) const f = io.run(ec); ec.tick() assert.equal(f.value(), Some(Failure(dummy))) }) it("reports error in registration after callback was called", () => { const ec = scheduler() const dummy = new DummyError("registration2") const io = IO.async<number>((ec, cb) => { cb(Success(1)); throw dummy }) const f = io.run(ec); ec.tick() assert.equal(f.value(), Some(Success(1))) assert.ok(ec.triggeredFailures().length > 0) assert.equal(ec.triggeredFailures()[0].message, dummy.message) }) }) describe("IO (error recovery)", () => { it("protects against errors in map", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.pure(1).map(() => { throw dummy }) assert.equal(io.run(ec).value(), Some(Failure(dummy))) }) it("recovers from failure with run()", () => { const ec = scheduler() const io = IO.raise<number>("error").recoverWith(e => { if (e === "error") return IO.pure(100) return IO.raise(e) }) const f = io.run(ec) ec.tick() assert.equal(f.value(), Some(Success(100))) }) it("recovers from failure with runOnComplete()", () => { const ec = scheduler() const io = IO.raise<number>("error").recoverWith(e => { if (e === "error") return IO.pure(100) return IO.raise(e) }) let result: Option<Try<number>> = None io.runOnComplete((r: Try<number>) => { result = Some(r) }) ec.tick() assert.equal(result, Some(Success(100))) }) it("protects flatMap against user error (run)", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.pure(1).flatMap(() => { throw dummy }) const f = io.run(ec) ec.tick() assert.equal(f.value(), Some(Failure(dummy))) }) it("protects flatMap against user error (runOnComplete)", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.pure(1).flatMap(() => { throw dummy }) let result: Option<Try<any>> = None io.runOnComplete(r => { result = Some(r) }, ec) ec.tick() assert.equal(result, Some(Failure(dummy))) }) it("recovers from user error in flatMap (run)", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.pure(1).flatMap(() => { throw dummy }) .recoverWith(e => { if (e === dummy) return IO.pure(100) return IO.raise(e) }) const f = io.run(ec) ec.tick() assert.equal(f.value(), Some(Success(100))) }) it("recovers from user error in flatMap (runOnComplete)", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.pure(1).flatMap(() => { throw dummy }) .recoverWith(e => { if (e === dummy) return IO.pure(100) return IO.raise(e) }) let result: Option<Try<any>> = None io.runOnComplete(r => { result = Some(r) }, ec) ec.tick() assert.equal(result, Some(Success(100))) }) it("protects against user errors in recoverWith (run)", () => { const ec = scheduler() const dummy1 = new DummyError("dummy1") const dummy2 = new DummyError("dummy2") const io = IO.raise<number>(dummy1) .recoverWith(() => { throw dummy2 }) .recoverWith(() => { return IO.pure(100) // return IO.raise(e) }) const f = io.run(ec) ec.tick() assert.equal(f.value(), Some(Success(100))) }) it("protects against user errors in recoverWith (runOnComplete)", () => { const ec = scheduler() const dummy1 = new DummyError("dummy1") const dummy2 = new DummyError("dummy2") const io = IO.raise<number>(dummy1).recoverWith(() => { throw dummy2 }) .recoverWith(e => { if (e === dummy2) return IO.pure(100) return IO.raise(e) }) let result: Option<Try<any>> = None io.runOnComplete(r => { result = Some(r) }, ec) ec.tick() assert.equal(result, Some(Success(100))) }) it("recovers with recover", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.raise<number>(dummy).recover(e => e === dummy ? 10 : 0) const f = io.run(ec); ec.tick() assert.equal(f.value(), Some(Success(10))) }) it("recovers with transform", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.raise<number>(dummy).transform( e => e === dummy ? 10 : 0, v => v + 1 ) const f = io.run(ec); ec.tick() assert.equal(f.value(), Some(Success(10))) }) it("recovers with transformWith", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.raise<number>(dummy).transformWith( e => e === dummy ? IO.pure(10) : IO.raise(e), v => IO.pure(v + 1) ) const f = io.run(ec); ec.tick() assert.equal(f.value(), Some(Success(10))) }) it("returns Left on IO.raise", () => { const ec = scheduler() const dummy = new DummyError("dummy") const f = IO.raise(dummy).attempt().run(ec) assert.equal(f.value(), Some(Success(Left(dummy)))) }) it("returns Right on success", () => { const ec = scheduler() const f = IO.pure(1).attempt().run(ec) assert.equal(f.value(), Some(Success(Right(1)))) }) it("reports errors during async boundaries", () => { const ec = scheduler() const io = IO.asyncUnsafe((ctx, cb) => { cb(Failure("dummy1")) cb(Failure("dummy2")) cb(Success(1)) cb(Failure("dummy3")) }) const f = io.run(ec); ec.tick() assert.equal(f.value(), Some(Failure("dummy1"))) assert.equal(ec.triggeredFailures().length, 2) assert.equal(ec.triggeredFailures()[0], "dummy2") assert.equal(ec.triggeredFailures()[1], "dummy3") }) }) describe("IO.map", () => { it("works", () => { const ec = scheduler() const io = IO.pure(1).map(x => x + 1) assert.equal(io.run(ec).value(), Some(Success(2))) }) it("protects against user error", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.pure(1).map(() => { throw dummy }) assert.equal(io.run(ec).value(), Some(Failure(dummy))) }) it("does forEach", () => { const ec = scheduler() let effect = 0 const io = IO.pure(10).forEach(x => { effect += x }) assert.equal(effect, 0) io.run(ec); ec.tick() assert.equal(effect, 10) }) jv.property("map(f) <-> flatMap(x => pure(f(x)))", inst.arbIONum, jv.fun(jv.number), (fa, f) => { const ec = scheduler() const f1 = fa.map(f).run(ec) const f2 = fa.flatMap(x => IO.pure(f(x))).run(ec) ec.tick() return f1.value().equals(f2.value()) }) jv.property("map(f) <-> transform(_, f)", inst.arbIONum, jv.fun(jv.number), (fa, f) => { const ec = scheduler() const f1 = fa.map(f).run(ec) const f2 = fa.transform(e => { throw e }, f).run(ec) ec.tick() return f1.value().equals(f2.value()) }) }) describe("IO.tailRecM", () => { it("is stack safe", () => { const ec = scheduler() const fa = IO.tailRecM(0, a => IO.now(a < 1000 ? Left(a + 1) : Right(a))) const fu = fa.run(ec) ec.tick() assert.equal(fu.value(), Some(Success(1000))) }) it("returns the failure unchanged", () => { const ec = scheduler() const fa = IO.tailRecM(0, () => IO.raise("failure")) const fu = fa.run(ec) ec.tick() assert.equal(fu.value(), Some(Failure("failure"))) }) it("protects against user errors", () => { const ec = scheduler() // tslint:disable:no-string-throw const fa = IO.tailRecM(0, () => { throw "dummy" }) const fu = fa.run(ec) assert.equal(fu.value(), Some(Failure("dummy"))) }) }) describe("IO builders", () => { it("always repeats side effects", () => { const ec = scheduler() let effect = 0 const io = IO.always(() => { effect += 1; return effect }) const f1 = io.run(ec); ec.tick() assert.equal(f1.value(), Some(Success(1))) const f2 = io.run(ec); ec.tick() assert.equal(f2.value(), Some(Success(2))) }) it("always protects against user error", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.always(() => { throw dummy }) assert.equal(io.run(ec).value(), Some(Failure(dummy))) }) it("once does memoization", () => { const ec = scheduler() let effect = 0 const io = IO.once(() => { effect += 1; return effect }) const f1 = io.run(ec); ec.tick() assert.equal(f1.value(), Some(Success(1))) const f2 = io.run(ec); ec.tick() assert.equal(f2.value(), Some(Success(1))) }) it("once protects against user error", () => { const ec = scheduler() const dummy = new DummyError("dummy") const io = IO.once(() => { throw dummy }) assert.equal(io.run(ec).value(), Some(Failure(dummy))) }) it("IO.fromTry(Success(1)) <-> IO.pure(1)", () => { const ec = scheduler() assert.equal(IO.fromTry(Success(1)).run(ec).value(), Some(Success(1))) }) it("IO.fromTry(Failure(e)) <-> IO.raise(e)", () => { const ec = scheduler() assert.equal(IO.fromTry(Failure("error")).run(ec).value(), Some(Failure("error"))) }) it("converts fromFuture(Future.pure(v))", () => { const ec = scheduler() const f = IO.fromFuture(Future.pure(1)).run(ec) assert.equal(f.value(), Some(Success(1))) }) it("converts fromFuture(Future.raise(v))", () => { const ec = scheduler() const f = IO.fromFuture(Future.raise("error")).run(ec) assert.equal(f.value(), Some(Failure("error"))) }) it("converts deferFuture(() => Future.of(f))", () => { const ec = scheduler() let effect = 0 const f = IO.deferFuture(() => Future.of(() => { effect += 1; return 1 }, ec)).run(ec) ec.tick() assert.equal(f.value(), Some(Success(1))) assert.equal(effect, 1) }) it("converts deferFuture(() => Future.of(throw))", () => { const ec = scheduler() const dummy = new DummyError() let effect = 0 const f = IO.deferFuture(() => Future.of(() => { effect += 1; throw dummy }, ec)).run(ec) ec.tick() assert.equal(f.value(), Some(Failure(dummy))) assert.equal(effect, 1) }) it("converts deferFutureAction(() => Future.of(f))", () => { const ec = scheduler() let effect = 0 const f = IO.deferFutureAction(ec => Future.of(() => { effect += 1; return 1 }, ec)).run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(1))) assert.equal(effect, 1) }) it("converts deferFutureAction(() => Future.of(throw))", () => { const ec = scheduler() const dummy = new DummyError() let effect = 0 const f = IO.deferFutureAction(ec => Future.of(() => { effect += 1; throw dummy }, ec)).run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Failure(dummy))) assert.equal(effect, 1) }) it("deferAction", () => { const ec = scheduler() ec.tick(1000) assert.equal(ec.currentTimeMillis(), 1000) const f = IO.deferAction(ec => IO.pure(ec.currentTimeMillis())).run(ec) assert.equal(f.value(), Some(Success(1000))) }) it("deferAction protects against user error", () => { const ec = scheduler() const dummy = new DummyError() const f = IO.deferAction<number>(() => { throw dummy }).run(ec) assert.equal(f.value(), Some(Failure(dummy))) }) }) describe("IO aliases", () => { jv.property("chain(f) <-> flatMap(f)", inst.arbIONum, jv.fun(inst.arbIONum), (fa, f) => { const ec = scheduler() const f1 = fa.flatMap(f).run(ec) const f2 = fa.chain(f).run(ec) ec.tick() return f1.value().equals(f2.value()) }) jv.property("fa.followedBy(fb) <-> fa.flatMap(_ => fb)", inst.arbIONum, inst.arbIONum, (fa, fb) => { const ec = scheduler() const f1 = fa.followedBy(fb).run(ec) const f2 = fa.flatMap(() => fb).run(ec) ec.tick() return f1.value().equals(f2.value()) }) jv.property("fa.forEffect(fb) <-> fa.flatMap(a => fb.map(_ => a))", inst.arbIONum, inst.arbIONum, (fa, fb) => { const ec = scheduler() const f1 = fa.forEffect(fb).run(ec) const f2 = fa.flatMap(a => fb.map(() => a)).run(ec) ec.tick() return f1.value().equals(f2.value()) }) jv.property("of(f) <-> always(f)", jv.fun(jv.number), (f) => { const ec = scheduler() const f1 = IO.of(() => f(null)).run(ec) const f2 = IO.always(() => f(null)).run(ec) ec.tick() return f1.value().equals(f2.value()) }) jv.property("suspend(f) <-> unit.flatMap(_ => f())", inst.arbIONum, (fa) => { const ec = scheduler() const f1 = IO.suspend(() => fa).run(ec) const f2 = IO.unit().flatMap(() => fa).run(ec) ec.tick() return f1.value().equals(f2.value()) }) jv.property("defer(f) <-> unit.flatMap(_ => f())", inst.arbIONum, (fa) => { const ec = scheduler() const f1 = IO.defer(() => fa).run(ec) const f2 = IO.unit().flatMap(() => fa).run(ec) ec.tick() return f1.value().equals(f2.value()) }) }) describe("IO run-loop", () => { it("does processing in batches (run)", () => { const ec = scheduler().withExecutionModel(ExecutionModel.batched()) let effect = 0 const io = flatShallowLoop(1000, x => IO.of(() => { effect += 1 return x })) const f = io.run(ec) assert.equal(effect, 128) ec.tickOne() assert.equal(effect, 256) ec.tick() assert.equal(effect, 1001) assert.equal(f.value(), Some(Success(0))) }) it("does processing in batches (runOnComplete)", () => { const ec = scheduler().withExecutionModel(ExecutionModel.batched()) let effect = 0 const io = flatShallowLoop(1000, x => IO.of(() => { effect += 1 return x })) let result: Option<Try<any>> = None io.runOnComplete(r => { result = Some(r) }, ec) assert.equal(effect, 128) ec.tickOne() assert.equal(effect, 256) ec.tick() assert.equal(effect, 1001) assert.equal(result, Some(Success(0))) }) it("can be auto-cancelable (run)", () => { const ec = scheduler().withExecutionModel(ExecutionModel.batched()) let effect = 0 const io = flatShallowLoop(1000, x => IO.of(() => { effect += 1 return x })) const f = io .executeWithOptions({ autoCancelableRunLoops: true }) .run(ec) assert.equal(effect, 128) f.cancel() ec.tick() assert.equal(effect, 256) assert.not(ec.hasTasksLeft()) assert.equal(f.value(), None) }) it("can be auto-cancelable (runOnComplete)", () => { const ec = scheduler().withExecutionModel(ExecutionModel.batched()) let effect = 0 const io = flatShallowLoop(1000, x => IO.of(() => { effect += 1 return x })) let result: Option<Try<any>> = None const c = io .executeWithOptions({ autoCancelableRunLoops: true }) .runOnComplete((r: any) => { result = r }, ec) assert.equal(effect, 128) c.cancel() ec.tick() assert.equal(effect, 256) assert.not(ec.hasTasksLeft()) assert.equal(result, None) }) it("can auto-cancel at any async boundary (run)", () => { const ec = scheduler() const io = IO.asyncUnsafe<number>((ctx, cb) => { ctx.scheduler.executeAsync(() => cb(Success(1))) }) const f = io.flatMap(() => io).executeWithOptions({ autoCancelableRunLoops: true }).run(ec) f.cancel() assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), None) assert.not(ec.hasTasksLeft()) }) it("can auto-cancel at any async boundary (runOnComplete)", () => { const ec = scheduler() const io = IO.asyncUnsafe<number>((ctx, cb) => { ctx.scheduler.executeAsync(() => cb(Success(1))) }) let result: Option<Try<any>> = None const c = io .executeWithOptions({ autoCancelableRunLoops: true }) .runOnComplete(r => { result = Some(r) }) c.cancel() ec.tick() assert.equal(result, None) assert.not(ec.hasTasksLeft()) }) it("process pure(n).map(f) in alwaysAsync mode (run)", () => { const ec = scheduler().withExecutionModel(ExecutionModel.alwaysAsync()) const f = IO.pure(1).map(x => x + 1).run(ec) assert.equal(f.value(), None); ec.tickOne() assert.equal(f.value(), Some(Success(2))) }) it("process pure(n).map(f) in alwaysAsync mode (runOnComplete)", () => { const ec = scheduler().withExecutionModel(ExecutionModel.alwaysAsync()) let result: Option<Try<any>> = None IO.pure(1).map(x => x + 1).runOnComplete(r => { result = Some(r) }, ec) assert.equal(result, None); ec.tickOne() assert.equal(result, Some(Success(2))) }) it("can process in alwaysAsync mode (run)", () => { const ec = scheduler().withExecutionModel(ExecutionModel.alwaysAsync()) let effect = 0 const io = flatShallowLoop(1000, x => IO.of(() => { effect += 1 return x })) const f = io.run(ec) assert.equal(effect, 1) ec.tickOne() assert.equal(effect, 2) ec.tickOne() assert.equal(effect, 3) ec.tick() assert.equal(effect, 1001) assert.equal(f.value(), Some(Success(0))) }) it("can process in alwaysAsync mode (runOnComplete)", () => { const ec = scheduler().withExecutionModel(ExecutionModel.alwaysAsync()) let effect = 0 const io = flatShallowLoop(1000, x => IO.of(() => { effect += 1 return x })) let result: Option<Try<any>> = None io.runOnComplete(r => { result = Some(r) }, ec) assert.equal(effect, 1) ec.tickOne() assert.equal(effect, 2) ec.tickOne() assert.equal(effect, 3) ec.tick() assert.equal(effect, 1001) assert.equal(result, Some(Success(0))) }) it("can mark async boundary (run)", () => { const asyncEC = scheduler() function signal(n: number): IO<number> { return IO.asyncUnsafe<number>((ctx, cb) => { asyncEC.executeAsync(() => { ctx.markAsyncBoundary() cb(Success(n)) }) }) } const ec1 = scheduler().withExecutionModel(ExecutionModel.batched()) const f1 = Future.unit(ec1).flatMap(Future.pure) .flatMap(() => IO.pure(1).flatMap(IO.pure).run(ec1)) .map(() => ec1.batchIndex) ec1.tick() asyncEC.tick() assert.equal(f1.value(), Some(Success(4))) const ec2 = scheduler() const f2 = Future.unit(ec2).flatMap(Future.pure) .flatMap(() => IO.pure(1).flatMap(signal).run(ec2)) .map(() => ec2.batchIndex) ec2.tick() asyncEC.tick() assert.equal(f2.value(), Some(Success(0))) }) it("can override the execution model", () => { const ec = scheduler() const f = IO.pure(1).map(x => x + 1) .executeWithModel(ExecutionModel.alwaysAsync()) .run(ec) assert.equal(f.value(), None); ec.tick() assert.equal(f.value(), Some(Success(2))) }) }) describe("IO.memoize", () => { it("works for subsequent subscribers after finish", () => { const ec = scheduler() let effect = 0 const io = IO .suspend(() => { effect += 1; return IO.pure(effect) }) .memoize() const f1 = io.run(ec) assert.equal(f1.value(), Some(Success(1))) const f2 = io.run(ec) assert.equal(f2.value(), Some(Success(1))) const f3 = io.run(ec) assert.equal(f3.value(), Some(Success(1))) }) it("works for subsequent subscribers during processing", () => { const ec = scheduler() let effect = 0 const io = IO .deferFuture(() => Future.of(() => { effect += 1; return effect }, ec)) .map(_ => _ + 1) .memoize() .map(_ => _ + 1) const f1 = io.run(ec) const f2 = io.run(ec) const f3 = io.run(ec) assert.equal(f1.value(), None) assert.equal(f2.value(), None) assert.equal(f3.value(), None) ec.tick() assert.equal(f1.value(), Some(Success(3))) assert.equal(f2.value(), Some(Success(3))) assert.equal(f3.value(), Some(Success(3))) const f4 = io.run(ec) assert.equal(f4.value(), Some(Success(3))) }) it("caches failures", () => { const ec = scheduler() let effect = 0 const io = IO .defer(() => { effect += 1; return IO.raise(effect) }) .memoize() const f1 = io.run(ec) assert.equal(f1.value(), Some(Failure(1))) const f2 = io.run(ec) assert.equal(f2.value(), Some(Failure(1))) const f3 = io.run(ec) assert.equal(f3.value(), Some(Failure(1))) }) jv.property("returns same reference on double call", inst.arbIONum, fa => { const mem = fa.memoize() return mem === mem.memoize() }) it("memoizes IO.always", () => { const ec = scheduler() let effect = 0 const io = IO .always(() => { effect += 1; return effect }) .memoize() assert.equal(io._tag, "once") assert.equal(io.run(ec).value(), Some(Success(1))) assert.equal(io.run(ec).value(), Some(Success(1))) }) it("returns same reference on IO.once", () => { const io = IO.once(() => 1) assert.equal(io.memoize(), io) }) it("memoizes errors for IO.always(f).memoizeOnSuccess().memoize()", () => { const ec = scheduler() const dummy = new DummyError() let effect = 0 const io = IO .always(() => { effect += 1; throw dummy }) .memoizeOnSuccess() const io2 = io.memoize() assert.notEqual(io, io2) assert.equal(io2._tag, "once") assert.equal(io2.run(ec).value(), Some(Failure(dummy))) assert.equal(effect, 1) assert.equal(io2.run(ec).value(), Some(Failure(dummy))) assert.equal(effect, 1) }) it("memoizes errors for IO.async().memoizeOnSuccess().memoize()", () => { const ec = scheduler() const dummy = new DummyError() let effect = 0 const io = IO .async((ec, cb) => { effect += 1; cb(Failure(dummy)) }) .memoizeOnSuccess() const io2 = io.memoize() assert.equal(io._tag, "memoize") assert.equal(io2._tag, "memoize") assert.notEqual(io, io2) const f1 = io2.run(ec); ec.tick() assert.equal(f1.value(), Some(Failure(dummy))) assert.equal(effect, 1) const f2 = io2.run(ec); ec.tick() assert.equal(f2.value(), Some(Failure(dummy))) assert.equal(effect, 1) }) }) describe("IO.memoizeOnSuccess", () => { it("returns same reference for IO.pure", () => { const io = IO.pure(1) assert.equal(io.memoizeOnSuccess(), io) }) it("returns same reference for IO.raise", () => { const io = IO.raise("error") assert.equal(io.memoizeOnSuccess(), io) }) it("returns same reference for IO.once(f)", () => { const io = IO.once(() => 1) assert.equal(io.memoizeOnSuccess(), io) }) it("repeats processing of IO.always on error", () => { let effect = 0 const dummy = new DummyError() const io = IO .always(() => { effect += 1; throw dummy }) .memoizeOnSuccess() const f1 = io.run() assert.equal(f1.value(), Some(Failure(dummy))) assert.equal(effect, 1) const f2 = io.run() assert.equal(f2.value(), Some(Failure(dummy))) assert.equal(effect, 2) const f3 = io.run() assert.equal(f3.value(), Some(Failure(dummy))) assert.equal(effect, 3) }) it("memoizes IO.always", () => { const ec = scheduler() let effect = 0 const io = IO .always(() => { effect += 1; return effect }) .memoizeOnSuccess() assert.equal(io._tag, "once") assert.equal(io.run(ec).value(), Some(Success(1))) assert.equal(io.run(ec).value(), Some(Success(1))) }) jv.property("returns same reference on double call", inst.arbIONum, fa => { const mem = fa.memoizeOnSuccess() return mem === mem.memoizeOnSuccess() }) jv.property("returns same reference after memoize()", inst.arbIONum, fa => { const mem = fa.memoize() return mem === mem.memoizeOnSuccess() }) it("works for subsequent subscribers after finish", () => { const ec = scheduler() let effect = 0 const io = IO .suspend(() => { effect += 1; return IO.pure(effect) }) .memoizeOnSuccess() const f1 = io.run(ec) assert.equal(f1.value(), Some(Success(1))) const f2 = io.run(ec) assert.equal(f2.value(), Some(Success(1))) const f3 = io.run(ec) assert.equal(f3.value(), Some(Success(1))) }) it("works for subsequent subscribers during processing", () => { const ec = scheduler() let effect = 0 const io = IO .deferFuture(() => Future.of(() => { effect += 1; return effect }, ec)) .map(_ => _ + 1) .memoizeOnSuccess() .map(_ => _ + 1) const f1 = io.run(ec) const f2 = io.run(ec) const f3 = io.run(ec) assert.equal(f1.value(), None) assert.equal(f2.value(), None) assert.equal(f3.value(), None) ec.tick() assert.equal(f1.value(), Some(Success(3))) assert.equal(f2.value(), Some(Success(3))) assert.equal(f3.value(), Some(Success(3))) const f4 = io.run(ec) assert.equal(f4.value(), Some(Success(3))) }) it("does not caches failures", () => { const ec = scheduler() let effect = 0 const io = IO .defer(() => { effect += 1; return IO.raise(effect) }) .memoizeOnSuccess() const f1 = io.run(ec); ec.tick() assert.equal(f1.value(), Some(Failure(1))) const f2 = io.run(ec); ec.tick() assert.equal(f2.value(), Some(Failure(2))) const f3 = io.run(ec); ec.tick() assert.equal(f3.value(), Some(Failure(3))) }) it("does not cache failures for async IOs", () => { const ec = scheduler() let effect = 0 const io = IO .async((ec, cb) => ec.executeAsync(() => { effect += 1 if (effect < 3) cb(Failure(effect)) else cb(Success(effect)) })) .memoizeOnSuccess() const f1 = io.run(ec); ec.tick() assert.equal(f1.value(), Some(Failure(1))) const f2 = io.run(ec); ec.tick() assert.equal(f2.value(), Some(Failure(2))) const f3 = io.run(ec); ec.tick() assert.equal(f3.value(), Some(Success(3))) const f4 = io.run(ec); ec.tick() assert.equal(f4.value(), Some(Success(3))) }) }) describe("IO.shift", () => { it("can shift before evaluation", () => { const ec = scheduler() let effect = 0 const io = IO.of(() => { effect += 1; return effect }) .executeForked() const f = io.run(ec) assert.equal(effect, 0) assert.equal(f.value(), None) ec.tickOne() assert.equal(f.value(), Some(Success(1))) }) it("fa.executeForked <-> IO.fork(fa)", () => { const ec = scheduler() let effect = 0 const io = IO.fork(IO.of(() => { effect += 1; return effect })) const f = io.run(ec) assert.equal(effect, 0) assert.equal(f.value(), None) ec.tickOne() assert.equal(f.value(), Some(Success(1))) }) it("can do fork for real", () => { let effect = 0 const io = IO.of(() => { effect += 1; return effect }) .executeForked() .run() return io.then(value => { assert.equal(value, 1) }) }) it("can shift after evaluation", () => { const ec = scheduler() let effect = 0 const io = IO.of(() => { effect += 1; return effect }) .asyncBoundary(ec) const f = io.run(ec) assert.equal(effect, 1) assert.equal(f.value(), None) ec.tickOne() assert.equal(f.value(), Some(Success(1))) }) it("can do async boundary for real", () => { let effect = 0 const io = IO.of(() => { effect += 1; return effect }) .asyncBoundary() .run() return io.then(value => { assert.equal(value, 1) }) }) }) describe("IO.sequence", () => { it("works", () => { const ec = scheduler() const all = [IO.pure(1), IO.pure(2), IO.pure(3)] const io = IO.sequence(all).map(lst => { let sum = 0 for (let i = 0; i < lst.length; i++) sum += lst[i] return sum }) assert.equal(io.run(ec).value(), Some(Success(6))) }) it("map2", () => { const ec = scheduler() const f = IO.map2( IO.pure(1), IO.pure(2), (a, b) => a + b ) assert.equal(f.run(ec).value(), Some(Success(3))) }) it("map3", () => { const ec = scheduler() const f = IO.map3( IO.pure(1), IO.pure(2), IO.pure(3), (a, b, c) => a + b + c ) assert.equal(f.run(ec).value(), Some(Success(6))) }) it("map4", () => { const ec = scheduler() const f = IO.map4( IO.pure(1), IO.pure(2), IO.pure(3), IO.pure(4), (a, b, c, d) => a + b + c + d ) assert.equal(f.run(ec).value(), Some(Success(10))) }) it("map5", () => { const ec = scheduler() const f = IO.map5( IO.pure(1), IO.pure(2), IO.pure(3), IO.pure(4), IO.pure(5), (a, b, c, d, e) => a + b + c + d + e ) assert.equal(f.run(ec).value(), Some(Success(15))) }) it("map6", () => { const ec = scheduler() const f = IO.map6( IO.pure(1), IO.pure(2), IO.pure(3), IO.pure(4), IO.pure(5), IO.pure(6), (a, b, c, d, e, f) => a + b + c + d + e + f ) assert.equal(f.run(ec).value(), Some(Success(21))) }) it("works with null list", () => { const ec = scheduler() assert.equal(IO.sequence(null as any).map(x => x.toString()).run(ec).value(), Some(Success(""))) }) it("works with empty list", () => { const ec = scheduler() assert.equal(IO.sequence([]).map(x => x.toString()).run(ec).value(), Some(Success(""))) }) it("works with any iterable", () => { const ec = scheduler() const iter = { [Symbol.iterator]: () => { let done = false return { next: () => { if (!done) { done = true return { done: false, value: IO.pure(1) } } else { return { done: true } } } } } } const seq = IO.sequence(iter as any).map(_ => _[0]).run(ec) assert.equal(seq.value(), Some(Success(1))) }) it("protects against broken iterables", () => { const ec = scheduler() const dummy = new DummyError() const iter = { [Symbol.iterator]: () => { throw dummy } } const seq = IO.sequence(iter as any).run(ec) assert.equal(seq.value(), Some(Failure(dummy))) }) it("executes sequentially", () => { const ec = scheduler() const list = [ IO.pure(1).delayExecution(3000), IO.pure(1).delayExecution(1000), IO.pure(1).delayExecution(2000) ] const all = IO.sequence(list).map(_ => _.toString()).run(ec) ec.tick(3000) assert.equal(all.value(), None) ec.tick(3000) assert.equal(all.value(), Some(Success("1,1,1"))) }) it("cancels everything on cancel", () => { const ec = scheduler() const list = [ IO.pure(1).delayExecution(3000), IO.pure(1).delayExecution(1000), IO.pure(1).delayExecution(2000) ] const all = IO.sequence(list).map(_ => _.toString()).run(ec) assert.ok(ec.hasTasksLeft()) all.cancel() assert.not(ec.hasTasksLeft()) }) it("cancels everything on failure", () => { const ec = scheduler() const list = [ IO.pure(1).delayExecution(2000), IO.raise("error").delayExecution(1000), IO.pure(1).delayExecution(2000) ] const all = IO.sequence(list).map(_ => _.toString()).run(ec) assert.ok(ec.hasTasksLeft()) ec.tick(3000) assert.equal(all.value(), Some(Failure("error"))) assert.not(ec.hasTasksLeft()) }) }) describe("IO.gather", () => { it("works", () => { const ec = scheduler() const all = [IO.pure(1), IO.pure(2), IO.pure(3)] const io = IO.gather(all).map(lst => { let sum = 0 for (let i = 0; i < lst.length; i++) sum += lst[i] return sum }) assert.equal(io.run(ec).value(), Some(Success(6))) }) it("parMap2", () => { const ec = scheduler() const f = IO.parMap2( IO.pure(1), IO.pure(2), (a, b) => a + b ) assert.equal(f.run(ec).value(), Some(Success(3))) }) it("parMap3", () => { const ec = scheduler() const f = IO.parMap3( IO.pure(1), IO.pure(2), IO.pure(3), (a, b, c) => a + b + c ) assert.equal(f.run(ec).value(), Some(Success(6))) }) it("parMap4", () => { const ec = scheduler() const f = IO.parMap4( IO.pure(1), IO.pure(2), IO.pure(3), IO.pure(4), (a, b, c, d) => a + b + c + d ) assert.equal(f.run(ec).value(), Some(Success(10))) }) it("parMap5", () => { const ec = scheduler() const f = IO.parMap5( IO.pure(1), IO.pure(2), IO.pure(3), IO.pure(4), IO.pure(5), (a, b, c, d, e) => a + b + c + d + e ) assert.equal(f.run(ec).value(), Some(Success(15))) }) it("parMap6", () => { const ec = scheduler() const f = IO.parMap6( IO.pure(1), IO.pure(2), IO.pure(3), IO.pure(4), IO.pure(5), IO.pure(6), (a, b, c, d, e, f) => a + b + c + d + e + f ) assert.equal(f.run(ec).value(), Some(Success(21))) }) it("works with empty list", () => { const ec = scheduler() assert.equal(IO.gather([]).map(x => x.toString()).run(ec).value(), Some(Success(""))) }) it("works with null list", () => { const ec = scheduler() assert.equal(IO.gather(null as any).map(x => x.toString()).run(ec).value(), Some(Success(""))) }) it("works with any iterable", () => { const ec = scheduler() const iter = { [Symbol.iterator]: () => { let done = false return { next: () => { if (!done) { done = true return { done: false, value: IO.pure(1) } } else { return { done: true } } } } } } const seq = IO.gather(iter as any).map(_ => _[0]).run(ec) assert.equal(seq.value(), Some(Success(1))) }) it("protects against broken iterables", () => { const ec = scheduler() const dummy = new DummyError() const iter = { [Symbol.iterator]: () => { throw dummy } } const seq = IO.gather(iter as any).run(ec) assert.equal(seq.value(), Some(Failure(dummy))) }) it("executes in parallel", () => { const ec = scheduler() const list = [ IO.pure(1).delayExecution(3000), IO.pure(1).delayExecution(1000), IO.pure(1).delayExecution(2000) ] const all = IO.gather(list).map(_ => _.toString()).run(ec) ec.tick(3000) assert.equal(all.value(), Some(Success("1,1,1"))) }) it("cancels everything on cancel", () => { const ec = scheduler() const list = [ IO.pure(1).delayExecution(3000), IO.pure(1).delayExecution(1000), IO.pure(1).delayExecution(2000) ] const all = IO.gather(list).map(_ => _.toString()).run(ec) assert.ok(ec.hasTasksLeft()) all.cancel() assert.not(ec.hasTasksLeft()) }) it("cancels everything on failure", () => { const ec = scheduler() const list = [ IO.pure(1).delayExecution(2000), IO.raise("error").delayExecution(1000), IO.pure(1).delayExecution(4000) ] const all = IO.gather(list).map(_ => _.toString()).run(ec) assert.ok(ec.hasTasksLeft()) ec.tick(1000) assert.equal(all.value(), Some(Failure("error"))) assert.not(ec.hasTasksLeft()) }) }) describe("IO delay", () => { it("delayResult works for successful values", () => { const s = new TestScheduler() let effect = 0 const f = IO.of(() => { effect += 1; return effect }).delayResult(1000).run(s) assert.equal(effect, 1) assert.equal(f.value(), None) s.tick(1000) assert.equal(f.value(), Some(Success(1))) }) it("delayResult works for failures", () => { const s = new TestScheduler() const dummy = new DummyError("dummy") const f = IO.raise(dummy).delayResult(1000).run(s) assert.equal(f.value(), None) s.tick(1000) assert.equal(f.value(), Some(Failure(dummy))) }) it("delayExecution works", () => { const s = new TestScheduler() let effect = 0 const f = IO.of(() => { effect += 1; return effect }).delayExecution(1000).run(s) assert.equal(effect, 0) assert.equal(f.value(), None) s.tick(1000) assert.equal(f.value(), Some(Success(1))) }) }) describe("IO.doOnFinish", () => { it("works for success", () => { const ec = new TestScheduler() let effect = 0 const io = IO.of(() => 1).doOnFinish(e => IO.of(() => { if (e.isEmpty()) effect += 1 })) assert.equal(io.run(ec).value(), Some(Success(1))) assert.equal(effect, 1) }) it("works for failure", () => { const ec = new TestScheduler() const dummy = new DummyError() let effect = 0 const io = IO.raise<number>(dummy).doOnFinish(e => IO.of(() => { if (e.nonEmpty() && e.get() === dummy) effect += 1 })) assert.equal(io.run(ec).value(), Some(Failure(dummy))) assert.equal(effect, 1) }) }) describe("IO.doOnCancel", () => { it("does not trigger anything on success", () => { const ec = new TestScheduler() let effect = 0 const io = IO.of(() => 1).doOnCancel(IO.of(() => { effect += 1 })) assert.equal(io.run(ec).value(), Some(Success(1))) assert.equal(effect, 0) }) it("does not trigger anything on failure", () => { const ec = new TestScheduler() const dummy = new DummyError() let effect = 0 const io = IO.raise<number>(dummy).doOnCancel(IO.of(() => { effect += 1 })) assert.equal(io.run(ec).value(), Some(Failure(dummy))) assert.equal(effect, 0) }) it("triggers effect on cancellation", () => { const ec = new TestScheduler() let effect = 0 const io = IO.pure(1).delayExecution(1000) .doOnCancel(IO.of(() => { effect += 1 })) const f = io.run(ec) assert.equal(f.value(), None) f.cancel(); ec.tick() assert.equal(effect, 1) assert.not(ec.hasTasksLeft()) }) }) describe("IO.firstCompletedOf", () => { it("picks the winner and cancels the rest", () => { const ec = new TestScheduler() let effect = 0 const all = IO.firstCompletedOf([ IO.pure(1).delayExecution(2000).doOnCancel(IO.of(() => { effect += 1 })), IO.pure(2).delayExecution(1000).doOnCancel(IO.of(() => { effect += 1 })), IO.pure(3).delayExecution(3000).doOnCancel(IO.of(() => { effect += 1 })) ]) const f = all.run(ec) ec.tick(1000) assert.equal(f.value(), Some(Success(2))) assert.equal(effect, 2) assert.not(ec.hasTasksLeft()) }) it("throws error on empty list", () => { const ec = scheduler() const f = IO.firstCompletedOf([]).map(x => x.toString()).run(ec) assert.ok(f.value().nonEmpty() && f.value().get().isFailure()) }) it("throws error on null list", () => { const ec = scheduler() const f = IO.firstCompletedOf(null as any).map(x => x.toString()).run(ec) assert.ok(f.value().nonEmpty() && f.value().get().isFailure()) }) it("works with any iterable", () => { const ec = scheduler() const iter = { [Symbol.iterator]: () => { let done = false return { next: () => { if (!done) { done = true return { done: false, value: IO.pure(1) } } else { return { done: true } } } } } } const seq = IO.firstCompletedOf(iter as any).run(ec) assert.equal(seq.value(), Some(Success(1))) }) it("protects against broken iterables", () => { const ec = scheduler() const dummy = new DummyError() const iter = { [Symbol.iterator]: () => { throw dummy } } const seq = IO.firstCompletedOf(iter as any).run(ec) assert.equal(seq.value(), Some(Failure(dummy))) }) it("mirrors the source on .timeout", () => { const ec = scheduler() const io = IO.pure(1).timeout(1000) assert.equal(io.run(ec).value(), Some(Success(1))) }) it("triggers error when timespan exceeded", () => { const ec = scheduler() const io = IO.pure(1).delayExecution(10000).timeout(1000) const f = io.run(ec) ec.tick(1000) assert.ok(!f.value().isEmpty() && f.value().get().isFailure()) }) it("cancels both on cancel", () => { const ec = scheduler() const io = IO.pure(1).delayExecution(10000).timeout(1000) const f = io.run(ec) assert.ok(ec.hasTasksLeft()) f.cancel() assert.not(ec.hasTasksLeft()) }) }) describe("IO type classes", () => { function check(ec: TestScheduler): <A>(eq: Equiv<HK<"funfix/io", A>>) => boolean { return eq => { const a = (eq.lh as IO<any>).run(ec) const b = (eq.rh as IO<any>).run(ec) ec.tick(Duration.days(99)) return is(a.value(), b.value()) } } describe("Monad<IO> (static-land)", () => { const sc = new TestScheduler() const arbFA = inst.arbIO(jv.int32) const arbFB = inst.arbIO(jv.string) const arbFC = inst.arbIO(jv.int16) const arbFAtoB = inst.arbIO(jv.fun(jv.string)) const arbFBtoC = inst.arbIO(jv.fun(jv.int16)) monadCheck( arbFA, arbFB, arbFC, jv.fun(jv.string), jv.fun(jv.int16), arbFAtoB, arbFBtoC, jv.int32, check(sc), IOModule) }) describe("Functor<IO> (fantasy-land)", () => { const sc = new TestScheduler() const arbFA = inst.arbIO(jv.int32) const arbFB = inst.arbIO(jv.string) const arbFC = inst.arbIO(jv.int16) const arbFAtoB = inst.arbIO(jv.fun(jv.string)) const arbFBtoC = inst.arbIO(jv.fun(jv.int16)) monadCheck( arbFA, arbFB, arbFC, jv.fun(jv.string), jv.fun(jv.int16), arbFAtoB, arbFBtoC, jv.int32, check(sc), { map: (f, fa) => (fa as any)["fantasy-land/map"](f), ap: (ff, fa) => (fa as any)["fantasy-land/ap"](ff), chain: (f, fa) => (fa as any)["fantasy-land/chain"](f), chainRec: (f, a) => (IO as any)["fantasy-land/chainRec"](f, a), of: a => (IO as any)["fantasy-land/of"](a) }) }) }) function scheduler(): TestScheduler { return new TestScheduler(undefined, ExecutionModel.global.get()) } function flatShallowLoop(n: number, f: (x: number) => IO<number>): IO<number> { return f(n).flatMap(n => { if (n <= 0) return IO.pure(n) return flatShallowLoop(n - 1, f) }) } function flatEagerLoop(n: number, f: (x: number) => IO<number>): IO<number> { let cursor = f(n) for (let i = n - 1; i >= 0; i--) cursor = cursor.flatMap(x => f(x - 1)) return cursor } function suspendLoop(n: number, f: (x: number) => IO<number>): IO<number> { return IO.suspend(() => { if (n <= 0) return IO.pure(n) return suspendLoop(n - 1, f) }) }
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 { BeginDrillThroughEventArgs } from '../../src/common/base/interface'; import { CalculatedField } from '../../src/common/calculatedfield/calculated-field'; import { Grid } from '@syncfusion/ej2-grids'; import { DrillThrough } from '../../src/pivotview/actions'; import { profile, inMB, getMemoryProfile } from '../common.spec'; describe('- Editing', () => { 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('- normal', () => { let originalTimeout: number; let pivotGridObj: PivotView; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:200px; width:500px' }); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000; if (!document.getElementById(elem.id)) { document.body.appendChild(elem); } let dataBound: EmitType<Object> = () => { done(); }; PivotView.Inject(GroupingBar, DrillThrough, CalculatedField); pivotGridObj = new PivotView({ dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], calculatedFieldSettings: [{ name: 'price', formula: '(("Sum(balance)"*10^3+"Count(quantity)")/100)+"Sum(balance)"' }], rows: [{ name: 'product' }, { name: 'state' }], columns: [{ name: 'gender' }], values: [{ name: 'balance' }, { name: 'price' }, { name: 'quantity' }], filters: [{ name: 'index' }], drilledMembers: [{ name: 'product', items: ['Flight'] }], allowValueFilter: true, allowLabelFilter: true }, height: 300, width: 800, allowDrillThrough: true, editSettings: { allowAdding: true, allowDeleting: true, allowEditing: true, showConfirmDialog: false, showDeleteConfirmDialog: false, allowCommandColumns: false, mode: 'Normal' }, beginDrillThrough: (args: BeginDrillThroughEventArgs) => { if (args.gridObj) { let eventType: string = args.type; let gridObj: Grid = args.gridObj; gridObj.allowKeyboard = false; } }, showGroupingBar: true, dataBound: dataBound, }); pivotGridObj.appendTo('#PivotGrid'); }); beforeEach((done: Function) => { setTimeout(() => { done(); }, 2000); }); let event: MouseEvent = new MouseEvent('dblclick', { 'view': window, 'bubbles': true, 'cancelable': true }); let mouseup: MouseEvent = new MouseEvent('mouseup', { 'view': window, 'bubbles': true, 'cancelable': true }); let mousedown: MouseEvent = new MouseEvent('mousedown', { 'view': window, 'bubbles': true, 'cancelable': true }); let click: MouseEvent = new MouseEvent('click', { 'view': window, 'bubbles': true, 'cancelable': true }); it('render testing', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; expect(document.querySelectorAll('.e-pivot-button').length).toBe(7); }); it('click bike-female-balance', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; document.querySelectorAll('td[aria-colindex="1"]')[0].dispatchEvent(event); setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid .e-groupdroparea')).toBeTruthy(); document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].dispatchEvent(event); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[0].dispatchEvent(mouseup); expect(document.querySelectorAll('.e-drillthrough-grid .e-numeric input')[0].getAttribute('aria-valuenow')).toBe("19"); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[3].dispatchEvent(click); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('click california-quantity-female', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; expect(document.querySelectorAll('td[aria-colindex="3"]')[0].textContent).toBe("477"); document.querySelectorAll('td[aria-colindex="3"]')[3].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].dispatchEvent(event); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[1].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[1].dispatchEvent(mouseup); expect(document.querySelectorAll('.e-drillthrough-grid .e-numeric input')[0].getAttribute('aria-valuenow')).toBe("19"); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[3].dispatchEvent(click); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('remove tamilnadu single', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; expect(document.querySelectorAll('td[aria-colindex="3"]')[3].textContent).toBe("66"); document.querySelectorAll('td[aria-colindex="3"]')[7].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid tr')[2].querySelector('td').dispatchEvent(click); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[2].dispatchEvent(click); done(); }, 2000); }); it('remove tamilnadu single check', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].textContent).toBe("12"); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('remove tamilnadu full', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; expect(document.querySelectorAll('td[aria-colindex="3"]')[7].textContent).toBe("12"); document.querySelectorAll('td[aria-colindex="3"]')[7].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid tr')[2].querySelector('td').dispatchEvent(click); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[2].dispatchEvent(click); done(); }, 2000); }); it('remove tamilnadu full check', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid tr')[2].textContent).toBe("No records to display"); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('add tamilnadu', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; expect(document.querySelectorAll('td[aria-colindex="3"]')[7].textContent).toBe(""); document.querySelectorAll('td[aria-colindex="3"]')[7].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[0].dispatchEvent(click); done(); }, 2000); }); it('add tamilnadu 1', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelectorAll('.e-drillthrough-grid .e-inline-edit .e-input')[0] as HTMLInputElement).value = "Tamilnadu"; (document.querySelectorAll('.e-drillthrough-grid .e-inline-edit .e-input')[1] as HTMLInputElement).value = "Flight"; (document.querySelectorAll('.e-drillthrough-grid .e-inline-edit .e-input')[2] as HTMLInputElement).value = "female"; document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[1].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[1].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[3].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[3].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[5].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[5].dispatchEvent(mouseup); done(); }, 2000); }); it('add tamilnadu check', (done: Function) => { ///jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid .e-numeric input')[0].getAttribute('aria-valuenow')).toBe("1"); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[3].dispatchEvent(click); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('batch mode', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { pivotGridObj.editSettings.mode = 'Batch'; pivotGridObj.editSettings.showConfirmDialog = false; pivotGridObj.editSettings.showDeleteConfirmDialog = false; pivotGridObj.dataSourceSettings.dataSource = pivot_dataset as IDataSet[]; pivotGridObj.refresh(); done(); }, 2000); }); it('batch click bike-female-balance', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; document.querySelectorAll('td[aria-colindex="1"]')[0].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].dispatchEvent(event); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[0].dispatchEvent(mouseup); done(); }, 2000); }); it('batch click bike-female-balance check', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid .e-numeric input')[0].getAttribute('aria-valuenow')).toBe("18"); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[2].dispatchEvent(click); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[2].dispatchEvent(click); done(); }, 2000); }); it('dummy', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(true).toBe(true); done(); }, 2000); }); it('batch click california-quantity-female', (done: Function) => { expect(document.querySelectorAll('td[aria-colindex="3"]')[0].textContent).toBe("476"); document.querySelectorAll('td[aria-colindex="3"]')[3].dispatchEvent(event); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].dispatchEvent(event); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[1].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-numeric span')[1].dispatchEvent(mouseup); done(); }, 2000); }); it('batch click california-quantity-female', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid .e-numeric input')[0].getAttribute('aria-valuenow')).toBe("20"); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[2].dispatchEvent(click); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[2].dispatchEvent(click); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('batch remove tamilnadu single', (done: Function) => { ///jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; document.querySelectorAll('td[aria-colindex="3"]')[7].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid tr')[2].querySelector('td').dispatchEvent(click); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[1].dispatchEvent(click); document.querySelectorAll('.e-drillthrough-grid .e-tbar-btn')[2].dispatchEvent(click); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('dialogmode', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { pivotGridObj.editSettings.mode = 'Dialog'; pivotGridObj.dataSourceSettings.dataSource = pivot_dataset as IDataSet[]; pivotGridObj.refresh(); done(); }, 2000); }); it('dialog click bike-female-balance', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; document.querySelectorAll('td[aria-colindex="1"]')[0].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].dispatchEvent(event); document.querySelectorAll('.e-spin-down')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-spin-down')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-edit-dialog button.e-primary')[0].dispatchEvent(click); done(); }, 2000); }); it('dialog click bike-female-balance check', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].textContent).toBe("17"); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('dialog click california-quantity-female', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; expect(document.querySelectorAll('td[aria-colindex="3"]')[0].textContent).toBe("475"); document.querySelectorAll('td[aria-colindex="3"]')[3].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].dispatchEvent(event); document.querySelectorAll('.e-spin-up')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-spin-up')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-edit-dialog button.e-primary')[0].dispatchEvent(click); done(); }, 2000); }); it('dialog click california-quantity-female', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].textContent).toBe("21"); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('command columns mode', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { pivotGridObj.editSettings.allowCommandColumns = true; pivotGridObj.dataSourceSettings.dataSource = pivot_dataset as IDataSet[]; pivotGridObj.refresh(); done(); }, 2000); }); it('cc click bike-female-balance', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; document.querySelectorAll('td[aria-colindex="1"]')[0].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-editbutton')[0].dispatchEvent(click); done(); }, 2000); }); it('cc click bike-female-balance save', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-savebutton')[2].dispatchEvent(click); done(); }, 2000); }); it('cc click bike-female-balance check', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].textContent).toBe("16"); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('cc click california-quantity-female', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; expect(document.querySelectorAll('td[aria-colindex="3"]')[0].textContent).toBe("474"); document.querySelectorAll('td[aria-colindex="3"]')[3].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-editbutton')[0].dispatchEvent(click); done(); }, 2000); }); it('cc click california-quantity-female save', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-savebutton')[2].dispatchEvent(click); done(); }, 2000); }); it('cc click california-quantity-female check', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].textContent).toBe("22"); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('cc click bike-female-balance', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; document.querySelectorAll('td[aria-colindex="1"]')[0].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-editbutton')[0].dispatchEvent(click); done(); }, 2000); }); it('cc click bike-female-balance save', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-up')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-savebutton')[2].dispatchEvent(click); done(); }, 2000); }); it('cc click bike-female-balance check', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].textContent).toBe("20"); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('cc click california-quantity-female', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; document.querySelectorAll('td[aria-colindex="3"]')[3].dispatchEvent(event); setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-editbutton')[0].dispatchEvent(click); done(); }, 2000); }); it('cc click california-quantity-female save', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mousedown); document.querySelectorAll('.e-drillthrough-grid .e-spin-down')[0].dispatchEvent(mouseup); document.querySelectorAll('.e-drillthrough-grid .e-savebutton')[2].dispatchEvent(click); done(); }, 2000); }); it('cc click california-quantity-female check', (done: Function) => { ///jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('.e-drillthrough-grid td[aria-colindex="11"]')[0].textContent).toBe("18"); (document.querySelectorAll('.e-drillthrough-dialog .e-dlg-closeicon-btn')[0] as HTMLElement).click(); done(); }, 2000); }); it('apply value filter', () => { expect(document.querySelector('.e-drillthrough-dialog')).toBeTruthy; pivotGridObj.dataSourceSettings.filterSettings = [ { name: 'product', type: 'Value', condition: 'GreaterThan', value1: '1000', measure: 'quantity' }, ]; }); it('value filter check', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelectorAll('td[aria-colindex="9"]')[4].textContent).toBe("4663"); done(); }, 2000); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange); //Check average change in memory samples to not be over 10MB //expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()); //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import Axios from 'axios'; import { readFileSync } from 'fs'; import { Base64 } from 'js-base64'; import { parse, resolve } from 'path'; import { workspace, commands } from 'vscode'; import { output } from '../helper/common'; // async fs does not have import module available const fs = require('fs'); const util = require('util'); const readFile = util.promisify(fs.readFile); export const CODE_RE = /\[!code-(.+?)\s*\[\s*.+?\s*]\(\s*(.+?)\s*\)\s*]/i; const ROOTPATH_RE = /.*~/gim; export function codeSnippets(md, options) { const replaceCodeSnippetWithContents = (src: string, rootdir: string) => { let captureGroup; while ((captureGroup = CODE_RE.exec(src))) { const repoRoot = workspace.workspaceFolders[0].uri.fsPath; let filePath = resolve(rootdir, captureGroup[2].trim()); if (filePath.includes('~')) { filePath = filePath.replace(ROOTPATH_RE, repoRoot); } let mdSrc = readFileSync(filePath, 'utf8'); mdSrc = `\`\`\`${captureGroup[1].trim()}\r\n${mdSrc}\r\n\`\`\``; src = src.slice(0, captureGroup.index) + mdSrc + src.slice(captureGroup.index + captureGroup[0].length, src.length); } return src; }; const importCodeSnippet = state => { try { state.src = replaceCodeSnippetWithContents(state.src, options.root); } catch (error) { output.appendLine(error); } }; md.core.ruler.before('normalize', 'codesnippet', importCodeSnippet); } let codeSnippetContent = ''; const fileMap = new Map(); const TRIPLE_COLON_CODE_RE = /:::(\s+)?code\s+(source|range|id|highlight|language|interactive)=".*?"(\s+)?((source|range|id|highlight|language|interactive)=".*?"(\s+))?((source|range|id|highlight|language|interactive)=".*?"\s+)?((source|range|id|highlight|language|interactive)=".*?"\s+)?((source|range|id|highlight|language|interactive)=".*?"(\s+)?)?:::/g; const SOURCE_RE = /source="(.*?)"/i; const LANGUAGE_RE = /language="(.*?)"/i; const RANGE_RE = /range="(.*?)"/i; const ID_RE = /id="(.*?)"/i; export function refreshPreviewCache() { fileMap.forEach((value, key) => { fileMap.delete(key); }); commands.executeCommand('markdown.preview.refresh'); } export function tripleColonCodeSnippets(md, options) { const replaceTripleColonCodeSnippetWithContents = async (src: string, rootdir: string) => { const matches = src.match(TRIPLE_COLON_CODE_RE); if (matches) { for (const match of matches) { let file; let shouldUpdate = false; let snippetOutput = ''; const lineArr: string[] = []; const position = src.indexOf(match); const source = match.match(SOURCE_RE); const path = source[1].trim(); if (path) { file = fileMap.get(path); if (!file) { shouldUpdate = true; const repoRoot = workspace.workspaceFolders[0].uri.fsPath; if (path.includes('~')) { // get openpublishing.json at root const openPublishingRepos = await getOpenPublishingFile(repoRoot); if (openPublishingRepos) { const apiUrl = buildRepoPath(openPublishingRepos, path); try { await Axios.get(apiUrl).then(response => { if (response) { if (response.status === 403) { output.appendLine( 'Github Rate Limit has been reached. 60 calls per hour are allowed.' ); } else if (response.status === 404) { output.appendLine('Resource not Found.'); } else if (response.status === 200) { file = Base64.decode(response.data.content); fileMap.set(path, file); } } }); } catch (error) { output.appendLine(error); } } } else { const filePath = resolve(rootdir, path); if (fs.existsSync(filePath)) { file = await readFile(filePath, 'utf8'); fileMap.set(path, file); } } } } if (file) { const data = file.split('\n'); const language = getLanguage(match, path); const range = match.match(RANGE_RE); const idMatch = match.match(ID_RE); if (idMatch) { snippetOutput = idToOutput(idMatch, lineArr, data, language); } else if (range) { snippetOutput = rangeToOutput(lineArr, data, range); } else { snippetOutput = file; } snippetOutput = `\`\`\`${language}\r\n${snippetOutput}\r\n\`\`\``; src = src.slice(0, position) + snippetOutput + src.slice(position + match.length, src.length); codeSnippetContent = src; if (shouldUpdate) { await commands.executeCommand('markdown.preview.refresh'); } } else { codeSnippetContent = src; } } } else { codeSnippetContent = src; } }; const importTripleColonCodeSnippets = state => { try { replaceTripleColonCodeSnippetWithContents(state.src, options.root); state.src = codeSnippetContent; } catch (error) { output.appendLine(error); } }; md.core.ruler.before('normalize', 'codesnippet', importTripleColonCodeSnippets); } function getLanguage(match, path) { let language = checkLanguageMatch(match); if (!language) { language = inferLanguage(path); } return language; } function buildRepoPath(repos, path) { let position = 0; let repoPath = ''; const parts = path.split('/'); repos.map((repo: { path_to_root: string; url: string }) => { if (parts) { parts.map((part, index) => { if (repo.path_to_root === part) { position = index; repoPath = repo.url; return; } }); } }); const fullPath = []; repoPath = repoPath.replace('https://github.com/', 'https://api.github.com/repos/'); fullPath.push(repoPath); fullPath.push('contents'); for (let index = position + 1; index < parts.length; index++) { fullPath.push(parts[index]); } return encodeURI(fullPath.join('/')); } async function getOpenPublishingFile(repoRoot) { const openPublishingFilePath = resolve(repoRoot, '.openpublishing.publish.config.json'); const openPublishingFile = await readFile(openPublishingFilePath, 'utf8'); const openPublishingJson = JSON.parse(openPublishingFile); return openPublishingJson.dependent_repositories; } function checkLanguageMatch(match) { const languageMatch = LANGUAGE_RE.exec(match); let language = ''; if (languageMatch) { language = languageMatch[1].trim(); } return language; } function inferLanguage(filePath: string) { const dict = [ { actionscript: ['.as'] }, { arduino: ['.ino'] }, { assembly: ['nasm', '.asm'] }, { batchfile: ['.bat', '.cmd'] }, { cpp: [ 'c', 'c++', 'objective-c', 'obj-c', 'objc', 'objectivec', '.c', '.cpp', '.h', '.hpp', '.cc' ] }, { csharp: ['cs', '.cs'] }, { cuda: ['.cu', '.cuh'] }, { d: ['dlang', '.d'] }, { erlang: ['.erl'] }, { fsharp: ['fs', '.fs', '.fsi', '.fsx'] }, { go: ['golang', '.go'] }, { haskell: ['.hs'] }, { html: ['.html', '.jsp', '.asp', '.aspx', '.ascx'] }, { cshtml: ['.cshtml', 'aspx-cs', 'aspx-csharp'] }, { vbhtml: ['.vbhtml', 'aspx-vb'] }, { java: ['.java'] }, { javascript: ['js', 'node', '.js'] }, { lisp: ['.lisp', '.lsp'] }, { lua: ['.lua'] }, { matlab: ['.matlab'] }, { pascal: ['.pas'] }, { perl: ['.pl'] }, { php: ['.php'] }, { powershell: ['posh', '.ps1'] }, { processing: ['.pde'] }, { python: ['.py'] }, { r: ['.r'] }, { ruby: ['ru', '.ru', '.ruby'] }, { rust: ['.rs'] }, { scala: ['.scala'] }, { shell: ['sh', 'bash', '.sh', '.bash'] }, { smalltalk: ['.st'] }, { sql: ['.sql'] }, { swift: ['.swift'] }, { typescript: ['ts', '.ts'] }, { xaml: ['.xaml'] }, { xml: [ 'xsl', 'xslt', 'xsd', 'wsdl', '.xml', '.csdl', '.edmx', '.xsl', '.xslt', '.xsd', '.wsdl' ] }, { vb: ['vbnet', 'vbscript', '.vb', '.bas', '.vbs', '.vba'] } ]; const target = parse(filePath); const ext: string = target.ext; let language: string = ''; language = parseLanguage(dict, ext, language); if (!language) { language = ext.substr(1); } return language; } function parseLanguage(dict: any, ext: string, language: string): string { dict.forEach((key: any) => { const element: any = key; element.forEach(extension => { const val: string[] = extension; val.forEach(x => { if (val[x] === ext) { language = extension; return language; } }); }); }); return language; } function rangeToOutput(lineArr, data, range) { const rangeArr: number[] = []; const rangeList = range[1].split(','); rangeList.forEach(element => { if (element.indexOf('-') > 0) { const rangeThru = element.split('-'); const startRange = parseInt(rangeThru[0], 10); const endRange = parseInt(rangeThru.pop(), 10); for (let index = startRange; index <= endRange; index++) { rangeArr.push(index); } } else { rangeArr.push(parseInt(element, 10)); } }); rangeArr.sort(); data.map((line, index) => { rangeArr.filter(x => { if (x === index + 1) { lineArr.push(line); } }); }); lineArr = dedent(lineArr); return lineArr.join('\n'); } function idToOutput(idMatch, lineArr, data, language) { const id = idMatch[1].trim(); let startLine = 0; let endLine = 0; const START_RE = new RegExp(`((<|#region)\s*${id}(>|(\s*>)))`, 'i'); const END_RE = new RegExp(`(</|#endregion)\s*${id}(\s*>)`, 'i'); // logic for id. for (let index = 0; index < data.length; index++) { if (START_RE.exec(data[index])) { startLine = index; } if (END_RE.exec(data[index])) { endLine = index; break; } if (index + 1 === data.length) { endLine = data.length; break; } } data.map((x, index) => { if (index > startLine && index < endLine) { lineArr.push(x); } }); lineArr = dedent(lineArr); return lineArr.join('\n'); } function dedent(lineArr) { let indent = 0; let firstIteration = true; for (const key in lineArr) { if (lineArr.hasOwnProperty(key)) { let index = 0; const line = lineArr[key].split(''); for (const val in line) { if (line.hasOwnProperty(val)) { const character = line[val]; if (firstIteration) { if (!/\s/.test(character)) { lineArr[key] = lineArr[key].substring(indent); break; } else { indent++; } } else { // check if all spaces const allSpaces = lineArr[key].substring(0, indent); if (allSpaces.match(/^ *$/) !== null) { lineArr[key] = lineArr[key].substring(indent); break; } else { if (!/\s/.test(character)) { lineArr[key] = lineArr[key].substring(index); break; } } } index++; } } firstIteration = false; } } return lineArr; }
the_stack
import { ClauseParameter, ContractParameterHash, createSignature, crypto, isHash } from "ivy-bitcoin" import { ContractParameterType, GenerateBytesInput, GenerateHashInput, getChild, getInputNameContext, getInputType, HashInput, Input, InputContext, InputMap, InputType, isComplexInput, isPrimaryInputType, ParameterInput, ProvideHashInput } from "./types" import * as momentImport from "moment" // weird workaround const moment = typeof (momentImport as any).default === "function" ? (momentImport as any).default : momentImport const MIN_TIMESTAMP = 500000000 const MAX_NUMBER = 2147483647 const MIN_NUMBER = -2147483647 const MAX_UINT32 = 4294967295 const MAX_UINT16 = 65535 function validateHex(str: string): boolean { return /^([a-f0-9][a-f0-9])*$/.test(str) } export const isValidInput = (id: string, inputMap: InputMap): boolean => { const input = inputMap[id] switch (input.type) { case "parameterInput": case "bytesInput": case "hashInput": case "publicKeyInput": case "timeInput": case "signatureInput": case "generateHashInput": case "generatePublicKeyInput": return isValidInput(getChild(input), inputMap) default: return validateInput(input) } } export function isValidBTC(value: string) { return ( value !== "" && /^(\d+)?(\.\d{0,8})?$/.test(value) && parseFloat(value) <= 21000000 ) } export function validateInput(input: Input): boolean { // validates that an individual input is valid // does not validate child inputs switch (input.type) { case "parameterInput": case "generateHashInput": return isPrimaryInputType(input.value) case "addressInput": return ( input.value === "generateAddressInput" || input.value === "provideAddressInput" ) case "bytesInput": return ( input.value === "generateBytesInput" || input.value === "provideBytesInput" ) case "hashInput": return ( input.value === "generateHashInput" || input.value === "provideHashInput" ) case "publicKeyInput": return ( input.value === "providePublicKeyInput" || input.value === "generatePublicKeyInput" ) case "generatePublicKeyInput": return ( input.value === "generatePrivateKeyInput" || input.value === "providePrivateKeyInput" ) case "durationInput": return ( input.value === "secondsDurationInput" || input.value === "blocksDurationInput" ) case "timeInput": return ( input.value === "timestampTimeInput" || input.value === "blockheightTimeInput" ) case "generatePublicKeyInput": case "generateAddressInput": return ( input.value === "generatePrivateKeyInput" || input.value === "providePrivateKeyInput" ) case "signatureInput": return ( input.value === "generateSignatureInput" || input.value === "provideSignatureInput" ) case "generateSignatureInput": return input.value === "providePrivateKeyInput" case "provideBytesInput": return validateHex(input.value) case "provideHashInput": if (!validateHex(input.value)) { return false } switch (input.hashFunction) { case "sha256": return input.value.length === 64 case "sha1": case "ripemd160": return input.value.length === 40 } case "generatePrivateKeyInput": case "providePrivateKeyInput": try { const kr = crypto.KeyRing.fromSecret(input.value) return true } catch (e) { return false } case "provideAddressInput": try { // const address = Address.fromBase58(input.value) return true } catch (e) { return false } case "providePublicKeyInput": try { const buf = Buffer.from(input.value, "hex") const kr = crypto.KeyRing.fromPublic(buf) return true } catch (e) { return false } case "provideSignatureInput": { if (!validateHex(input.value)) { return false } const buf = Buffer.from(input.value.slice(0, -2), "hex") try { const sig = crypto.secp256k1.fromDER(buf) return true } catch (e) { return false } } case "generateBytesInput": { const length = parseInt(input.value, 10) if (isNaN(length) || length < 0 || length > 520) { return false } return input.seed.length === 1040 } case "booleanInput": return input.value === "true" || input.value === "false" case "timestampTimeInput": const timestamp = Date.parse(input.value + "Z") / 1000 if ( isNaN(timestamp) || timestamp < MIN_TIMESTAMP || timestamp > MAX_UINT32 ) { return false } return true case "numberInput": case "blockheightTimeInput": case "secondsDurationInput": case "blocksDurationInput": if (!/^\-?\d+$/.test(input.value)) { return false } const numberValue = parseInt(input.value, 10) switch (input.type) { case "numberInput": return numberValue >= MIN_NUMBER && numberValue <= MAX_NUMBER case "blockheightTimeInput": return numberValue >= 0 && numberValue < MIN_TIMESTAMP case "secondsDurationInput": case "blocksDurationInput": return numberValue >= 0 && numberValue <= MAX_UINT16 default: throw new Error("unexpectedly reached end of switch statement") } case "valueInput": { return isValidBTC(input.value) } case "lockTimeInput": return input.value === "timeInput" case "sequenceNumberInput": return input.value === "durationInput" } } export function getSequence(inputsById: { [s: string]: Input }) { const durationInput = inputsById["transactionDetails.sequenceNumberInput.durationInput"] if (durationInput.value === "secondsDurationInput") { const input = inputsById[ "transactionDetails.sequenceNumberInput.durationInput.secondsDurationInput" ] if (!validateInput(input)) { throw new Error("invalid sequence number") } const val = input.value const seq = parseInt(val, 10) << 9 return { sequence: seq, seconds: true } } else { const input = inputsById[ "transactionDetails.sequenceNumberInput.durationInput.blocksDurationInput" ] if (!validateInput(input)) { throw new Error("invalid sequence number") } const val = input.value return { sequence: parseInt(val, 10), seconds: false } } } export function getData( inputId: string, inputsById: { [s: string]: Input }, sigHash?: Buffer ): Buffer | number { const input = inputsById[inputId] if (!validateInput(input)) { throw new Error("invalid input: " + input.name) } switch (input.type) { case "parameterInput": case "bytesInput": case "hashInput": case "publicKeyInput": case "durationInput": case "timeInput": case "signatureInput": case "lockTimeInput": case "sequenceNumberInput": return getData(getChild(input), inputsById, sigHash) case "provideBytesInput": case "providePublicKeyInput": case "provideHashInput": case "provideSignatureInput": { return Buffer.from(input.value, "hex") } case "generatePublicKeyInput": { const publicKeyValue = getPublicKeyValue(inputId, inputsById) return Buffer.from(publicKeyValue, "hex") } case "numberInput": { return parseInt(input.value, 10) } case "booleanInput": { return input.value === "true" ? 1 : 0 } case "valueInput": { return Math.round(parseFloat(input.value) * 100000000) } case "blocksDurationInput": case "secondsDurationInput": { let numValue = parseInt(input.value, 10) if (input.type === "secondsDurationInput") { numValue = numValue | (1 << 22) } // set the flag return numValue } case "timestampTimeInput": { const numValue = Date.parse(input.value + "Z") / 1000 return numValue } case "blockheightTimeInput": { const numValue = parseInt(input.value, 10) return numValue } case "generateBytesInput": { const generated = getGenerateBytesInputValue(input) return Buffer.from(generated, "hex") } case "generateHashInput": { const childData = getData(getChild(input), inputsById, sigHash) if (typeof childData === "number") { throw new Error("should not generate hash of a number") } switch (input.hashType.hashFunction) { case "sha1": return crypto.sha1(childData) case "sha256": return crypto.sha256(childData) case "ripemd160": return crypto.ripemd160(childData) default: throw new Error("unexpected hash function") } } case "generateSignatureInput": { const privKey = getPrivateKeyValue(inputId, inputsById) if (sigHash === undefined) { throw new Error("no sigHash provided to generateSignatureInput") } const sig = createSignature(sigHash, privKey) if (sig === undefined) { throw new Error("invalid private key") } return sig } default: throw new Error("should not call getData with " + input.type) } } export function getPublicKeyValue( inputId: string, inputsById: { [s: string]: Input } ) { const privateKeyValue = getPrivateKeyValue(inputId, inputsById) const kr = crypto.KeyRing.fromSecret(privateKeyValue) return kr.getPublicKey("hex") } export function getPrivateKeyValue( inputId: string, inputsById: { [s: string]: Input } ) { const input = inputsById[inputId] if ( input === undefined || (input.type !== "generatePublicKeyInput" && input.type !== "generateSignatureInput") ) { throw new Error("unexpected input") } const privateKeyInput = inputsById[getChild(input)] if (privateKeyInput === undefined) { throw new Error("private key input unexpectedly missing") } return privateKeyInput.value } export function getGenerateBytesInputValue(input: GenerateBytesInput) { const length = parseInt(input.value, 10) if (isNaN(length) || length < 0 || length > 520) { throw new Error( "invalid length value for generateBytesInput: " + input.value ) } return input.seed.slice(0, length * 2) // dumb, for now } function getGenerateAddressValue( inputId: string, inputsById: { [s: string]: Input } ) { const input = inputsById[inputId] if (input === undefined || input.type !== "generateAddressInput") { throw new Error("unexpected input") } const privateKeyInput = inputsById[getChild(input)] if (privateKeyInput === undefined) { throw new Error("private key input unexpectedly missing") } const kr = crypto.KeyRing.fromSecret(privateKeyInput.value) return kr.getAddress("base58") } export function computeDataForInput( inputId: string, inputsById: { [s: string]: Input } ): string { const input = inputsById[inputId] const data = getData(inputId, inputsById) if (typeof data === "number") { throw new Error("should not get data for a number") } return data.toString("hex") } export function getDefaultContractParameterValue(inputType: InputType): string { switch (inputType) { case "parameterInput": case "generateHashInput": case "lockTimeInput": case "sequenceNumberInput": case "addressInput": case "generateAddressInput": case "provideAddressInput": throw new Error( "getDefaultContractParameterValue should not be called on " + inputType ) case "booleanInput": return "false" case "generateBytesInput": return "32" case "numberInput": case "blocksDurationInput": case "secondsDurationInput": case "blockheightTimeInput": return "0" case "timestampTimeInput": const date = moment().subtract(15, "minutes") const dateString = date.toISOString().slice(0, -10) + "00:00" return dateString // "2018-01-01T00:00" case "provideBytesInput": case "provideHashInput": case "providePublicKeyInput": case "providePrivateKeyInput": case "provideSignatureInput": return "" case "generatePrivateKeyInput": const key = crypto.privateKey.generate() const kr = crypto.KeyRing.fromPrivate(key.privateKey) return kr.toSecret() case "bytesInput": return "generateBytesInput" case "hashInput": return "generateHashInput" case "generatePublicKeyInput": return "generatePrivateKeyInput" case "publicKeyInput": return "generatePublicKeyInput" case "signatureInput": return "generateSignatureInput" case "generateSignatureInput": return "providePrivateKeyInput" case "booleanInput": return "false" case "durationInput": return "blocksDurationInput" case "timeInput": return "blockheightTimeInput" case "valueInput": return "0" } } export function getDefaultTransactionDetailValue(inputType: InputType): string { switch (inputType) { case "lockTimeInput": return "timeInput" case "sequenceNumberInput": return "durationInput" case "provideAddressInput": return "" case "addressInput": return "generateAddressInput" case "generateAddressInput": return "generatePrivateKeyInput" default: // fall back for now return getDefaultContractParameterValue(inputType) } } export function getDefaultClauseParameterValue(inputType: InputType): string { switch (inputType) { case "parameterInput": case "generateHashInput": case "addressInput": case "generateAddressInput": case "provideAddressInput": case "lockTimeInput": case "sequenceNumberInput": case "valueInput": throw new Error( "getDefaultClauseParameterValue should not be called on " + inputType ) case "booleanInput": return "false" case "generateBytesInput": return "32" case "numberInput": case "blocksDurationInput": case "secondsDurationInput": case "blockheightTimeInput": return "0" case "timestampTimeInput": return "2018-01-01T00:00" case "provideBytesInput": case "provideHashInput": case "providePublicKeyInput": case "providePrivateKeyInput": case "provideSignatureInput": return "" case "generatePrivateKeyInput": const key = crypto.privateKey.generate() const kr = crypto.KeyRing.fromPrivate(key.privateKey) return kr.toSecret() case "bytesInput": return "provideBytesInput" case "hashInput": return "provideHashInput" case "publicKeyInput": return "providePublicKeyInput" case "signatureInput": return "generateSignatureInput" case "generatePublicKeyInput": case "generateSignatureInput": return "providePrivateKeyInput" case "booleanInput": return "false" case "durationInput": return "blocksDurationInput" case "timeInput": return "blockheightTimeInput" } } export function getDefaultValue(inputType, name): string { switch (getInputNameContext(name)) { case "clauseParameters": return getDefaultClauseParameterValue(inputType) case "contractParameters": return getDefaultContractParameterValue(inputType) case "transactionDetails": return getDefaultTransactionDetailValue(inputType) } } export function addDefaultInput( inputs: Input[], inputType: InputType, parentName ) { const name = parentName + "." + inputType const value = getDefaultValue(inputType, name) switch (inputType) { case "generateBytesInput": { const seed = crypto.randomBytes(520).toString("hex") inputs.push({ type: "generateBytesInput", value: value as any, seed, name }) break } default: inputs.push({ type: inputType as any, value, name }) } switch (inputType) { case "bytesInput": { addDefaultInput(inputs, "generateBytesInput", name) addDefaultInput(inputs, "provideBytesInput", name) return } case "publicKeyInput": { addDefaultInput(inputs, "generatePublicKeyInput", name) addDefaultInput(inputs, "providePublicKeyInput", name) return } case "generatePublicKeyInput": case "generateAddressInput": { addDefaultInput(inputs, "generatePrivateKeyInput", name) addDefaultInput(inputs, "providePrivateKeyInput", name) } case "timeInput": { addDefaultInput(inputs, "blockheightTimeInput", name) addDefaultInput(inputs, "timestampTimeInput", name) return } case "durationInput": { addDefaultInput(inputs, "blocksDurationInput", name) addDefaultInput(inputs, "secondsDurationInput", name) return } case "signatureInput": { addDefaultInput(inputs, "generateSignatureInput", name) addDefaultInput(inputs, "provideSignatureInput", name) return } case "generateSignatureInput": { addDefaultInput(inputs, "providePrivateKeyInput", name) return } case "addressInput": { addDefaultInput(inputs, "generateAddressInput", name) addDefaultInput(inputs, "provideAddressInput", name) return } case "lockTimeInput": { addDefaultInput(inputs, "timeInput", name) return } case "sequenceNumberInput": { addDefaultInput(inputs, "durationInput", name) return } default: return } } function addHashInputs( inputs: Input[], type: ContractParameterHash, parentName: string ) { const name = parentName + ".generateHashInput" const value = getInputType(type.inputType) const generateHashInput: GenerateHashInput = { type: "generateHashInput", hashType: type, value, name } inputs.push(generateHashInput) addInputForType(inputs, type.inputType, name) const hashType = generateHashInput.hashType.inputType const provideHashInput: ProvideHashInput = { type: "provideHashInput", hashFunction: type.hashFunction, value: "", name: parentName + ".provideHashInput" } inputs.push(provideHashInput) } function addHashInput( inputs: Input[], type: ContractParameterHash, parentName: string ) { const name = parentName + ".hashInput" const hashInput: HashInput = { type: "hashInput", hashType: type, value: "generateHashInput", name } inputs.push(hashInput) addHashInputs(inputs, type, name) } function addInputForType( inputs: Input[], parameterType: ContractParameterType, parentName: string ) { if (isHash(parameterType)) { addHashInput(inputs, parameterType, parentName) } else { addDefaultInput(inputs, getInputType(parameterType), parentName) } } export function addParameterInput( inputs: Input[], valueType: ContractParameterType, name: string ) { const inputType = getInputType(valueType) const parameterInput: ParameterInput = { type: "parameterInput", value: inputType, valueType, name } inputs.push(parameterInput) addInputForType(inputs, valueType, name) } export const getInputContext = (input: Input): InputContext => { return getInputNameContext(input.name) } export const getParameterIdentifier = (input: ParameterInput): string => { switch (getInputContext(input)) { case "contractParameters": return input.name.split(".")[1] case "clauseParameters": return input.name.split(".")[2] default: throw new Error( "unexpected input for getParameterIdentifier: " + input.name ) } }
the_stack
import { gql } from '@apollo/client' import * as Apollo from '@apollo/client' export type Maybe<T> = T | null export type InputMaybe<T> = Maybe<T> export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] } export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> } export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> } const defaultOptions = {} /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string String: string Boolean: boolean Int: number Float: number Date: any } export type AddBookmarkInput = { tag: Scalars['String'] url: Scalars['String'] } export type AddPostInput = { excerpt?: InputMaybe<Scalars['String']> slug: Scalars['String'] text: Scalars['String'] title: Scalars['String'] } export type AddQuestionInput = { description?: InputMaybe<Scalars['String']> title: Scalars['String'] } export type AddStackInput = { description: Scalars['String'] image: Scalars['String'] name: Scalars['String'] tag?: InputMaybe<Scalars['String']> url: Scalars['String'] } export type Bookmark = { __typename?: 'Bookmark' createdAt: Scalars['Date'] description?: Maybe<Scalars['String']> faviconUrl?: Maybe<Scalars['String']> host: Scalars['String'] id: Scalars['ID'] image?: Maybe<Scalars['String']> reactionCount?: Maybe<Scalars['Int']> tags: Array<Maybe<Tag>> title?: Maybe<Scalars['String']> updatedAt: Scalars['Date'] url: Scalars['String'] viewerHasReacted?: Maybe<Scalars['Boolean']> } export type BookmarkEdge = { __typename?: 'BookmarkEdge' cursor?: Maybe<Scalars['String']> node?: Maybe<Bookmark> } export type BookmarkFilter = { host?: InputMaybe<Scalars['String']> tag?: InputMaybe<Scalars['String']> } export type BookmarksConnection = { __typename?: 'BookmarksConnection' edges: Array<Maybe<BookmarkEdge>> pageInfo?: Maybe<PageInfo> } export type Comment = { __typename?: 'Comment' author: User createdAt: Scalars['Date'] id: Scalars['ID'] text?: Maybe<Scalars['String']> updatedAt?: Maybe<Scalars['Date']> viewerCanDelete?: Maybe<Scalars['Boolean']> viewerCanEdit?: Maybe<Scalars['Boolean']> } export enum CommentType { Bookmark = 'BOOKMARK', Post = 'POST', Question = 'QUESTION', Stack = 'STACK', } export type EditBookmarkInput = { description?: InputMaybe<Scalars['String']> faviconUrl?: InputMaybe<Scalars['String']> tag?: InputMaybe<Scalars['String']> title: Scalars['String'] } export type EditPostInput = { excerpt?: InputMaybe<Scalars['String']> published?: InputMaybe<Scalars['Boolean']> slug: Scalars['String'] text: Scalars['String'] title: Scalars['String'] } export type EditQuestionInput = { description?: InputMaybe<Scalars['String']> title: Scalars['String'] } export type EditStackInput = { description: Scalars['String'] image: Scalars['String'] name: Scalars['String'] tag?: InputMaybe<Scalars['String']> url: Scalars['String'] } export type EditUserInput = { email?: InputMaybe<Scalars['String']> username?: InputMaybe<Scalars['String']> } export type EmailSubscription = { __typename?: 'EmailSubscription' subscribed?: Maybe<Scalars['Boolean']> type?: Maybe<EmailSubscriptionType> } export type EmailSubscriptionInput = { email?: InputMaybe<Scalars['String']> subscribed: Scalars['Boolean'] type: EmailSubscriptionType } export enum EmailSubscriptionType { HackerNews = 'HACKER_NEWS', Newsletter = 'NEWSLETTER', } export type HackerNewsComment = { __typename?: 'HackerNewsComment' comments?: Maybe<Array<Maybe<HackerNewsComment>>> comments_count?: Maybe<Scalars['String']> content?: Maybe<Scalars['String']> id?: Maybe<Scalars['ID']> level?: Maybe<Scalars['Int']> time?: Maybe<Scalars['Int']> time_ago?: Maybe<Scalars['String']> user?: Maybe<Scalars['String']> } export type HackerNewsPost = { __typename?: 'HackerNewsPost' comments?: Maybe<Array<Maybe<HackerNewsComment>>> comments_count?: Maybe<Scalars['String']> content?: Maybe<Scalars['String']> domain?: Maybe<Scalars['String']> id?: Maybe<Scalars['ID']> time?: Maybe<Scalars['Int']> time_ago?: Maybe<Scalars['String']> title?: Maybe<Scalars['String']> url?: Maybe<Scalars['String']> user?: Maybe<Scalars['String']> } export type Mutation = { __typename?: 'Mutation' addBookmark?: Maybe<Bookmark> addComment?: Maybe<Comment> addPost?: Maybe<Post> addQuestion?: Maybe<Question> addStack?: Maybe<Stack> deleteBookmark?: Maybe<Scalars['Boolean']> deleteComment?: Maybe<Scalars['Boolean']> deletePost?: Maybe<Scalars['Boolean']> deleteQuestion?: Maybe<Scalars['Boolean']> deleteStack?: Maybe<Scalars['Boolean']> deleteUser?: Maybe<Scalars['Boolean']> editBookmark?: Maybe<Bookmark> editComment?: Maybe<Comment> editEmailSubscription?: Maybe<User> editPost?: Maybe<Post> editQuestion?: Maybe<Question> editStack?: Maybe<Stack> editUser?: Maybe<User> toggleReaction?: Maybe<Reactable> toggleStackUser?: Maybe<Stack> } export type MutationAddBookmarkArgs = { data: AddBookmarkInput } export type MutationAddCommentArgs = { refId: Scalars['ID'] text: Scalars['String'] type: CommentType } export type MutationAddPostArgs = { data: AddPostInput } export type MutationAddQuestionArgs = { data: AddQuestionInput } export type MutationAddStackArgs = { data: AddStackInput } export type MutationDeleteBookmarkArgs = { id: Scalars['ID'] } export type MutationDeleteCommentArgs = { id: Scalars['ID'] } export type MutationDeletePostArgs = { id: Scalars['ID'] } export type MutationDeleteQuestionArgs = { id: Scalars['ID'] } export type MutationDeleteStackArgs = { id: Scalars['ID'] } export type MutationEditBookmarkArgs = { data: EditBookmarkInput id: Scalars['ID'] } export type MutationEditCommentArgs = { id: Scalars['ID'] text?: InputMaybe<Scalars['String']> } export type MutationEditEmailSubscriptionArgs = { data?: InputMaybe<EmailSubscriptionInput> } export type MutationEditPostArgs = { data: EditPostInput id: Scalars['ID'] } export type MutationEditQuestionArgs = { data: EditQuestionInput id: Scalars['ID'] } export type MutationEditStackArgs = { data: EditStackInput id: Scalars['ID'] } export type MutationEditUserArgs = { data?: InputMaybe<EditUserInput> } export type MutationToggleReactionArgs = { refId: Scalars['ID'] type: ReactionType } export type MutationToggleStackUserArgs = { id: Scalars['ID'] } export type PageInfo = { __typename?: 'PageInfo' endCursor?: Maybe<Scalars['String']> hasNextPage?: Maybe<Scalars['Boolean']> totalCount?: Maybe<Scalars['Int']> } export type Post = { __typename?: 'Post' author?: Maybe<User> createdAt?: Maybe<Scalars['Date']> excerpt?: Maybe<Scalars['String']> featureImage?: Maybe<Scalars['String']> id: Scalars['ID'] publishedAt?: Maybe<Scalars['Date']> reactionCount?: Maybe<Scalars['Int']> slug?: Maybe<Scalars['String']> text?: Maybe<Scalars['String']> title?: Maybe<Scalars['String']> updatedAt?: Maybe<Scalars['Date']> viewerHasReacted?: Maybe<Scalars['Boolean']> } export type Query = { __typename?: 'Query' bookmark?: Maybe<Bookmark> bookmarks: BookmarksConnection comment?: Maybe<Comment> comments: Array<Maybe<Comment>> hackerNewsPost?: Maybe<HackerNewsPost> hackerNewsPosts: Array<Maybe<HackerNewsPost>> post?: Maybe<Post> posts: Array<Maybe<Post>> question?: Maybe<Question> questions: QuestionsConnection stack?: Maybe<Stack> stacks: StacksConnection tags: Array<Maybe<Tag>> user?: Maybe<User> viewer?: Maybe<User> } export type QueryBookmarkArgs = { id: Scalars['ID'] } export type QueryBookmarksArgs = { after?: InputMaybe<Scalars['String']> filter?: InputMaybe<BookmarkFilter> first?: InputMaybe<Scalars['Int']> } export type QueryCommentArgs = { id: Scalars['ID'] } export type QueryCommentsArgs = { refId: Scalars['ID'] type: CommentType } export type QueryHackerNewsPostArgs = { id: Scalars['ID'] } export type QueryPostArgs = { slug: Scalars['String'] } export type QueryPostsArgs = { filter?: InputMaybe<WritingFilter> } export type QueryQuestionArgs = { id: Scalars['ID'] } export type QueryQuestionsArgs = { after?: InputMaybe<Scalars['String']> filter?: InputMaybe<QuestionFilter> first?: InputMaybe<Scalars['Int']> } export type QueryStackArgs = { slug: Scalars['String'] } export type QueryStacksArgs = { after?: InputMaybe<Scalars['String']> first?: InputMaybe<Scalars['Int']> } export type QueryUserArgs = { username: Scalars['String'] } export type Question = { __typename?: 'Question' author?: Maybe<User> createdAt: Scalars['Date'] description?: Maybe<Scalars['String']> id: Scalars['ID'] reactionCount?: Maybe<Scalars['Int']> status?: Maybe<QuestionStatus> title: Scalars['String'] updatedAt?: Maybe<Scalars['Date']> viewerCanComment?: Maybe<Scalars['Boolean']> viewerCanEdit?: Maybe<Scalars['Boolean']> viewerHasReacted?: Maybe<Scalars['Boolean']> } export type QuestionEdge = { __typename?: 'QuestionEdge' cursor?: Maybe<Scalars['String']> node?: Maybe<Question> } export type QuestionFilter = { status?: InputMaybe<QuestionStatus> } export enum QuestionStatus { Answered = 'ANSWERED', Pending = 'PENDING', } export type QuestionsConnection = { __typename?: 'QuestionsConnection' edges: Array<Maybe<QuestionEdge>> pageInfo?: Maybe<PageInfo> } export type Reactable = Bookmark | Post | Question | Stack export enum ReactionType { Bookmark = 'BOOKMARK', Post = 'POST', Question = 'QUESTION', Stack = 'STACK', } export type Stack = { __typename?: 'Stack' createdAt: Scalars['Date'] description?: Maybe<Scalars['String']> id: Scalars['ID'] image?: Maybe<Scalars['String']> name: Scalars['String'] reactionCount?: Maybe<Scalars['Int']> slug: Scalars['String'] tags: Array<Maybe<Tag>> updatedAt?: Maybe<Scalars['Date']> url: Scalars['String'] usedBy: Array<Maybe<User>> usedByViewer?: Maybe<Scalars['Boolean']> viewerHasReacted?: Maybe<Scalars['Boolean']> } export type StackEdge = { __typename?: 'StackEdge' cursor?: Maybe<Scalars['String']> node?: Maybe<Stack> } export type StacksConnection = { __typename?: 'StacksConnection' edges: Array<Maybe<StackEdge>> pageInfo?: Maybe<PageInfo> } export type Tag = { __typename?: 'Tag' name: Scalars['String'] } export type User = { __typename?: 'User' avatar?: Maybe<Scalars['String']> createdAt?: Maybe<Scalars['Date']> email?: Maybe<Scalars['String']> emailSubscriptions?: Maybe<Array<Maybe<EmailSubscription>>> id: Scalars['ID'] isAdmin?: Maybe<Scalars['Boolean']> isViewer?: Maybe<Scalars['Boolean']> name?: Maybe<Scalars['String']> pendingEmail?: Maybe<Scalars['String']> role?: Maybe<UserRole> username?: Maybe<Scalars['String']> } export enum UserRole { Admin = 'ADMIN', Blocked = 'BLOCKED', User = 'USER', } export type WritingFilter = { published?: InputMaybe<Scalars['Boolean']> } export type BookmarkCoreFragment = { __typename: 'Bookmark' id: string url: string host: string title?: string | null | undefined description?: string | null | undefined faviconUrl?: string | null | undefined } export type BookmarkListItemFragment = { __typename: 'Bookmark' id: string url: string host: string title?: string | null | undefined description?: string | null | undefined faviconUrl?: string | null | undefined } export type BookmarkDetailFragment = { __typename: 'Bookmark' reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string url: string host: string title?: string | null | undefined description?: string | null | undefined faviconUrl?: string | null | undefined tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } export type BookmarksConnectionFragment = { __typename?: 'BookmarksConnection' pageInfo?: | { __typename?: 'PageInfo' hasNextPage?: boolean | null | undefined totalCount?: number | null | undefined endCursor?: string | null | undefined } | null | undefined edges: Array< | { __typename?: 'BookmarkEdge' cursor?: string | null | undefined node?: | { __typename: 'Bookmark' id: string url: string host: string title?: string | null | undefined description?: string | null | undefined faviconUrl?: string | null | undefined } | null | undefined } | null | undefined > } export type CommentInfoFragment = { __typename: 'Comment' id: string createdAt: any updatedAt?: any | null | undefined text?: string | null | undefined viewerCanEdit?: boolean | null | undefined viewerCanDelete?: boolean | null | undefined author: { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } } export type HackerNewsListItemInfoFragment = { __typename?: 'HackerNewsPost' id?: string | null | undefined title?: string | null | undefined domain?: string | null | undefined url?: string | null | undefined } export type HackerNewsCommentInfoFragment = { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: string | null | undefined time_ago?: string | null | undefined level?: number | null | undefined content?: string | null | undefined } export type HackerNewsPostInfoFragment = { __typename?: 'HackerNewsPost' user?: string | null | undefined time?: number | null | undefined time_ago?: string | null | undefined comments_count?: string | null | undefined url?: string | null | undefined domain?: string | null | undefined content?: string | null | undefined id?: string | null | undefined title?: string | null | undefined comments?: | Array< | { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: string | null | undefined time_ago?: string | null | undefined level?: number | null | undefined content?: string | null | undefined comments?: | Array< | { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: string | null | undefined time_ago?: string | null | undefined level?: number | null | undefined content?: string | null | undefined comments?: | Array< | { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: string | null | undefined time_ago?: string | null | undefined level?: number | null | undefined content?: string | null | undefined comments?: | Array< | { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: | string | null | undefined time_ago?: string | null | undefined level?: number | null | undefined content?: string | null | undefined } | null | undefined > | null | undefined } | null | undefined > | null | undefined } | null | undefined > | null | undefined } | null | undefined > | null | undefined } export type PostCoreFragment = { __typename: 'Post' id: string publishedAt?: any | null | undefined title?: string | null | undefined slug?: string | null | undefined excerpt?: string | null | undefined } export type PostListItemFragment = { __typename: 'Post' id: string publishedAt?: any | null | undefined title?: string | null | undefined slug?: string | null | undefined excerpt?: string | null | undefined } export type PostDetailFragment = { __typename: 'Post' text?: string | null | undefined featureImage?: string | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string publishedAt?: any | null | undefined title?: string | null | undefined slug?: string | null | undefined excerpt?: string | null | undefined } export type QuestionCoreFragment = { __typename: 'Question' id: string title: string createdAt: any author?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } export type QuestionListItemFragment = { __typename: 'Question' id: string title: string createdAt: any author?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } export type QuestionDetailFragment = { __typename: 'Question' description?: string | null | undefined status?: QuestionStatus | null | undefined viewerCanEdit?: boolean | null | undefined viewerCanComment?: boolean | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string title: string createdAt: any author?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } export type QuestionsConnectionFragment = { __typename?: 'QuestionsConnection' pageInfo?: | { __typename?: 'PageInfo' hasNextPage?: boolean | null | undefined totalCount?: number | null | undefined endCursor?: string | null | undefined } | null | undefined edges: Array< | { __typename?: 'QuestionEdge' cursor?: string | null | undefined node?: | { __typename: 'Question' id: string title: string createdAt: any author?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } | null | undefined } | null | undefined > } export type StackCoreFragment = { __typename: 'Stack' id: string name: string image?: string | null | undefined url: string slug: string } export type StackListItemFragment = { __typename: 'Stack' id: string name: string image?: string | null | undefined url: string slug: string } export type StackDetailFragment = { __typename: 'Stack' createdAt: any description?: string | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined usedByViewer?: boolean | null | undefined id: string name: string image?: string | null | undefined url: string slug: string usedBy: Array< | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined > tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } export type StacksConnectionFragment = { __typename?: 'StacksConnection' pageInfo?: | { __typename?: 'PageInfo' hasNextPage?: boolean | null | undefined totalCount?: number | null | undefined endCursor?: string | null | undefined } | null | undefined edges: Array< | { __typename?: 'StackEdge' cursor?: string | null | undefined node?: | { __typename: 'Stack' id: string name: string image?: string | null | undefined url: string slug: string } | null | undefined } | null | undefined > } export type UserInfoFragment = { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } export type UserSettingsFragment = { __typename?: 'User' email?: string | null | undefined pendingEmail?: string | null | undefined emailSubscriptions?: | Array< | { __typename?: 'EmailSubscription' type?: EmailSubscriptionType | null | undefined subscribed?: boolean | null | undefined } | null | undefined > | null | undefined } export type EditBookmarkMutationVariables = Exact<{ id: Scalars['ID'] data: EditBookmarkInput }> export type EditBookmarkMutation = { __typename?: 'Mutation' editBookmark?: | { __typename: 'Bookmark' reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string url: string host: string title?: string | null | undefined description?: string | null | undefined faviconUrl?: string | null | undefined tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } | null | undefined } export type DeleteBookmarkMutationVariables = Exact<{ id: Scalars['ID'] }> export type DeleteBookmarkMutation = { __typename?: 'Mutation' deleteBookmark?: boolean | null | undefined } export type AddBookmarkMutationVariables = Exact<{ data: AddBookmarkInput }> export type AddBookmarkMutation = { __typename?: 'Mutation' addBookmark?: | { __typename: 'Bookmark' reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string url: string host: string title?: string | null | undefined description?: string | null | undefined faviconUrl?: string | null | undefined tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } | null | undefined } export type AddCommentMutationVariables = Exact<{ refId: Scalars['ID'] type: CommentType text: Scalars['String'] }> export type AddCommentMutation = { __typename?: 'Mutation' addComment?: | { __typename: 'Comment' id: string createdAt: any updatedAt?: any | null | undefined text?: string | null | undefined viewerCanEdit?: boolean | null | undefined viewerCanDelete?: boolean | null | undefined author: { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } } | null | undefined } export type EditCommentMutationVariables = Exact<{ id: Scalars['ID'] text: Scalars['String'] }> export type EditCommentMutation = { __typename?: 'Mutation' editComment?: | { __typename: 'Comment' id: string createdAt: any updatedAt?: any | null | undefined text?: string | null | undefined viewerCanEdit?: boolean | null | undefined viewerCanDelete?: boolean | null | undefined author: { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } } | null | undefined } export type DeleteCommentMutationVariables = Exact<{ id: Scalars['ID'] }> export type DeleteCommentMutation = { __typename?: 'Mutation' deleteComment?: boolean | null | undefined } export type EditEmailSubscriptionMutationVariables = Exact<{ data?: InputMaybe<EmailSubscriptionInput> }> export type EditEmailSubscriptionMutation = { __typename?: 'Mutation' editEmailSubscription?: | { __typename?: 'User' emailSubscriptions?: | Array< | { __typename?: 'EmailSubscription' subscribed?: boolean | null | undefined type?: EmailSubscriptionType | null | undefined } | null | undefined > | null | undefined } | null | undefined } export type EditPostMutationVariables = Exact<{ id: Scalars['ID'] data: EditPostInput }> export type EditPostMutation = { __typename?: 'Mutation' editPost?: | { __typename: 'Post' text?: string | null | undefined featureImage?: string | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string publishedAt?: any | null | undefined title?: string | null | undefined slug?: string | null | undefined excerpt?: string | null | undefined } | null | undefined } export type DeletePostMutationVariables = Exact<{ id: Scalars['ID'] }> export type DeletePostMutation = { __typename?: 'Mutation' deletePost?: boolean | null | undefined } export type AddPostMutationVariables = Exact<{ data: AddPostInput }> export type AddPostMutation = { __typename?: 'Mutation' addPost?: | { __typename: 'Post' text?: string | null | undefined featureImage?: string | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string publishedAt?: any | null | undefined title?: string | null | undefined slug?: string | null | undefined excerpt?: string | null | undefined } | null | undefined } export type EditQuestionMutationVariables = Exact<{ id: Scalars['ID'] data: EditQuestionInput }> export type EditQuestionMutation = { __typename?: 'Mutation' editQuestion?: | { __typename: 'Question' description?: string | null | undefined status?: QuestionStatus | null | undefined viewerCanEdit?: boolean | null | undefined viewerCanComment?: boolean | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string title: string createdAt: any author?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } | null | undefined } export type DeleteQuestionMutationVariables = Exact<{ id: Scalars['ID'] }> export type DeleteQuestionMutation = { __typename?: 'Mutation' deleteQuestion?: boolean | null | undefined } export type AddQuestionMutationVariables = Exact<{ data: AddQuestionInput }> export type AddQuestionMutation = { __typename?: 'Mutation' addQuestion?: | { __typename: 'Question' description?: string | null | undefined status?: QuestionStatus | null | undefined viewerCanEdit?: boolean | null | undefined viewerCanComment?: boolean | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string title: string createdAt: any author?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } | null | undefined } export type ToggleReactionMutationVariables = Exact<{ refId: Scalars['ID'] type: ReactionType }> export type ToggleReactionMutation = { __typename?: 'Mutation' toggleReaction?: | { __typename?: 'Bookmark' id: string url: string reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined } | { __typename?: 'Post' id: string reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined } | { __typename?: 'Question' id: string reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined } | { __typename?: 'Stack' id: string reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined } | null | undefined } export type EditStackMutationVariables = Exact<{ id: Scalars['ID'] data: EditStackInput }> export type EditStackMutation = { __typename?: 'Mutation' editStack?: | { __typename: 'Stack' createdAt: any description?: string | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined usedByViewer?: boolean | null | undefined id: string name: string image?: string | null | undefined url: string slug: string usedBy: Array< | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined > tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } | null | undefined } export type DeleteStackMutationVariables = Exact<{ id: Scalars['ID'] }> export type DeleteStackMutation = { __typename?: 'Mutation' deleteStack?: boolean | null | undefined } export type AddStackMutationVariables = Exact<{ data: AddStackInput }> export type AddStackMutation = { __typename?: 'Mutation' addStack?: | { __typename: 'Stack' createdAt: any description?: string | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined usedByViewer?: boolean | null | undefined id: string name: string image?: string | null | undefined url: string slug: string usedBy: Array< | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined > tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } | null | undefined } export type ToggleStackUserMutationVariables = Exact<{ id: Scalars['ID'] }> export type ToggleStackUserMutation = { __typename?: 'Mutation' toggleStackUser?: | { __typename: 'Stack' id: string name: string image?: string | null | undefined url: string slug: string usedBy: Array< | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined > } | null | undefined } export type DeleteUserMutationVariables = Exact<{ [key: string]: never }> export type DeleteUserMutation = { __typename?: 'Mutation' deleteUser?: boolean | null | undefined } export type EditUserMutationVariables = Exact<{ data?: InputMaybe<EditUserInput> }> export type EditUserMutation = { __typename?: 'Mutation' editUser?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } export type GetBookmarksQueryVariables = Exact<{ first?: InputMaybe<Scalars['Int']> after?: InputMaybe<Scalars['String']> filter?: InputMaybe<BookmarkFilter> }> export type GetBookmarksQuery = { __typename?: 'Query' bookmarks: { __typename?: 'BookmarksConnection' pageInfo?: | { __typename?: 'PageInfo' hasNextPage?: boolean | null | undefined totalCount?: number | null | undefined endCursor?: string | null | undefined } | null | undefined edges: Array< | { __typename?: 'BookmarkEdge' cursor?: string | null | undefined node?: | { __typename: 'Bookmark' id: string url: string host: string title?: string | null | undefined description?: string | null | undefined faviconUrl?: string | null | undefined } | null | undefined } | null | undefined > } } export type GetBookmarkQueryVariables = Exact<{ id: Scalars['ID'] }> export type GetBookmarkQuery = { __typename?: 'Query' bookmark?: | { __typename: 'Bookmark' reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string url: string host: string title?: string | null | undefined description?: string | null | undefined faviconUrl?: string | null | undefined tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } | null | undefined } export type GetCommentsQueryVariables = Exact<{ refId: Scalars['ID'] type: CommentType }> export type GetCommentsQuery = { __typename?: 'Query' comments: Array< | { __typename: 'Comment' id: string createdAt: any updatedAt?: any | null | undefined text?: string | null | undefined viewerCanEdit?: boolean | null | undefined viewerCanDelete?: boolean | null | undefined author: { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } } | null | undefined > } export type GetHackerNewsPostsQueryVariables = Exact<{ [key: string]: never }> export type GetHackerNewsPostsQuery = { __typename?: 'Query' hackerNewsPosts: Array< | { __typename?: 'HackerNewsPost' id?: string | null | undefined title?: string | null | undefined domain?: string | null | undefined url?: string | null | undefined } | null | undefined > } export type GetHackerNewsPostQueryVariables = Exact<{ id: Scalars['ID'] }> export type GetHackerNewsPostQuery = { __typename?: 'Query' hackerNewsPost?: | { __typename?: 'HackerNewsPost' user?: string | null | undefined time?: number | null | undefined time_ago?: string | null | undefined comments_count?: string | null | undefined url?: string | null | undefined domain?: string | null | undefined content?: string | null | undefined id?: string | null | undefined title?: string | null | undefined comments?: | Array< | { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: string | null | undefined time_ago?: string | null | undefined level?: number | null | undefined content?: string | null | undefined comments?: | Array< | { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: string | null | undefined time_ago?: string | null | undefined level?: number | null | undefined content?: string | null | undefined comments?: | Array< | { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: string | null | undefined time_ago?: string | null | undefined level?: number | null | undefined content?: string | null | undefined comments?: | Array< | { __typename?: 'HackerNewsComment' id?: string | null | undefined user?: string | null | undefined comments_count?: | string | null | undefined time_ago?: | string | null | undefined level?: | number | null | undefined content?: | string | null | undefined } | null | undefined > | null | undefined } | null | undefined > | null | undefined } | null | undefined > | null | undefined } | null | undefined > | null | undefined } | null | undefined } export type GetPostsQueryVariables = Exact<{ filter?: InputMaybe<WritingFilter> }> export type GetPostsQuery = { __typename?: 'Query' posts: Array< | { __typename: 'Post' id: string publishedAt?: any | null | undefined title?: string | null | undefined slug?: string | null | undefined excerpt?: string | null | undefined } | null | undefined > } export type GetPostQueryVariables = Exact<{ slug: Scalars['String'] }> export type GetPostQuery = { __typename?: 'Query' post?: | { __typename: 'Post' text?: string | null | undefined featureImage?: string | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string publishedAt?: any | null | undefined title?: string | null | undefined slug?: string | null | undefined excerpt?: string | null | undefined } | null | undefined } export type GetQuestionsQueryVariables = Exact<{ first?: InputMaybe<Scalars['Int']> after?: InputMaybe<Scalars['String']> filter?: InputMaybe<QuestionFilter> }> export type GetQuestionsQuery = { __typename?: 'Query' questions: { __typename?: 'QuestionsConnection' pageInfo?: | { __typename?: 'PageInfo' hasNextPage?: boolean | null | undefined totalCount?: number | null | undefined endCursor?: string | null | undefined } | null | undefined edges: Array< | { __typename?: 'QuestionEdge' cursor?: string | null | undefined node?: | { __typename: 'Question' id: string title: string createdAt: any author?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } | null | undefined } | null | undefined > } } export type GetQuestionQueryVariables = Exact<{ id: Scalars['ID'] }> export type GetQuestionQuery = { __typename?: 'Query' question?: | { __typename: 'Question' description?: string | null | undefined status?: QuestionStatus | null | undefined viewerCanEdit?: boolean | null | undefined viewerCanComment?: boolean | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined id: string title: string createdAt: any author?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } | null | undefined } export type GetStacksQueryVariables = Exact<{ first?: InputMaybe<Scalars['Int']> after?: InputMaybe<Scalars['String']> }> export type GetStacksQuery = { __typename?: 'Query' stacks: { __typename?: 'StacksConnection' pageInfo?: | { __typename?: 'PageInfo' hasNextPage?: boolean | null | undefined totalCount?: number | null | undefined endCursor?: string | null | undefined } | null | undefined edges: Array< | { __typename?: 'StackEdge' cursor?: string | null | undefined node?: | { __typename: 'Stack' id: string name: string image?: string | null | undefined url: string slug: string } | null | undefined } | null | undefined > } } export type GetStackQueryVariables = Exact<{ slug: Scalars['String'] }> export type GetStackQuery = { __typename?: 'Query' stack?: | { __typename: 'Stack' createdAt: any description?: string | null | undefined reactionCount?: number | null | undefined viewerHasReacted?: boolean | null | undefined usedByViewer?: boolean | null | undefined id: string name: string image?: string | null | undefined url: string slug: string usedBy: Array< | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined > tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } | null | undefined } export type GetTagsQueryVariables = Exact<{ [key: string]: never }> export type GetTagsQuery = { __typename?: 'Query' tags: Array<{ __typename?: 'Tag'; name: string } | null | undefined> } export type GetUserQueryVariables = Exact<{ username: Scalars['String'] }> export type GetUserQuery = { __typename?: 'Query' user?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } export type ViewerQueryVariables = Exact<{ [key: string]: never }> export type ViewerQuery = { __typename?: 'Query' viewer?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined } | null | undefined } export type GetViewerWithSettingsQueryVariables = Exact<{ [key: string]: never }> export type GetViewerWithSettingsQuery = { __typename?: 'Query' viewer?: | { __typename: 'User' id: string username?: string | null | undefined avatar?: string | null | undefined name?: string | null | undefined role?: UserRole | null | undefined isViewer?: boolean | null | undefined isAdmin?: boolean | null | undefined email?: string | null | undefined pendingEmail?: string | null | undefined emailSubscriptions?: | Array< | { __typename?: 'EmailSubscription' type?: EmailSubscriptionType | null | undefined subscribed?: boolean | null | undefined } | null | undefined > | null | undefined } | null | undefined } export const BookmarkCoreFragmentDoc = gql` fragment BookmarkCore on Bookmark { __typename id url host title description faviconUrl } ` export const BookmarkDetailFragmentDoc = gql` fragment BookmarkDetail on Bookmark { ...BookmarkCore reactionCount viewerHasReacted tags { name } } ${BookmarkCoreFragmentDoc} ` export const BookmarkListItemFragmentDoc = gql` fragment BookmarkListItem on Bookmark { ...BookmarkCore } ${BookmarkCoreFragmentDoc} ` export const BookmarksConnectionFragmentDoc = gql` fragment BookmarksConnection on BookmarksConnection { pageInfo { hasNextPage totalCount endCursor } edges { cursor node { ...BookmarkListItem } } } ${BookmarkListItemFragmentDoc} ` export const UserInfoFragmentDoc = gql` fragment UserInfo on User { __typename id username avatar name role isViewer isAdmin } ` export const CommentInfoFragmentDoc = gql` fragment CommentInfo on Comment { __typename id createdAt updatedAt text viewerCanEdit viewerCanDelete author { ...UserInfo } } ${UserInfoFragmentDoc} ` export const HackerNewsListItemInfoFragmentDoc = gql` fragment HackerNewsListItemInfo on HackerNewsPost { id title domain url } ` export const HackerNewsCommentInfoFragmentDoc = gql` fragment HackerNewsCommentInfo on HackerNewsComment { id user comments_count time_ago level content } ` export const HackerNewsPostInfoFragmentDoc = gql` fragment HackerNewsPostInfo on HackerNewsPost { ...HackerNewsListItemInfo user time time_ago comments_count url domain content comments { ...HackerNewsCommentInfo comments { ...HackerNewsCommentInfo comments { ...HackerNewsCommentInfo comments { ...HackerNewsCommentInfo } } } } } ${HackerNewsListItemInfoFragmentDoc} ${HackerNewsCommentInfoFragmentDoc} ` export const PostCoreFragmentDoc = gql` fragment PostCore on Post { __typename id publishedAt title slug excerpt } ` export const PostListItemFragmentDoc = gql` fragment PostListItem on Post { ...PostCore } ${PostCoreFragmentDoc} ` export const PostDetailFragmentDoc = gql` fragment PostDetail on Post { ...PostCore text featureImage reactionCount viewerHasReacted } ${PostCoreFragmentDoc} ` export const QuestionCoreFragmentDoc = gql` fragment QuestionCore on Question { __typename id title createdAt author { ...UserInfo } } ${UserInfoFragmentDoc} ` export const QuestionDetailFragmentDoc = gql` fragment QuestionDetail on Question { ...QuestionCore description status viewerCanEdit viewerCanComment reactionCount viewerHasReacted } ${QuestionCoreFragmentDoc} ` export const QuestionListItemFragmentDoc = gql` fragment QuestionListItem on Question { ...QuestionCore } ${QuestionCoreFragmentDoc} ` export const QuestionsConnectionFragmentDoc = gql` fragment QuestionsConnection on QuestionsConnection { pageInfo { hasNextPage totalCount endCursor } edges { cursor node { ...QuestionListItem } } } ${QuestionListItemFragmentDoc} ` export const StackCoreFragmentDoc = gql` fragment StackCore on Stack { __typename id name image url slug } ` export const StackDetailFragmentDoc = gql` fragment StackDetail on Stack { ...StackCore createdAt description reactionCount viewerHasReacted usedByViewer usedBy { ...UserInfo } tags { name } } ${StackCoreFragmentDoc} ${UserInfoFragmentDoc} ` export const StackListItemFragmentDoc = gql` fragment StackListItem on Stack { ...StackCore } ${StackCoreFragmentDoc} ` export const StacksConnectionFragmentDoc = gql` fragment StacksConnection on StacksConnection { pageInfo { hasNextPage totalCount endCursor } edges { cursor node { ...StackListItem } } } ${StackListItemFragmentDoc} ` export const UserSettingsFragmentDoc = gql` fragment UserSettings on User { email pendingEmail emailSubscriptions { type subscribed } } ` export const EditBookmarkDocument = gql` mutation editBookmark($id: ID!, $data: EditBookmarkInput!) { editBookmark(id: $id, data: $data) { ...BookmarkDetail } } ${BookmarkDetailFragmentDoc} ` export type EditBookmarkMutationFn = Apollo.MutationFunction< EditBookmarkMutation, EditBookmarkMutationVariables > /** * __useEditBookmarkMutation__ * * To run a mutation, you first call `useEditBookmarkMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useEditBookmarkMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [editBookmarkMutation, { data, loading, error }] = useEditBookmarkMutation({ * variables: { * id: // value for 'id' * data: // value for 'data' * }, * }); */ export function useEditBookmarkMutation( baseOptions?: Apollo.MutationHookOptions< EditBookmarkMutation, EditBookmarkMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation< EditBookmarkMutation, EditBookmarkMutationVariables >(EditBookmarkDocument, options) } export type EditBookmarkMutationHookResult = ReturnType< typeof useEditBookmarkMutation > export type EditBookmarkMutationResult = Apollo.MutationResult<EditBookmarkMutation> export type EditBookmarkMutationOptions = Apollo.BaseMutationOptions< EditBookmarkMutation, EditBookmarkMutationVariables > export const DeleteBookmarkDocument = gql` mutation deleteBookmark($id: ID!) { deleteBookmark(id: $id) } ` export type DeleteBookmarkMutationFn = Apollo.MutationFunction< DeleteBookmarkMutation, DeleteBookmarkMutationVariables > /** * __useDeleteBookmarkMutation__ * * To run a mutation, you first call `useDeleteBookmarkMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteBookmarkMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteBookmarkMutation, { data, loading, error }] = useDeleteBookmarkMutation({ * variables: { * id: // value for 'id' * }, * }); */ export function useDeleteBookmarkMutation( baseOptions?: Apollo.MutationHookOptions< DeleteBookmarkMutation, DeleteBookmarkMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation< DeleteBookmarkMutation, DeleteBookmarkMutationVariables >(DeleteBookmarkDocument, options) } export type DeleteBookmarkMutationHookResult = ReturnType< typeof useDeleteBookmarkMutation > export type DeleteBookmarkMutationResult = Apollo.MutationResult<DeleteBookmarkMutation> export type DeleteBookmarkMutationOptions = Apollo.BaseMutationOptions< DeleteBookmarkMutation, DeleteBookmarkMutationVariables > export const AddBookmarkDocument = gql` mutation addBookmark($data: AddBookmarkInput!) { addBookmark(data: $data) { ...BookmarkDetail } } ${BookmarkDetailFragmentDoc} ` export type AddBookmarkMutationFn = Apollo.MutationFunction< AddBookmarkMutation, AddBookmarkMutationVariables > /** * __useAddBookmarkMutation__ * * To run a mutation, you first call `useAddBookmarkMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAddBookmarkMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [addBookmarkMutation, { data, loading, error }] = useAddBookmarkMutation({ * variables: { * data: // value for 'data' * }, * }); */ export function useAddBookmarkMutation( baseOptions?: Apollo.MutationHookOptions< AddBookmarkMutation, AddBookmarkMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<AddBookmarkMutation, AddBookmarkMutationVariables>( AddBookmarkDocument, options ) } export type AddBookmarkMutationHookResult = ReturnType< typeof useAddBookmarkMutation > export type AddBookmarkMutationResult = Apollo.MutationResult<AddBookmarkMutation> export type AddBookmarkMutationOptions = Apollo.BaseMutationOptions< AddBookmarkMutation, AddBookmarkMutationVariables > export const AddCommentDocument = gql` mutation addComment($refId: ID!, $type: CommentType!, $text: String!) { addComment(refId: $refId, type: $type, text: $text) { ...CommentInfo } } ${CommentInfoFragmentDoc} ` export type AddCommentMutationFn = Apollo.MutationFunction< AddCommentMutation, AddCommentMutationVariables > /** * __useAddCommentMutation__ * * To run a mutation, you first call `useAddCommentMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAddCommentMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [addCommentMutation, { data, loading, error }] = useAddCommentMutation({ * variables: { * refId: // value for 'refId' * type: // value for 'type' * text: // value for 'text' * }, * }); */ export function useAddCommentMutation( baseOptions?: Apollo.MutationHookOptions< AddCommentMutation, AddCommentMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<AddCommentMutation, AddCommentMutationVariables>( AddCommentDocument, options ) } export type AddCommentMutationHookResult = ReturnType< typeof useAddCommentMutation > export type AddCommentMutationResult = Apollo.MutationResult<AddCommentMutation> export type AddCommentMutationOptions = Apollo.BaseMutationOptions< AddCommentMutation, AddCommentMutationVariables > export const EditCommentDocument = gql` mutation editComment($id: ID!, $text: String!) { editComment(id: $id, text: $text) { ...CommentInfo } } ${CommentInfoFragmentDoc} ` export type EditCommentMutationFn = Apollo.MutationFunction< EditCommentMutation, EditCommentMutationVariables > /** * __useEditCommentMutation__ * * To run a mutation, you first call `useEditCommentMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useEditCommentMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [editCommentMutation, { data, loading, error }] = useEditCommentMutation({ * variables: { * id: // value for 'id' * text: // value for 'text' * }, * }); */ export function useEditCommentMutation( baseOptions?: Apollo.MutationHookOptions< EditCommentMutation, EditCommentMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<EditCommentMutation, EditCommentMutationVariables>( EditCommentDocument, options ) } export type EditCommentMutationHookResult = ReturnType< typeof useEditCommentMutation > export type EditCommentMutationResult = Apollo.MutationResult<EditCommentMutation> export type EditCommentMutationOptions = Apollo.BaseMutationOptions< EditCommentMutation, EditCommentMutationVariables > export const DeleteCommentDocument = gql` mutation deleteComment($id: ID!) { deleteComment(id: $id) } ` export type DeleteCommentMutationFn = Apollo.MutationFunction< DeleteCommentMutation, DeleteCommentMutationVariables > /** * __useDeleteCommentMutation__ * * To run a mutation, you first call `useDeleteCommentMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteCommentMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteCommentMutation, { data, loading, error }] = useDeleteCommentMutation({ * variables: { * id: // value for 'id' * }, * }); */ export function useDeleteCommentMutation( baseOptions?: Apollo.MutationHookOptions< DeleteCommentMutation, DeleteCommentMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation< DeleteCommentMutation, DeleteCommentMutationVariables >(DeleteCommentDocument, options) } export type DeleteCommentMutationHookResult = ReturnType< typeof useDeleteCommentMutation > export type DeleteCommentMutationResult = Apollo.MutationResult<DeleteCommentMutation> export type DeleteCommentMutationOptions = Apollo.BaseMutationOptions< DeleteCommentMutation, DeleteCommentMutationVariables > export const EditEmailSubscriptionDocument = gql` mutation editEmailSubscription($data: EmailSubscriptionInput) { editEmailSubscription(data: $data) { emailSubscriptions { subscribed type } } } ` export type EditEmailSubscriptionMutationFn = Apollo.MutationFunction< EditEmailSubscriptionMutation, EditEmailSubscriptionMutationVariables > /** * __useEditEmailSubscriptionMutation__ * * To run a mutation, you first call `useEditEmailSubscriptionMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useEditEmailSubscriptionMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [editEmailSubscriptionMutation, { data, loading, error }] = useEditEmailSubscriptionMutation({ * variables: { * data: // value for 'data' * }, * }); */ export function useEditEmailSubscriptionMutation( baseOptions?: Apollo.MutationHookOptions< EditEmailSubscriptionMutation, EditEmailSubscriptionMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation< EditEmailSubscriptionMutation, EditEmailSubscriptionMutationVariables >(EditEmailSubscriptionDocument, options) } export type EditEmailSubscriptionMutationHookResult = ReturnType< typeof useEditEmailSubscriptionMutation > export type EditEmailSubscriptionMutationResult = Apollo.MutationResult<EditEmailSubscriptionMutation> export type EditEmailSubscriptionMutationOptions = Apollo.BaseMutationOptions< EditEmailSubscriptionMutation, EditEmailSubscriptionMutationVariables > export const EditPostDocument = gql` mutation editPost($id: ID!, $data: EditPostInput!) { editPost(id: $id, data: $data) { ...PostDetail } } ${PostDetailFragmentDoc} ` export type EditPostMutationFn = Apollo.MutationFunction< EditPostMutation, EditPostMutationVariables > /** * __useEditPostMutation__ * * To run a mutation, you first call `useEditPostMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useEditPostMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [editPostMutation, { data, loading, error }] = useEditPostMutation({ * variables: { * id: // value for 'id' * data: // value for 'data' * }, * }); */ export function useEditPostMutation( baseOptions?: Apollo.MutationHookOptions< EditPostMutation, EditPostMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<EditPostMutation, EditPostMutationVariables>( EditPostDocument, options ) } export type EditPostMutationHookResult = ReturnType<typeof useEditPostMutation> export type EditPostMutationResult = Apollo.MutationResult<EditPostMutation> export type EditPostMutationOptions = Apollo.BaseMutationOptions< EditPostMutation, EditPostMutationVariables > export const DeletePostDocument = gql` mutation deletePost($id: ID!) { deletePost(id: $id) } ` export type DeletePostMutationFn = Apollo.MutationFunction< DeletePostMutation, DeletePostMutationVariables > /** * __useDeletePostMutation__ * * To run a mutation, you first call `useDeletePostMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeletePostMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deletePostMutation, { data, loading, error }] = useDeletePostMutation({ * variables: { * id: // value for 'id' * }, * }); */ export function useDeletePostMutation( baseOptions?: Apollo.MutationHookOptions< DeletePostMutation, DeletePostMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<DeletePostMutation, DeletePostMutationVariables>( DeletePostDocument, options ) } export type DeletePostMutationHookResult = ReturnType< typeof useDeletePostMutation > export type DeletePostMutationResult = Apollo.MutationResult<DeletePostMutation> export type DeletePostMutationOptions = Apollo.BaseMutationOptions< DeletePostMutation, DeletePostMutationVariables > export const AddPostDocument = gql` mutation addPost($data: AddPostInput!) { addPost(data: $data) { ...PostDetail } } ${PostDetailFragmentDoc} ` export type AddPostMutationFn = Apollo.MutationFunction< AddPostMutation, AddPostMutationVariables > /** * __useAddPostMutation__ * * To run a mutation, you first call `useAddPostMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAddPostMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [addPostMutation, { data, loading, error }] = useAddPostMutation({ * variables: { * data: // value for 'data' * }, * }); */ export function useAddPostMutation( baseOptions?: Apollo.MutationHookOptions< AddPostMutation, AddPostMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<AddPostMutation, AddPostMutationVariables>( AddPostDocument, options ) } export type AddPostMutationHookResult = ReturnType<typeof useAddPostMutation> export type AddPostMutationResult = Apollo.MutationResult<AddPostMutation> export type AddPostMutationOptions = Apollo.BaseMutationOptions< AddPostMutation, AddPostMutationVariables > export const EditQuestionDocument = gql` mutation editQuestion($id: ID!, $data: EditQuestionInput!) { editQuestion(id: $id, data: $data) { ...QuestionDetail } } ${QuestionDetailFragmentDoc} ` export type EditQuestionMutationFn = Apollo.MutationFunction< EditQuestionMutation, EditQuestionMutationVariables > /** * __useEditQuestionMutation__ * * To run a mutation, you first call `useEditQuestionMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useEditQuestionMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [editQuestionMutation, { data, loading, error }] = useEditQuestionMutation({ * variables: { * id: // value for 'id' * data: // value for 'data' * }, * }); */ export function useEditQuestionMutation( baseOptions?: Apollo.MutationHookOptions< EditQuestionMutation, EditQuestionMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation< EditQuestionMutation, EditQuestionMutationVariables >(EditQuestionDocument, options) } export type EditQuestionMutationHookResult = ReturnType< typeof useEditQuestionMutation > export type EditQuestionMutationResult = Apollo.MutationResult<EditQuestionMutation> export type EditQuestionMutationOptions = Apollo.BaseMutationOptions< EditQuestionMutation, EditQuestionMutationVariables > export const DeleteQuestionDocument = gql` mutation deleteQuestion($id: ID!) { deleteQuestion(id: $id) } ` export type DeleteQuestionMutationFn = Apollo.MutationFunction< DeleteQuestionMutation, DeleteQuestionMutationVariables > /** * __useDeleteQuestionMutation__ * * To run a mutation, you first call `useDeleteQuestionMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteQuestionMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteQuestionMutation, { data, loading, error }] = useDeleteQuestionMutation({ * variables: { * id: // value for 'id' * }, * }); */ export function useDeleteQuestionMutation( baseOptions?: Apollo.MutationHookOptions< DeleteQuestionMutation, DeleteQuestionMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation< DeleteQuestionMutation, DeleteQuestionMutationVariables >(DeleteQuestionDocument, options) } export type DeleteQuestionMutationHookResult = ReturnType< typeof useDeleteQuestionMutation > export type DeleteQuestionMutationResult = Apollo.MutationResult<DeleteQuestionMutation> export type DeleteQuestionMutationOptions = Apollo.BaseMutationOptions< DeleteQuestionMutation, DeleteQuestionMutationVariables > export const AddQuestionDocument = gql` mutation addQuestion($data: AddQuestionInput!) { addQuestion(data: $data) { ...QuestionDetail } } ${QuestionDetailFragmentDoc} ` export type AddQuestionMutationFn = Apollo.MutationFunction< AddQuestionMutation, AddQuestionMutationVariables > /** * __useAddQuestionMutation__ * * To run a mutation, you first call `useAddQuestionMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAddQuestionMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [addQuestionMutation, { data, loading, error }] = useAddQuestionMutation({ * variables: { * data: // value for 'data' * }, * }); */ export function useAddQuestionMutation( baseOptions?: Apollo.MutationHookOptions< AddQuestionMutation, AddQuestionMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<AddQuestionMutation, AddQuestionMutationVariables>( AddQuestionDocument, options ) } export type AddQuestionMutationHookResult = ReturnType< typeof useAddQuestionMutation > export type AddQuestionMutationResult = Apollo.MutationResult<AddQuestionMutation> export type AddQuestionMutationOptions = Apollo.BaseMutationOptions< AddQuestionMutation, AddQuestionMutationVariables > export const ToggleReactionDocument = gql` mutation toggleReaction($refId: ID!, $type: ReactionType!) { toggleReaction(refId: $refId, type: $type) { ... on Stack { id reactionCount viewerHasReacted } ... on Bookmark { id url reactionCount viewerHasReacted } ... on Question { id reactionCount viewerHasReacted } ... on Post { id reactionCount viewerHasReacted } } } ` export type ToggleReactionMutationFn = Apollo.MutationFunction< ToggleReactionMutation, ToggleReactionMutationVariables > /** * __useToggleReactionMutation__ * * To run a mutation, you first call `useToggleReactionMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useToggleReactionMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [toggleReactionMutation, { data, loading, error }] = useToggleReactionMutation({ * variables: { * refId: // value for 'refId' * type: // value for 'type' * }, * }); */ export function useToggleReactionMutation( baseOptions?: Apollo.MutationHookOptions< ToggleReactionMutation, ToggleReactionMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation< ToggleReactionMutation, ToggleReactionMutationVariables >(ToggleReactionDocument, options) } export type ToggleReactionMutationHookResult = ReturnType< typeof useToggleReactionMutation > export type ToggleReactionMutationResult = Apollo.MutationResult<ToggleReactionMutation> export type ToggleReactionMutationOptions = Apollo.BaseMutationOptions< ToggleReactionMutation, ToggleReactionMutationVariables > export const EditStackDocument = gql` mutation editStack($id: ID!, $data: EditStackInput!) { editStack(id: $id, data: $data) { ...StackDetail } } ${StackDetailFragmentDoc} ` export type EditStackMutationFn = Apollo.MutationFunction< EditStackMutation, EditStackMutationVariables > /** * __useEditStackMutation__ * * To run a mutation, you first call `useEditStackMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useEditStackMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [editStackMutation, { data, loading, error }] = useEditStackMutation({ * variables: { * id: // value for 'id' * data: // value for 'data' * }, * }); */ export function useEditStackMutation( baseOptions?: Apollo.MutationHookOptions< EditStackMutation, EditStackMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<EditStackMutation, EditStackMutationVariables>( EditStackDocument, options ) } export type EditStackMutationHookResult = ReturnType< typeof useEditStackMutation > export type EditStackMutationResult = Apollo.MutationResult<EditStackMutation> export type EditStackMutationOptions = Apollo.BaseMutationOptions< EditStackMutation, EditStackMutationVariables > export const DeleteStackDocument = gql` mutation deleteStack($id: ID!) { deleteStack(id: $id) } ` export type DeleteStackMutationFn = Apollo.MutationFunction< DeleteStackMutation, DeleteStackMutationVariables > /** * __useDeleteStackMutation__ * * To run a mutation, you first call `useDeleteStackMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteStackMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteStackMutation, { data, loading, error }] = useDeleteStackMutation({ * variables: { * id: // value for 'id' * }, * }); */ export function useDeleteStackMutation( baseOptions?: Apollo.MutationHookOptions< DeleteStackMutation, DeleteStackMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<DeleteStackMutation, DeleteStackMutationVariables>( DeleteStackDocument, options ) } export type DeleteStackMutationHookResult = ReturnType< typeof useDeleteStackMutation > export type DeleteStackMutationResult = Apollo.MutationResult<DeleteStackMutation> export type DeleteStackMutationOptions = Apollo.BaseMutationOptions< DeleteStackMutation, DeleteStackMutationVariables > export const AddStackDocument = gql` mutation addStack($data: AddStackInput!) { addStack(data: $data) { ...StackDetail } } ${StackDetailFragmentDoc} ` export type AddStackMutationFn = Apollo.MutationFunction< AddStackMutation, AddStackMutationVariables > /** * __useAddStackMutation__ * * To run a mutation, you first call `useAddStackMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAddStackMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [addStackMutation, { data, loading, error }] = useAddStackMutation({ * variables: { * data: // value for 'data' * }, * }); */ export function useAddStackMutation( baseOptions?: Apollo.MutationHookOptions< AddStackMutation, AddStackMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<AddStackMutation, AddStackMutationVariables>( AddStackDocument, options ) } export type AddStackMutationHookResult = ReturnType<typeof useAddStackMutation> export type AddStackMutationResult = Apollo.MutationResult<AddStackMutation> export type AddStackMutationOptions = Apollo.BaseMutationOptions< AddStackMutation, AddStackMutationVariables > export const ToggleStackUserDocument = gql` mutation toggleStackUser($id: ID!) { toggleStackUser(id: $id) { ...StackCore usedBy { ...UserInfo } } } ${StackCoreFragmentDoc} ${UserInfoFragmentDoc} ` export type ToggleStackUserMutationFn = Apollo.MutationFunction< ToggleStackUserMutation, ToggleStackUserMutationVariables > /** * __useToggleStackUserMutation__ * * To run a mutation, you first call `useToggleStackUserMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useToggleStackUserMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [toggleStackUserMutation, { data, loading, error }] = useToggleStackUserMutation({ * variables: { * id: // value for 'id' * }, * }); */ export function useToggleStackUserMutation( baseOptions?: Apollo.MutationHookOptions< ToggleStackUserMutation, ToggleStackUserMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation< ToggleStackUserMutation, ToggleStackUserMutationVariables >(ToggleStackUserDocument, options) } export type ToggleStackUserMutationHookResult = ReturnType< typeof useToggleStackUserMutation > export type ToggleStackUserMutationResult = Apollo.MutationResult<ToggleStackUserMutation> export type ToggleStackUserMutationOptions = Apollo.BaseMutationOptions< ToggleStackUserMutation, ToggleStackUserMutationVariables > export const DeleteUserDocument = gql` mutation deleteUser { deleteUser } ` export type DeleteUserMutationFn = Apollo.MutationFunction< DeleteUserMutation, DeleteUserMutationVariables > /** * __useDeleteUserMutation__ * * To run a mutation, you first call `useDeleteUserMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteUserMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteUserMutation, { data, loading, error }] = useDeleteUserMutation({ * variables: { * }, * }); */ export function useDeleteUserMutation( baseOptions?: Apollo.MutationHookOptions< DeleteUserMutation, DeleteUserMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<DeleteUserMutation, DeleteUserMutationVariables>( DeleteUserDocument, options ) } export type DeleteUserMutationHookResult = ReturnType< typeof useDeleteUserMutation > export type DeleteUserMutationResult = Apollo.MutationResult<DeleteUserMutation> export type DeleteUserMutationOptions = Apollo.BaseMutationOptions< DeleteUserMutation, DeleteUserMutationVariables > export const EditUserDocument = gql` mutation editUser($data: EditUserInput) { editUser(data: $data) { ...UserInfo } } ${UserInfoFragmentDoc} ` export type EditUserMutationFn = Apollo.MutationFunction< EditUserMutation, EditUserMutationVariables > /** * __useEditUserMutation__ * * To run a mutation, you first call `useEditUserMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useEditUserMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [editUserMutation, { data, loading, error }] = useEditUserMutation({ * variables: { * data: // value for 'data' * }, * }); */ export function useEditUserMutation( baseOptions?: Apollo.MutationHookOptions< EditUserMutation, EditUserMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useMutation<EditUserMutation, EditUserMutationVariables>( EditUserDocument, options ) } export type EditUserMutationHookResult = ReturnType<typeof useEditUserMutation> export type EditUserMutationResult = Apollo.MutationResult<EditUserMutation> export type EditUserMutationOptions = Apollo.BaseMutationOptions< EditUserMutation, EditUserMutationVariables > export const GetBookmarksDocument = gql` query getBookmarks($first: Int, $after: String, $filter: BookmarkFilter) { bookmarks(first: $first, after: $after, filter: $filter) { ...BookmarksConnection } } ${BookmarksConnectionFragmentDoc} ` /** * __useGetBookmarksQuery__ * * To run a query within a React component, call `useGetBookmarksQuery` and pass it any options that fit your needs. * When your component renders, `useGetBookmarksQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetBookmarksQuery({ * variables: { * first: // value for 'first' * after: // value for 'after' * filter: // value for 'filter' * }, * }); */ export function useGetBookmarksQuery( baseOptions?: Apollo.QueryHookOptions< GetBookmarksQuery, GetBookmarksQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetBookmarksQuery, GetBookmarksQueryVariables>( GetBookmarksDocument, options ) } export function useGetBookmarksLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetBookmarksQuery, GetBookmarksQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetBookmarksQuery, GetBookmarksQueryVariables>( GetBookmarksDocument, options ) } export type GetBookmarksQueryHookResult = ReturnType< typeof useGetBookmarksQuery > export type GetBookmarksLazyQueryHookResult = ReturnType< typeof useGetBookmarksLazyQuery > export type GetBookmarksQueryResult = Apollo.QueryResult< GetBookmarksQuery, GetBookmarksQueryVariables > export const GetBookmarkDocument = gql` query getBookmark($id: ID!) { bookmark(id: $id) { ...BookmarkDetail } } ${BookmarkDetailFragmentDoc} ` /** * __useGetBookmarkQuery__ * * To run a query within a React component, call `useGetBookmarkQuery` and pass it any options that fit your needs. * When your component renders, `useGetBookmarkQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetBookmarkQuery({ * variables: { * id: // value for 'id' * }, * }); */ export function useGetBookmarkQuery( baseOptions: Apollo.QueryHookOptions< GetBookmarkQuery, GetBookmarkQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetBookmarkQuery, GetBookmarkQueryVariables>( GetBookmarkDocument, options ) } export function useGetBookmarkLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetBookmarkQuery, GetBookmarkQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetBookmarkQuery, GetBookmarkQueryVariables>( GetBookmarkDocument, options ) } export type GetBookmarkQueryHookResult = ReturnType<typeof useGetBookmarkQuery> export type GetBookmarkLazyQueryHookResult = ReturnType< typeof useGetBookmarkLazyQuery > export type GetBookmarkQueryResult = Apollo.QueryResult< GetBookmarkQuery, GetBookmarkQueryVariables > export const GetCommentsDocument = gql` query getComments($refId: ID!, $type: CommentType!) { comments(refId: $refId, type: $type) { ...CommentInfo } } ${CommentInfoFragmentDoc} ` /** * __useGetCommentsQuery__ * * To run a query within a React component, call `useGetCommentsQuery` and pass it any options that fit your needs. * When your component renders, `useGetCommentsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetCommentsQuery({ * variables: { * refId: // value for 'refId' * type: // value for 'type' * }, * }); */ export function useGetCommentsQuery( baseOptions: Apollo.QueryHookOptions< GetCommentsQuery, GetCommentsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetCommentsQuery, GetCommentsQueryVariables>( GetCommentsDocument, options ) } export function useGetCommentsLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetCommentsQuery, GetCommentsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetCommentsQuery, GetCommentsQueryVariables>( GetCommentsDocument, options ) } export type GetCommentsQueryHookResult = ReturnType<typeof useGetCommentsQuery> export type GetCommentsLazyQueryHookResult = ReturnType< typeof useGetCommentsLazyQuery > export type GetCommentsQueryResult = Apollo.QueryResult< GetCommentsQuery, GetCommentsQueryVariables > export const GetHackerNewsPostsDocument = gql` query getHackerNewsPosts { hackerNewsPosts { ...HackerNewsListItemInfo } } ${HackerNewsListItemInfoFragmentDoc} ` /** * __useGetHackerNewsPostsQuery__ * * To run a query within a React component, call `useGetHackerNewsPostsQuery` and pass it any options that fit your needs. * When your component renders, `useGetHackerNewsPostsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetHackerNewsPostsQuery({ * variables: { * }, * }); */ export function useGetHackerNewsPostsQuery( baseOptions?: Apollo.QueryHookOptions< GetHackerNewsPostsQuery, GetHackerNewsPostsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery< GetHackerNewsPostsQuery, GetHackerNewsPostsQueryVariables >(GetHackerNewsPostsDocument, options) } export function useGetHackerNewsPostsLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetHackerNewsPostsQuery, GetHackerNewsPostsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery< GetHackerNewsPostsQuery, GetHackerNewsPostsQueryVariables >(GetHackerNewsPostsDocument, options) } export type GetHackerNewsPostsQueryHookResult = ReturnType< typeof useGetHackerNewsPostsQuery > export type GetHackerNewsPostsLazyQueryHookResult = ReturnType< typeof useGetHackerNewsPostsLazyQuery > export type GetHackerNewsPostsQueryResult = Apollo.QueryResult< GetHackerNewsPostsQuery, GetHackerNewsPostsQueryVariables > export const GetHackerNewsPostDocument = gql` query getHackerNewsPost($id: ID!) { hackerNewsPost(id: $id) { ...HackerNewsPostInfo } } ${HackerNewsPostInfoFragmentDoc} ` /** * __useGetHackerNewsPostQuery__ * * To run a query within a React component, call `useGetHackerNewsPostQuery` and pass it any options that fit your needs. * When your component renders, `useGetHackerNewsPostQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetHackerNewsPostQuery({ * variables: { * id: // value for 'id' * }, * }); */ export function useGetHackerNewsPostQuery( baseOptions: Apollo.QueryHookOptions< GetHackerNewsPostQuery, GetHackerNewsPostQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery< GetHackerNewsPostQuery, GetHackerNewsPostQueryVariables >(GetHackerNewsPostDocument, options) } export function useGetHackerNewsPostLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetHackerNewsPostQuery, GetHackerNewsPostQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery< GetHackerNewsPostQuery, GetHackerNewsPostQueryVariables >(GetHackerNewsPostDocument, options) } export type GetHackerNewsPostQueryHookResult = ReturnType< typeof useGetHackerNewsPostQuery > export type GetHackerNewsPostLazyQueryHookResult = ReturnType< typeof useGetHackerNewsPostLazyQuery > export type GetHackerNewsPostQueryResult = Apollo.QueryResult< GetHackerNewsPostQuery, GetHackerNewsPostQueryVariables > export const GetPostsDocument = gql` query getPosts($filter: WritingFilter) { posts(filter: $filter) { ...PostListItem } } ${PostListItemFragmentDoc} ` /** * __useGetPostsQuery__ * * To run a query within a React component, call `useGetPostsQuery` and pass it any options that fit your needs. * When your component renders, `useGetPostsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetPostsQuery({ * variables: { * filter: // value for 'filter' * }, * }); */ export function useGetPostsQuery( baseOptions?: Apollo.QueryHookOptions<GetPostsQuery, GetPostsQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetPostsQuery, GetPostsQueryVariables>( GetPostsDocument, options ) } export function useGetPostsLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetPostsQuery, GetPostsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetPostsQuery, GetPostsQueryVariables>( GetPostsDocument, options ) } export type GetPostsQueryHookResult = ReturnType<typeof useGetPostsQuery> export type GetPostsLazyQueryHookResult = ReturnType< typeof useGetPostsLazyQuery > export type GetPostsQueryResult = Apollo.QueryResult< GetPostsQuery, GetPostsQueryVariables > export const GetPostDocument = gql` query getPost($slug: String!) { post(slug: $slug) { ...PostDetail } } ${PostDetailFragmentDoc} ` /** * __useGetPostQuery__ * * To run a query within a React component, call `useGetPostQuery` and pass it any options that fit your needs. * When your component renders, `useGetPostQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetPostQuery({ * variables: { * slug: // value for 'slug' * }, * }); */ export function useGetPostQuery( baseOptions: Apollo.QueryHookOptions<GetPostQuery, GetPostQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetPostQuery, GetPostQueryVariables>( GetPostDocument, options ) } export function useGetPostLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<GetPostQuery, GetPostQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetPostQuery, GetPostQueryVariables>( GetPostDocument, options ) } export type GetPostQueryHookResult = ReturnType<typeof useGetPostQuery> export type GetPostLazyQueryHookResult = ReturnType<typeof useGetPostLazyQuery> export type GetPostQueryResult = Apollo.QueryResult< GetPostQuery, GetPostQueryVariables > export const GetQuestionsDocument = gql` query getQuestions($first: Int, $after: String, $filter: QuestionFilter) { questions(first: $first, after: $after, filter: $filter) { ...QuestionsConnection } } ${QuestionsConnectionFragmentDoc} ` /** * __useGetQuestionsQuery__ * * To run a query within a React component, call `useGetQuestionsQuery` and pass it any options that fit your needs. * When your component renders, `useGetQuestionsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetQuestionsQuery({ * variables: { * first: // value for 'first' * after: // value for 'after' * filter: // value for 'filter' * }, * }); */ export function useGetQuestionsQuery( baseOptions?: Apollo.QueryHookOptions< GetQuestionsQuery, GetQuestionsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetQuestionsQuery, GetQuestionsQueryVariables>( GetQuestionsDocument, options ) } export function useGetQuestionsLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetQuestionsQuery, GetQuestionsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetQuestionsQuery, GetQuestionsQueryVariables>( GetQuestionsDocument, options ) } export type GetQuestionsQueryHookResult = ReturnType< typeof useGetQuestionsQuery > export type GetQuestionsLazyQueryHookResult = ReturnType< typeof useGetQuestionsLazyQuery > export type GetQuestionsQueryResult = Apollo.QueryResult< GetQuestionsQuery, GetQuestionsQueryVariables > export const GetQuestionDocument = gql` query getQuestion($id: ID!) { question(id: $id) { ...QuestionDetail } } ${QuestionDetailFragmentDoc} ` /** * __useGetQuestionQuery__ * * To run a query within a React component, call `useGetQuestionQuery` and pass it any options that fit your needs. * When your component renders, `useGetQuestionQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetQuestionQuery({ * variables: { * id: // value for 'id' * }, * }); */ export function useGetQuestionQuery( baseOptions: Apollo.QueryHookOptions< GetQuestionQuery, GetQuestionQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetQuestionQuery, GetQuestionQueryVariables>( GetQuestionDocument, options ) } export function useGetQuestionLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetQuestionQuery, GetQuestionQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetQuestionQuery, GetQuestionQueryVariables>( GetQuestionDocument, options ) } export type GetQuestionQueryHookResult = ReturnType<typeof useGetQuestionQuery> export type GetQuestionLazyQueryHookResult = ReturnType< typeof useGetQuestionLazyQuery > export type GetQuestionQueryResult = Apollo.QueryResult< GetQuestionQuery, GetQuestionQueryVariables > export const GetStacksDocument = gql` query getStacks($first: Int, $after: String) { stacks(first: $first, after: $after) { ...StacksConnection } } ${StacksConnectionFragmentDoc} ` /** * __useGetStacksQuery__ * * To run a query within a React component, call `useGetStacksQuery` and pass it any options that fit your needs. * When your component renders, `useGetStacksQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetStacksQuery({ * variables: { * first: // value for 'first' * after: // value for 'after' * }, * }); */ export function useGetStacksQuery( baseOptions?: Apollo.QueryHookOptions<GetStacksQuery, GetStacksQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetStacksQuery, GetStacksQueryVariables>( GetStacksDocument, options ) } export function useGetStacksLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetStacksQuery, GetStacksQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetStacksQuery, GetStacksQueryVariables>( GetStacksDocument, options ) } export type GetStacksQueryHookResult = ReturnType<typeof useGetStacksQuery> export type GetStacksLazyQueryHookResult = ReturnType< typeof useGetStacksLazyQuery > export type GetStacksQueryResult = Apollo.QueryResult< GetStacksQuery, GetStacksQueryVariables > export const GetStackDocument = gql` query getStack($slug: String!) { stack(slug: $slug) { ...StackDetail } } ${StackDetailFragmentDoc} ` /** * __useGetStackQuery__ * * To run a query within a React component, call `useGetStackQuery` and pass it any options that fit your needs. * When your component renders, `useGetStackQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetStackQuery({ * variables: { * slug: // value for 'slug' * }, * }); */ export function useGetStackQuery( baseOptions: Apollo.QueryHookOptions<GetStackQuery, GetStackQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetStackQuery, GetStackQueryVariables>( GetStackDocument, options ) } export function useGetStackLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetStackQuery, GetStackQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetStackQuery, GetStackQueryVariables>( GetStackDocument, options ) } export type GetStackQueryHookResult = ReturnType<typeof useGetStackQuery> export type GetStackLazyQueryHookResult = ReturnType< typeof useGetStackLazyQuery > export type GetStackQueryResult = Apollo.QueryResult< GetStackQuery, GetStackQueryVariables > export const GetTagsDocument = gql` query getTags { tags { name } } ` /** * __useGetTagsQuery__ * * To run a query within a React component, call `useGetTagsQuery` and pass it any options that fit your needs. * When your component renders, `useGetTagsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetTagsQuery({ * variables: { * }, * }); */ export function useGetTagsQuery( baseOptions?: Apollo.QueryHookOptions<GetTagsQuery, GetTagsQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetTagsQuery, GetTagsQueryVariables>( GetTagsDocument, options ) } export function useGetTagsLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<GetTagsQuery, GetTagsQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetTagsQuery, GetTagsQueryVariables>( GetTagsDocument, options ) } export type GetTagsQueryHookResult = ReturnType<typeof useGetTagsQuery> export type GetTagsLazyQueryHookResult = ReturnType<typeof useGetTagsLazyQuery> export type GetTagsQueryResult = Apollo.QueryResult< GetTagsQuery, GetTagsQueryVariables > export const GetUserDocument = gql` query getUser($username: String!) { user(username: $username) { ...UserInfo } } ${UserInfoFragmentDoc} ` /** * __useGetUserQuery__ * * To run a query within a React component, call `useGetUserQuery` and pass it any options that fit your needs. * When your component renders, `useGetUserQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetUserQuery({ * variables: { * username: // value for 'username' * }, * }); */ export function useGetUserQuery( baseOptions: Apollo.QueryHookOptions<GetUserQuery, GetUserQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<GetUserQuery, GetUserQueryVariables>( GetUserDocument, options ) } export function useGetUserLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<GetUserQuery, GetUserQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<GetUserQuery, GetUserQueryVariables>( GetUserDocument, options ) } export type GetUserQueryHookResult = ReturnType<typeof useGetUserQuery> export type GetUserLazyQueryHookResult = ReturnType<typeof useGetUserLazyQuery> export type GetUserQueryResult = Apollo.QueryResult< GetUserQuery, GetUserQueryVariables > export const ViewerDocument = gql` query viewer { viewer { ...UserInfo } } ${UserInfoFragmentDoc} ` /** * __useViewerQuery__ * * To run a query within a React component, call `useViewerQuery` and pass it any options that fit your needs. * When your component renders, `useViewerQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useViewerQuery({ * variables: { * }, * }); */ export function useViewerQuery( baseOptions?: Apollo.QueryHookOptions<ViewerQuery, ViewerQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery<ViewerQuery, ViewerQueryVariables>( ViewerDocument, options ) } export function useViewerLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<ViewerQuery, ViewerQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery<ViewerQuery, ViewerQueryVariables>( ViewerDocument, options ) } export type ViewerQueryHookResult = ReturnType<typeof useViewerQuery> export type ViewerLazyQueryHookResult = ReturnType<typeof useViewerLazyQuery> export type ViewerQueryResult = Apollo.QueryResult< ViewerQuery, ViewerQueryVariables > export const GetViewerWithSettingsDocument = gql` query getViewerWithSettings { viewer { ...UserInfo ...UserSettings } } ${UserInfoFragmentDoc} ${UserSettingsFragmentDoc} ` /** * __useGetViewerWithSettingsQuery__ * * To run a query within a React component, call `useGetViewerWithSettingsQuery` and pass it any options that fit your needs. * When your component renders, `useGetViewerWithSettingsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetViewerWithSettingsQuery({ * variables: { * }, * }); */ export function useGetViewerWithSettingsQuery( baseOptions?: Apollo.QueryHookOptions< GetViewerWithSettingsQuery, GetViewerWithSettingsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useQuery< GetViewerWithSettingsQuery, GetViewerWithSettingsQueryVariables >(GetViewerWithSettingsDocument, options) } export function useGetViewerWithSettingsLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< GetViewerWithSettingsQuery, GetViewerWithSettingsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions } return Apollo.useLazyQuery< GetViewerWithSettingsQuery, GetViewerWithSettingsQueryVariables >(GetViewerWithSettingsDocument, options) } export type GetViewerWithSettingsQueryHookResult = ReturnType< typeof useGetViewerWithSettingsQuery > export type GetViewerWithSettingsLazyQueryHookResult = ReturnType< typeof useGetViewerWithSettingsLazyQuery > export type GetViewerWithSettingsQueryResult = Apollo.QueryResult< GetViewerWithSettingsQuery, GetViewerWithSettingsQueryVariables >
the_stack
import * as Bluebird from 'bluebird'; import { groupBy, maxBy } from 'lodash'; import * as moment from 'moment'; import { fn, Op } from 'sequelize'; import { Article, Comment, CommentScore, CommentScoreRequest, CommentSummaryScore, Decision, ENDPOINT_TYPE_API, findOrCreateTagByKey, IResolution, IScorerExtra, isModerationRule, isUser, ModerationRule, Tag, User, USER_GROUP_MODERATOR, } from '../models'; import {sequelize} from '../sequelize'; import { cacheCommentTopScores, cacheTextSize, denormalizeCommentCountsForArticle, denormalizeCountsForComment, } from '../domain'; import {logger} from '../logger'; import {processRulesForComment} from './rules'; import {IScoreData, IScores, IShim, ISummaryScores} from './shim'; import {getIsDoneScoring} from './state'; import {createShim as createApiShim} from './apiShim'; import {commentModeratedHook} from './hooks'; const shims = new Map<number, IShim>(); export async function sendToScorer(comment: Comment, scorer: User) { try { // Destroy existing comment score request for user. await CommentScoreRequest.destroy({ where: { commentId: comment.id, userId: scorer.id, }, }); let shim = shims.get(scorer.id); if (!shim) { const extra = scorer.extra as IScorerExtra; if (!extra) { logger.error(`Missing endpoint config for scorer ${scorer.id}`); return; } if (extra.endpointType === ENDPOINT_TYPE_API) { shim = await createApiShim(scorer, processMachineScore); } else { logger.error(`Unknown moderator endpoint type: ${extra.endpoint} for scorer ${scorer.id}`); return; } shims.set(scorer.id, shim); } // Create score request const csr = await CommentScoreRequest.create({ commentId: comment.id, userId: scorer.id, sentAt: fn('now'), }); await shim.sendToScorer(comment, csr.id); } catch (err) { logger.error(`Error posting comment id ${comment.id} for scoring: ${err}`); } } export async function checkScoringDone(comment: Comment): Promise<void> { // Mark timestamp for when comment was last sent for scoring comment.sentForScoring = new Date(); await comment.save(); const isDoneScoring = await getIsDoneScoring(comment.id); if (isDoneScoring) { await completeMachineScoring(comment.id); } } /** * Send passed in comment for scoring against all active service Users. */ export async function sendForScoring(comment: Comment): Promise<void> { const serviceUsers = await User.findAll({ where: { group: USER_GROUP_MODERATOR, isActive: true, }, } as any); let foundServiceUser = false; for (const scorer of serviceUsers) { await sendToScorer(comment, scorer); foundServiceUser = true; } if (foundServiceUser) { await checkScoringDone(comment); } else { logger.info('No active Comment Scorers found'); } } /** * Return a cutoff date object for re-sending score requests. Every CommentScoreRequest * whose `sentAt` date is before this should be re-sent for scoring. */ export function resendCutoff() { return moment().subtract(5, 'minutes').toDate(); } /** * Get all comment instances that were sent for scoring before the `resendCutoff` * who have not been marked `isScored` or resolved */ export async function getCommentsToResendForScoring( processCommentLimit?: number, ): Promise<Array<Comment>> { const findOpts = { where: { isAccepted: null, isScored: false, sentForScoring: {[Op.lt]: resendCutoff()}, }, include: [Article], } as any; if ('undefined' !== typeof processCommentLimit) { findOpts.limit = processCommentLimit; } return await Comment.findAll(findOpts); } /** * Resend a comment to be scored again. */ export async function resendForScoring(comment: Comment): Promise<void> { logger.info(`Re-sending comment id ${comment.id} for scoring`); await sendForScoring(comment); } /** * Receive a single score. Data object should have: commentId, serviceUserId, sourceType, * score, and optionally annotationStart and annotationEnd */ export async function processMachineScore( commentId: number, serviceUserId: number, scoreData: IScoreData, ): Promise<void> { logger.info('PROCESS MACHINE SCORE ::', commentId, serviceUserId, JSON.stringify(scoreData)); const comment = (await Comment.findByPk(commentId))!; // Find matching comment score request const commentScoreRequest = await CommentScoreRequest.findOne({ where: { commentId, userId: serviceUserId, }, order: [['sentAt', 'DESC']], }); if (!commentScoreRequest) { throw new Error('Comment score request not found'); } // Find/create all tags present in scores const scoresTags = await findOrCreateTagsByKey(Object.keys(scoreData.scores)); const commentScoresData = compileScoresData( 'Machine', serviceUserId, scoreData.scores, { comment, commentScoreRequest, tags: scoresTags, }, ); // Find/create all tags present in summary scores const summaryScoresTags = await findOrCreateTagsByKey(Object.keys(scoreData.summaryScores)); // Clear old comment scores and create new comment scores await CommentScore.destroy({ where: { commentId, userId: serviceUserId, }, }); await CommentScore.bulkCreate(commentScoresData); // TODO send update notification that comment has been updated const commentSummaryScoresData = compileSummaryScoresData( scoreData.summaryScores, comment, summaryScoresTags, ); await sequelize.transaction(async (t) => { for (const c of commentSummaryScoresData) { await CommentSummaryScore.upsert(c, {transaction: t, returning: false}); } }); await updateMaxSummaryScore(comment); // Mark the comment score request as done commentScoreRequest.doneAt = new Date(); await commentScoreRequest.save(); } export async function updateMaxSummaryScore(comment: Comment): Promise<void> { const tagsInSummaryScore = await Tag.findAll({ where: { inSummaryScore: true, }, }); const summaryScores = await CommentSummaryScore.findAll({ where: { commentId: comment.id, tagId: { [Op.in]: tagsInSummaryScore.map((tag) => tag.id), }, }, }); if (summaryScores.length <= 0) { return; } const maxSummaryScores = maxBy(summaryScores, (score) => score.score); await comment.update({ maxSummaryScore: maxSummaryScores!.score, maxSummaryScoreTagId: maxSummaryScores!.tagId, }); } /** * Once all scores are in, process rules, record the decision and denormalize. */ export async function completeMachineScoring(commentId: number): Promise<void> { const comment = (await Comment.findByPk(commentId, { include: [Article], }))!; comment.isScored = true; await comment.save(); await cacheCommentTopScores(comment); await processRulesForComment(comment); await denormalizeCountsForComment(comment); await denormalizeCommentCountsForArticle(await comment.getArticle(), false); } /** * Take raw scores data and an object of model data and map it all together in an array to * bulk create comment scores with */ export function compileScoresData(sourceType: string, userId: number, scoreData: IScores, modelData: any) { sourceType = sourceType || 'Machine'; const tagsByKey = groupBy(modelData.tags, (tag: Tag) => tag.key); const data: Array<Pick<CommentScore, 'commentId' | 'commentScoreRequestId' | 'sourceType' | 'userId' | 'tagId' | 'score' | 'annotationStart' | 'annotationEnd'>> = []; Object .keys(scoreData) .forEach((tagKey) => { scoreData[tagKey].forEach((score) => { data.push({ commentId: modelData.comment.id, commentScoreRequestId: modelData.commentScoreRequest.id, sourceType, userId, tagId: tagsByKey[tagKey][0].id, score: score.score, annotationStart: score.begin, annotationEnd: score.end, }); }); }); return data; } /** * Take raw scores data and an object of model data and map it all together in an array to * bulk create comment summary scores with */ export function compileSummaryScoresData(scoreData: ISummaryScores, comment: Comment, tags: Array<Tag>) { const tagsByKey = groupBy(tags, (tag: Tag) => tag.key); const data: Array<Pick<CommentSummaryScore, 'commentId' | 'tagId' | 'score'>> = []; Object .keys(scoreData) .forEach((tagKey) => { data.push({ commentId: comment.id, tagId: (tagsByKey[tagKey][0]).id, score: scoreData[tagKey], }); }); return data; } /** * Given an array of tag keys, find or create them * * @param {array} keys Array of tag keys (strings) * @return {object} Promise object that resolves to an array of Tag model instances */ export async function findOrCreateTagsByKey( keys: Array<string>, ): Promise<Array<Tag>> { return Bluebird.mapSeries(keys, async (key) => { return await findOrCreateTagByKey(key); }); } /** * Save the action of a rule or user making a comment on a decision. */ export async function recordDecision( comment: Comment, status: IResolution, source: User | ModerationRule | null, ): Promise<Decision> { // Find out if we're overriding a previous decision. const previousDecisions = await comment.getDecisions({ where: {isCurrentDecision: true}, }); // Set previous active decisions to `isCurrentDecision` false. await Promise.all( previousDecisions.map((d) => d.update({isCurrentDecision: false})), ); await comment.update({updatedAt: fn('now')}); // Add new decision, isCurrentDecision defaults to true. const decision = await Decision.create({ commentId: comment.id, status, source: isUser(source) ? 'User' : 'Rule', userId: (source && isUser(source)) ? source.id : undefined, moderationRuleId: (source && isModerationRule(source)) ? source.id : undefined, }); await commentModeratedHook(comment); return decision; } export async function postProcessComment(comment: Comment): Promise<void> { const article = await comment.getArticle(); // Denormalize the moderation counts for the comment article await denormalizeCommentCountsForArticle(article, false); // Cache the size of the comment text. await cacheTextSize(comment, 696); // Try to create reply, return if not a reply const replyToSourceId = comment.replyToSourceId; if (!replyToSourceId) { return; } // Find a parent id const parent = await Comment.findOne({where: {sourceId: replyToSourceId}}); // If the parent cannot be found, then return if (!parent) { return; } await comment.update({ replyId: parent.id, }); }
the_stack
import { $Values } from 'utility-types'; import { Channel } from 'redux-saga'; import { all, call, fork, put } from 'redux-saga/effects'; import { getExtensionHash, Extension, ClientType, ROOT_DOMAIN_ID, } from '@colony/colony-js'; import { poll } from 'ethers/utils'; import { ContextModule, TEMP_getContext } from '~context/index'; import { DEFAULT_TOKEN_DECIMALS } from '~constants'; import { getLoggedInUser, refetchUserNotifications, CreateUserMutation, CreateUserDocument, CreateUserMutationVariables, SubscribeToColonyDocument, SubscribeToColonyMutation, SubscribeToColonyMutationVariables, cacheUpdates, NetworkExtensionVersionQuery, NetworkExtensionVersionQueryVariables, NetworkExtensionVersionDocument, getNetworkContracts, } from '~data/index'; import ENS from '~lib/ENS'; import { ActionTypes, Action, AllActions } from '~redux/index'; import { createAddress } from '~utils/web3'; import { putError, takeFrom, takeLatestCancellable } from '~utils/saga/effects'; import { TxConfig } from '~types/index'; import { transactionAddParams, transactionAddIdentifier, transactionReady, transactionLoadRelated, transactionPending, } from '../../core/actionCreators'; import { createTransaction, createTransactionChannels } from '../../core/sagas'; import { ipfsUpload } from '../../core/sagas/ipfs'; import { log } from '~utils/debug'; interface ChannelDefinition { channel: Channel<any>; index: number; id: string; } function* colonyCreate({ meta, payload: { colonyName: givenColonyName, displayName, tokenAddress: givenTokenAddress, tokenChoice, tokenName: givenTokenName, tokenSymbol: givenTokenSymbol, username: givenUsername, }, }: Action<ActionTypes.COLONY_CREATE>) { const { username: currentUsername, walletAddress } = yield getLoggedInUser(); const apolloClient = TEMP_getContext(ContextModule.ApolloClient); const colonyManager = TEMP_getContext(ContextModule.ColonyManager); const { networkClient } = colonyManager; const channelNames: string[] = []; /* * If the user did not claim a profile yet, define a tx to create the user. */ if (!currentUsername) { channelNames.push('createUser'); } /* * If the user opted to create a token, define a tx to create the token. */ if (tokenChoice === 'create') { channelNames.push('createToken'); } channelNames.push('createColony'); /* * If the user opted to create a token, define txs to manage the token. */ if (tokenChoice === 'create') { channelNames.push('deployTokenAuthority'); channelNames.push('setTokenAuthority'); channelNames.push('setOwner'); } channelNames.push('deployOneTx'); channelNames.push('setOneTxRoleAdministration'); channelNames.push('setOneTxRoleFunding'); /* * Define a manifest of transaction ids and their respective channels. */ const channels: { [id: string]: ChannelDefinition; } = yield call(createTransactionChannels, meta.id, channelNames); const { createColony, createToken, createUser, deployOneTx, setOneTxRoleAdministration, setOneTxRoleFunding, deployTokenAuthority, setTokenAuthority, setOwner, } = channels; const createGroupedTransaction = ( { id, index }: $Values<typeof channels>, config: TxConfig, ) => fork(createTransaction, id, { ...config, group: { key: 'createColony', id: meta.id, index, }, }); /* * Create all transactions for the group. */ try { const colonyName = ENS.normalize(givenColonyName); const username = ENS.normalize(givenUsername); const tokenName = givenTokenName; const tokenSymbol = givenTokenSymbol; if (createUser) { yield createGroupedTransaction(createUser, { context: ClientType.NetworkClient, methodName: 'registerUserLabel', params: [username, ''], ready: true, }); } if (createToken) { yield createGroupedTransaction(createToken, { context: ClientType.NetworkClient, methodName: 'deployToken', params: [tokenName, tokenSymbol, DEFAULT_TOKEN_DECIMALS], }); } if (createColony) { yield createGroupedTransaction(createColony, { context: ClientType.NetworkClient, methodName: 'createColony(address,uint256,string,string)', ready: false, }); } if (deployTokenAuthority) { yield createGroupedTransaction(deployTokenAuthority, { context: ClientType.ColonyClient, methodName: 'deployTokenAuthority', ready: false, }); } if (setTokenAuthority) { yield createGroupedTransaction(setTokenAuthority, { context: ClientType.TokenClient, methodName: 'setAuthority', ready: false, }); } if (setOwner) { yield createGroupedTransaction(setOwner, { context: ClientType.TokenClient, methodName: 'setOwner', ready: false, }); } if (deployOneTx) { yield createGroupedTransaction(deployOneTx, { context: ClientType.ColonyClient, methodName: 'installExtension', ready: false, }); } if (setOneTxRoleAdministration) { yield createGroupedTransaction(setOneTxRoleAdministration, { context: ClientType.ColonyClient, methodContext: 'setOneTxRoles', methodName: 'setAdministrationRoleWithProofs', ready: false, }); } if (setOneTxRoleFunding) { yield createGroupedTransaction(setOneTxRoleFunding, { context: ClientType.ColonyClient, methodContext: 'setOneTxRoles', methodName: 'setFundingRoleWithProofs', ready: false, }); } /* * Wait until all transactions are created. */ yield all( Object.keys(channels).map((id) => takeFrom(channels[id].channel, ActionTypes.TRANSACTION_CREATED), ), ); /* * Dispatch a success action; this progresses to next wizard step, * where transactions can get processed. */ yield put<AllActions>({ type: ActionTypes.COLONY_CREATE_SUCCESS, meta, payload: undefined, }); if (createUser) { /* * If the username is being created, wait for the transaction to succeed * before creating the profile store and dispatching a success action. */ yield takeFrom(createUser.channel, ActionTypes.TRANSACTION_SUCCEEDED); yield put<AllActions>(transactionLoadRelated(createUser.id, true)); yield apolloClient.mutate< CreateUserMutation, CreateUserMutationVariables >({ mutation: CreateUserDocument, variables: { createUserInput: { username }, loggedInUserInput: { username }, }, }); yield put<AllActions>(transactionLoadRelated(createUser.id, false)); yield refetchUserNotifications(walletAddress); } /* * For transactions that rely on the receipt/event data of previous transactions, * wait for these transactions to succeed, collect the data, and apply it to * the pending transactions. */ let tokenAddress: string; if (createToken) { const { payload: { deployedContractAddress }, } = yield takeFrom( createToken.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); tokenAddress = createAddress(deployedContractAddress); } else { if (!givenTokenAddress) { throw new Error('Token address not provided'); } tokenAddress = createAddress(givenTokenAddress); } /* * This is a bit of a cumbersome solution, but should serve fine currently, * until we find a way to properly stabilize IPFS uploads */ let colonyAddress; if (createColony) { /* * First IPFS upload try */ let colonyMetadataIpfsHash; try { colonyMetadataIpfsHash = yield call( ipfsUpload, JSON.stringify({ colonyName, colonyDisplayName: displayName, colonyAvatarHash: null, colonyTokens: [], }), ); } catch (error) { log.verbose('Could not upload the colony metadata IPFS. Retrying...'); log.verbose(error); /* * If the first try fails, then attempt to upload again * We assume the first error was due to a connection issue */ colonyMetadataIpfsHash = yield call( ipfsUpload, JSON.stringify({ colonyName, colonyDisplayName: displayName, colonyAvatarHash: null, colonyTokens: [], }), ); } const { version: latestVersion } = yield getNetworkContracts(); yield put( transactionAddParams(createColony.id, [ tokenAddress, latestVersion, colonyName, /* * If both upload attempts fail, set the value to an empty string * This is needed as the contract method expects a string (doesn't care * if it's empty) othwise the call will fail * * This way, even if we didn't upload the metadata, we can still * go forward with creating the colony, and relying on it's fallback * values to display it */ typeof colonyMetadataIpfsHash === 'string' ? colonyMetadataIpfsHash : '', ]), ); yield put(transactionReady(createColony.id)); const { payload: { eventData: { ColonyAdded: { colonyAddress: createdColonyAddress }, }, }, } = yield takeFrom( createColony.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); colonyAddress = createdColonyAddress; if (!colonyAddress) { return yield putError( ActionTypes.COLONY_CREATE_ERROR, new Error('Missing colony address'), meta, ); } yield put(transactionLoadRelated(createColony.id, true)); } if (createColony) { yield put(transactionLoadRelated(createColony.id, false)); } /* * Add a colonyAddress identifier to all pending transactions. */ yield all( [ deployTokenAuthority, setTokenAuthority, setOwner, deployOneTx, setOneTxRoleAdministration, setOneTxRoleFunding, ] .filter(Boolean) .map(({ id }) => put(transactionAddIdentifier(id, colonyAddress))), ); if (deployTokenAuthority) { /* * Deploy TokenAuthority */ const tokenLockingAddress = yield networkClient.getTokenLocking(); yield put( transactionAddParams(deployTokenAuthority.id, [ tokenAddress, [tokenLockingAddress], ]), ); yield put(transactionReady(deployTokenAuthority.id)); const { payload: { deployedContractAddress }, } = yield takeFrom( deployTokenAuthority.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); /* * Set Token authority (to deployed TokenAuthority) */ yield put( transactionAddParams(setTokenAuthority.id, [deployedContractAddress]), ); yield put(transactionReady(setTokenAuthority.id)); yield takeFrom( setTokenAuthority.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); } if (setOwner) { yield put(transactionAddParams(setOwner.id, [colonyAddress])); yield put(transactionReady(setOwner.id)); yield takeFrom(setOwner.channel, ActionTypes.TRANSACTION_SUCCEEDED); } if (deployOneTx) { const { data: { networkExtensionVersion }, } = yield apolloClient.query< NetworkExtensionVersionQuery, NetworkExtensionVersionQueryVariables >({ query: NetworkExtensionVersionDocument, variables: { extensionId: Extension.OneTxPayment, }, fetchPolicy: 'network-only', }); const [latestOneTxDepoyment] = networkExtensionVersion; /* * Deploy OneTx */ yield put( transactionAddParams(deployOneTx.id, [ getExtensionHash(Extension.OneTxPayment), latestOneTxDepoyment?.version || 0, ]), ); yield put(transactionReady(deployOneTx.id)); yield takeFrom(deployOneTx.channel, ActionTypes.TRANSACTION_SUCCEEDED); /* * Set OneTx administration role */ yield put(transactionPending(setOneTxRoleAdministration.id)); const oneTxPaymentExtension = yield poll( async () => { try { const client = await colonyManager.getClient( ClientType.OneTxPaymentClient, colonyAddress, ); return client; } catch (err) { return undefined; } }, { timeout: 30000, }, ); const extensionAddress = oneTxPaymentExtension.address; yield put( transactionAddParams(setOneTxRoleAdministration.id, [ extensionAddress, ROOT_DOMAIN_ID, true, ]), ); yield put(transactionReady(setOneTxRoleAdministration.id)); yield takeFrom( setOneTxRoleAdministration.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); /* * Set OneTx funding role */ yield put( transactionAddParams(setOneTxRoleFunding.id, [ extensionAddress, ROOT_DOMAIN_ID, true, ]), ); yield put(transactionReady(setOneTxRoleFunding.id)); yield colonyManager.setColonyClient(colonyAddress); yield takeFrom( setOneTxRoleFunding.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); } /* * Manually subscribe the user to the colony * * @NOTE That this just subscribes the user to a particular address, as we * don't have the capability any more, to check if that address is a valid * colony, on the server side * * However, we do know that his colony actually exists, since we just * created it, but be **WARNED** that his is race condition!! * * We just skirt around it by calling this mutation after the whole batch * of transactions have been sent, assuming that by that time, the subgraph * had time to ingest the new block in which the colony was created. * * However, due to various network conditions, this might not be case, and * the colony might not exist still. * * It's not a super-huge deal breaker, as a page refresh will solve it, * and the colony is still usable, just that it doesn't provide _that_ * nice of a user experience. */ yield apolloClient.mutate< SubscribeToColonyMutation, SubscribeToColonyMutationVariables >({ mutation: SubscribeToColonyDocument, variables: { input: { colonyAddress }, }, update: cacheUpdates.subscribeToColony(colonyAddress), }); return null; } catch (error) { yield putError(ActionTypes.COLONY_CREATE_ERROR, error, meta); // For non-transaction errors (where something is probably irreversibly wrong), // cancel the saga. return null; } finally { /* * Close all transaction channels. */ yield all( Object.keys(channels).map((id) => call([channels[id].channel, channels[id].channel.close]), ), ); } } export default function* colonyCreateSaga() { yield takeLatestCancellable( ActionTypes.COLONY_CREATE, ActionTypes.COLONY_CREATE_CANCEL, colonyCreate, ); }
the_stack
import { Param, Widget } from '../models/flutter-model'; import { applyOnDescendants, Border, findAndRemoveParam, parseBorderStyle, parseBoxShadow, parseStyleBackgroundSize, parseStyleColor, parseStyleDoubleValue, parseStyleRepeat, parseStyleUrl, parseTRBLStyle, unquote, toBorderRadiusCode, parsePropertyStyle } from '../tools'; import { Options } from '../watcher'; type Borders = { top?: Border, right?: Border, bottom?: Border, left?: Border } export function transformWidget(widget: Widget, options: Options): Widget { if (widget.name == 'Container' || widget.name == 'AnimatedContainer') { if (!widget.params) widget.params = [] const backgroundColorParam = findAndRemoveParam(widget, 'backgroundColor') const backgroundImageParam = findAndRemoveParam(widget, 'backgroundImage') const backgroundRepeatParam = findAndRemoveParam(widget, 'backgroundRepeat') const backgroundSizeParam = findAndRemoveParam(widget, 'backgroundSize') const borderParam = findAndRemoveParam(widget, 'border') const borderTopParam = findAndRemoveParam(widget, 'borderTop') const borderRightParam = findAndRemoveParam(widget, 'borderRight') const borderBottomParam = findAndRemoveParam(widget, 'borderBottom') const borderLeftParam = findAndRemoveParam(widget, 'borderLeft') const borderWidthParam = findAndRemoveParam(widget, 'borderWidth') const borderStyleParam = findAndRemoveParam(widget, 'borderStyle') const borderColorParam = findAndRemoveParam(widget, 'borderColor') const borderRadiusParam = findAndRemoveParam(widget, 'borderRadius') const boxShadowParam = findAndRemoveParam(widget, 'boxShadow') const shapeParam = findAndRemoveParam(widget, 'shape') // border let borders: Borders = {} if (borderParam && borderParam.value) { const border = parseBorderStyle(borderParam.value.toString()) borders.top = border borders.right = border borders.bottom = border borders.left = border } if (borderWidthParam && borderWidthParam.value) { const width = parseStyleDoubleValue(borderWidthParam.value.toString()) if (borders.top) { borders.top.width = width } else borders.top = { width } if (borders.right) { borders.right.width = width } else borders.right = { width } if (borders.bottom) { borders.bottom.width = width } else borders.bottom = { width } if (borders.left) { borders.left.width = width } else borders.left = { width } } if (borderStyleParam && borderStyleParam.value) { const style = parseStyleDoubleValue(borderStyleParam.value.toString()) if (borders.top) { borders.top.style = style } else borders.top = { style } if (borders.right) { borders.right.style = style } else borders.right = { style } if (borders.bottom) { borders.bottom.style = style } else borders.bottom = { style } if (borders.left) { borders.left.style = style } else borders.left = { style } } if (borderColorParam && borderColorParam.value) { const color = parseStyleColor(borderColorParam.value.toString()) if (borders.top) { borders.top.color = color } else borders.top = { color } if (borders.right) { borders.right.color = color } else borders.right = { color } if (borders.bottom) { borders.bottom.color = color } else borders.bottom = { color } if (borders.left) { borders.left.color = color } else borders.left = { color } } if (borderTopParam && borderTopParam.value) { const border = parseBorderStyle(borderTopParam.value.toString()) borders.top = border } if (borderRightParam && borderRightParam.value) { const border = parseBorderStyle(borderRightParam.value.toString()) borders.right = border } if (borderBottomParam && borderBottomParam.value) { const border = parseBorderStyle(borderBottomParam.value.toString()) borders.bottom = border } if (borderLeftParam && borderLeftParam.value) { const border = parseBorderStyle(borderLeftParam.value.toString()) borders.left = border } let borderWidget: Widget if (Object.keys(borders).length > 0) { borderWidget = toBorderWidget(borders) } // image let imageWidget: Widget if (backgroundImageParam && backgroundImageParam.value) { const imgLocation = parseStyleUrl(backgroundImageParam.value.toString()) if (imgLocation) { switch (imgLocation.type) { case 'asset': { imageWidget = { class: 'widget', name: options.tagClasses.backgroundAssetImg, constant: false, params: [ { class: 'param', resolved: false, type: 'literal', value: imgLocation.location } ] } break } case 'url': { imageWidget = { class: 'widget', name: options.tagClasses.backgroundUrlImg, constant: false, params: [ { class: 'param', resolved: false, type: 'literal', value: imgLocation.location } ] } break } } } } // decorationimage let decorationImageWidget: Widget if (imageWidget) { decorationImageWidget = { class: 'widget', name: 'DecorationImage', constant: false, params: [] } if (imageWidget) decorationImageWidget.params.push({ class: 'param', name: 'image', type: 'widget', resolved: false, value: imageWidget }) if (backgroundRepeatParam && backgroundRepeatParam.value) { decorationImageWidget.params.push({ class: 'param', name: 'repeat', type: 'expression', resolved: false, value: parseStyleRepeat(backgroundRepeatParam) }) } if (backgroundSizeParam && backgroundSizeParam.value) { decorationImageWidget.params.push({ class: 'param', name: 'fit', type: 'expression', resolved: false, value: parseStyleBackgroundSize(backgroundSizeParam) }) } } // box decoration let boxDecorationWidget: Widget if (borderWidget || backgroundColorParam || backgroundImageParam || decorationImageWidget || shapeParam || borderRadiusParam || boxShadowParam) { boxDecorationWidget = { class: 'widget', name: 'BoxDecoration', constant: false, params: [] } if (decorationImageWidget) boxDecorationWidget.params.push({ class: 'param', name: 'image', resolved: false, type: 'widget', value: decorationImageWidget }) if (borderWidget) boxDecorationWidget.params.push({ class: 'param', name: 'border', type: 'widget', resolved: true, value: borderWidget }) if (backgroundColorParam && backgroundColorParam.value) boxDecorationWidget.params.push({ class: 'param', name: 'color', type: 'expression', value: parseStyleColor(unquote(backgroundColorParam.value.toString())), resolved: true }) if (borderRadiusParam && borderRadiusParam.value) boxDecorationWidget.params.push({ class: 'param', name: 'borderRadius', type: 'expression', value: toBorderRadiusCode(borderRadiusParam), resolved: true }) if (shapeParam && shapeParam.value) boxDecorationWidget.params.push({ class: 'param', name: 'shape', type: 'expression', value: parsePropertyStyle('BoxShape', shapeParam), resolved: true }) if (boxShadowParam && boxShadowParam.value) { const values = boxShadowParam.value.toString().split(',') const boxShadows = values.map(value=>toBoxShadow(parseBoxShadow(value))) boxDecorationWidget.params.push({ class: 'param', name: 'boxShadow', type: 'array', value: boxShadows, resolved: true }) } } if (boxDecorationWidget) { widget.params.push({ class: 'param', name: 'decoration', type: 'widget', resolved: true, value: boxDecorationWidget }) } } // also apply the plugin to the rest of the widget tree of this widget applyOnDescendants(widget, descendant => transformWidget(descendant, options)) return widget } function toBorderSizeWidget(border: Border): Widget { const borderSideWidget: Widget = { class: 'widget', name: 'BorderSide', constant: false, params: [] } if (border.width) borderSideWidget.params.push({ class: 'param', name: 'width', resolved: true, type: 'expression', value: border.width }) if (border.style) borderSideWidget.params.push({ class: 'param', name: 'style', resolved: true, type: 'expression', value: `BorderStyle.${border.style}` }) if (border.color) borderSideWidget.params.push({ class: 'param', name: 'color', resolved: true, type: 'expression', value: border.color }) return borderSideWidget } function toBorderWidget(borders: Borders): Widget { const borderWidget: Widget = { class: 'widget', name: 'Border', constant: false, params: [] } if (borders.top) { borderWidget.params.push({ class: 'param', name: 'top', resolved: true, type: 'widget', value: toBorderSizeWidget(borders.top) }) } if (borders.right) { borderWidget.params.push({ class: 'param', name: 'right', resolved: true, type: 'widget', value: toBorderSizeWidget(borders.right) }) } if (borders.bottom) { borderWidget.params.push({ class: 'param', name: 'bottom', resolved: true, type: 'widget', value: toBorderSizeWidget(borders.bottom) }) } if (borders.left) { borderWidget.params.push({ class: 'param', name: 'left', resolved: true, type: 'widget', value: toBorderSizeWidget(borders.left) }) } return borderWidget } function toBoxShadow(boxShadow: { color?: string, hoffset: string, voffset: string, blur?: string, spread?: string }) : Widget { const params : Param[] = [] params.push({ class: 'param', type: 'expression', resolved: true, name: 'offset', value: `Offset(${boxShadow.hoffset}, ${boxShadow.voffset})` }) if(boxShadow.color) { params.push({ class: 'param', type: 'expression', resolved: true, name: 'color', value: boxShadow.color }) } if(boxShadow.blur) { params.push({ class: 'param', type: 'expression', resolved: true, name: 'blurRadius', value: boxShadow.blur }) } if(boxShadow.spread) { params.push({ class: 'param', type: 'expression', resolved: true, name: 'spreadRadius', value: boxShadow.spread }) } return { class: 'widget', constant: false, name: 'BoxShadow', params: params } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The CSS for the sticky header and expandable content came from here: * http://stackoverflow.com/questions/12605816/sticky-flexible-footers-and-headers-css-working-fine-in-webkit-but-not-in-gecko */ /** * @fileoverview A jQuery UI widget that wraps an element and displays it with a header panel. Intended for use on the * mobile site. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.pagePanelClass = VRS.globalOptions.pagePanelClass || 'pagePanel'; // The class to set on page headers. /** * The state held by a PagePanel widget. */ class PagePanel_State { /** * The element for the previous page button. */ previousPageElement: JQuery = null; /** * The element for the title label. */ titleElement: JQuery = null; /** * The element for the text in the title. */ titleTextElement: JQuery = null; /** * The element for the next page button */ nextPageElement: JQuery = null; /** * The original parent of the content that's been moved into the page. */ originalContentParent: JQuery = null; /** * The VRS.vrsMenu menu shown in the header panel, if any. */ headerMenu: MenuPlugin = null; /** * The jQuery element holding the header menu. */ headerMenuElement: JQuery = null; /** * The hook result for the locale changed event. */ localeChangedHookResult: IEventHandle = null; } /** * The options for the PagePanel widget. */ export interface PagePanel_Options { /** * The element that will be moved into the page's container. */ element: JQuery; /** * The name of the previous page to jump to. */ previousPageName?: string; /** * The key in VRS.$$ of the label for the previous page. */ previousPageLabelKey?: string; /** * The name of the next page to jump to. */ nextPageName?: string; /** * The key in VRS.$$ of the label for the next page. */ nextPageLabelKey?: string; /** * The key in VRS.$$ of the title for the page. */ titleLabelKey?: string; /** * The menu to display when the header's menu button is clicked. If omitted then no menu button is shown. */ headerMenu?: Menu; /** * True if a gap should be shown in the page footer. */ showFooterGap?: boolean; } /* * jQueryUIHelper methods */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; VRS.jQueryUIHelper.getPagePanelPlugin = function(jQueryElement: JQuery) : PagePanel { return jQueryElement.data('vrsVrsPagePanel'); } VRS.jQueryUIHelper.getPagePanelOptions = function(overrides?: PagePanel_Options) : PagePanel_Options { return $.extend({ element: null, previousPageName: null, previousPageLabelKey: null, nextPageName: null, nextPageLabelKey: null, titleLabelKey: null, headerMenu: null, showFooterGap: false }, overrides); } /** * A jQuery UI widget that wraps an element and displays it with a header panel. Intended for use on the mobile site. */ export class PagePanel extends JQueryUICustomWidget { options: PagePanel_Options; constructor() { super(); this.options = VRS.jQueryUIHelper.getPagePanelOptions(); } private _getState() : PagePanel_State { var result = this.element.data('vrsPageHeaderPanelState'); if(result === undefined) { result = new PagePanel_State() this.element.data('vrsPageHeaderPanelState', result); } return result; } _create() { var state = this._getState(); var options = this.options; this.element.addClass(VRS.globalOptions.pagePanelClass); state.originalContentParent = options.element.parent(); // The extra div wrappers are required by the CSS, don't zap them :) var headerPanel = $('<header/>') .addClass('headerPanel') .appendTo(this.element); var headerInner = $('<div/>') .appendTo(headerPanel); state.previousPageElement = $('<p/>') .addClass('previous vrsNoHighlight') .on('click', $.proxy(this._previousPageClicked, this)) .appendTo(headerInner); state.titleElement = $('<p/>') .addClass('title') .appendTo(headerInner); state.titleTextElement = $('<span/>') .appendTo(state.titleElement); if(options.headerMenu) { state.headerMenuElement = $('<span/>') .prependTo(state.titleElement) .vrsMenu(VRS.jQueryUIHelper.getMenuOptions({ menu: options.headerMenu })); state.headerMenu = VRS.jQueryUIHelper.getMenuPlugin(state.headerMenuElement); } state.nextPageElement = $('<p/>') .addClass('next vrsNoHighlight') .on('click', $.proxy(this._nextPageClicked, this)) .appendTo(headerInner); var elementParent = $('<div/>'); $('<section/>') .addClass('pageContent') .appendTo(this.element) .append($('<div/>') .append(elementParent) ); elementParent.append(options.element); if(options.showFooterGap) $('<div/>').addClass('pageFooterGap').appendTo(elementParent); state.localeChangedHookResult = VRS.globalisation.hookLocaleChanged(this._localeChanged, this); this._updateHeaderText(); } private _destroy() { var state = this._getState(); var options = this.options; if(state.localeChangedHookResult) { VRS.globalisation.unhook(state.localeChangedHookResult); state.localeChangedHookResult = null; } if(state.headerMenuElement) { state.headerMenu.destroy(); state.headerMenuElement.remove(); state.headerMenu = null; state.headerMenuElement = null; } if(state.previousPageElement) state.previousPageElement.off(); if(state.nextPageElement) state.nextPageElement.off(); if(state.originalContentParent) { options.element.appendTo(state.originalContentParent); state.originalContentParent = null; } } /** * Redraws the text in the header strip. */ private _updateHeaderText() { var state = this._getState(); var options = this.options; var updateText = function(element, labelKey) { if(element) { var text = labelKey ? VRS.globalisation.getText(labelKey) : ''; element.text(text); } }; updateText(state.previousPageElement, options.previousPageLabelKey); updateText(state.titleTextElement, options.titleLabelKey); updateText(state.nextPageElement, options.nextPageLabelKey); } /** * Does the work for the previous/next page clicked handlers. */ private _doPageClicked(event: Event, pageName: string) { var result = !(!!pageName); if(!result) { event.stopPropagation(); event.preventDefault(); setTimeout(function() { VRS.pageManager.show(pageName); }, 100); } return result; } /** * Called by jQuery when an option is changed. */ _setOption(key: string, value: any) { this._super(key, value); switch(key) { case 'previousPageLabelKey': case 'nextPageLabelKey': case 'titleLabelKey': this._updateHeaderText(); break; } } /** * Called when the previous page button is clicked. */ private _previousPageClicked(event: Event) { return this._doPageClicked(event, this.options.previousPageName); } /** * Called when the next page button is clicked. */ private _nextPageClicked(event: Event) { return this._doPageClicked(event, this.options.nextPageName); } /** * Called when the user changes the locale. */ private _localeChanged() { this._updateHeaderText(); } } $.widget('vrs.vrsPagePanel', new PagePanel()); } declare interface JQuery { vrsPagePanel(); vrsPagePanel(options: VRS.PagePanel_Options); vrsPagePanel(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
import { addListeners } from '../../../../../client/addListener' import classnames from '../../../../../client/classnames' import mergePropStyle from '../../../../../client/component/mergeStyle' import { Element } from '../../../../../client/element' import { makeCustomListener } from '../../../../../client/event/custom' import { makeResizeListener } from '../../../../../client/event/resize' import parentElement from '../../../../../client/platform/web/parentElement' import { SimNode, Simulation } from '../../../../../client/simulation' import { COLOR_NONE } from '../../../../../client/theme' import { Pod } from '../../../../../pod' import { System } from '../../../../../system' import { Dict } from '../../../../../types/Dict' import { IHTMLDivElement } from '../../../../../types/global/dom' import { Unlisten } from '../../../../../types/Unlisten' import { clamp } from '../../../../core/relation/Clamp/f' import Div from '../../Div/Component' import Frame from '../../Frame/Component' import Drawer, { KNOB_HEIGHT, Props as DrawerProps } from '../Drawer/Component' export interface CabinetDrawer extends DrawerProps { active?: boolean state?: { y?: number } } export interface Props { className?: string style?: Dict<string> hidden?: boolean } export const DEFAULT_STYLE = { position: 'absolute', right: '0', top: '0', width: '0', height: '0', } export default class Cabinet extends Element<IHTMLDivElement, Props> { private _cabinet: Div private _drawer: Dict<CabinetDrawer> = {} private _drawer_component: Dict<Drawer> = {} private _drawer_node: Dict<SimNode> = {} private _drawer_active: Set<string> = new Set() private _drawer_y: Dict<number> = {} private _simulation: Simulation private _component_frame: Dict<Frame> = {} private _width: number = 0 private _height: number = 0 // z-index private _z_index: number = 1 constructor($props: Props, $system: System, $pod: Pod) { super($props, $system, $pod) const { className, style = {} } = $props const cabinet = new Div( { className: classnames('cabinet', className), style: { ...DEFAULT_STYLE, ...style, }, }, this.$system, this.$pod ) this._cabinet = cabinet this._simulation = new Simulation({ n: 6, force: this._force, }) this._simulation.nodes(this._drawer_node) this._simulation.addListener('tick', this._tick) const $element = parentElement($system) this.$element = $element this.$subComponent = { cabinet, } this.$unbundled = false this.registerRoot(cabinet) } private _setActive(drawerId: string, active: boolean): void { if (active) { this._drawer_active.add(drawerId) } else { this._drawer_active.delete(drawerId) } } onPropChanged(prop: string, current: any): void { if (prop === 'className') { this._cabinet.setProp('className', current) } else if (prop === 'style') { this._cabinet.setProp('style', { ...DEFAULT_STYLE, ...current }) const { style = {} } = this.$props const { color = 'currentColor', backgroundColor = COLOR_NONE } = style for (const drawerId in this._component_frame) { const drawer = this._drawer_component[drawerId] mergePropStyle(drawer, { color, backgroundColor, }) } } else if (prop === 'disabled') { // TODO } else if (prop === 'hidden') { if (this._hidden && !current) { this.show(false) } else if (!this._hidden && current) { this.hide(false) } } } public setActive(drawerId: string, active: boolean): void { const drawer = this._drawer_component[drawerId] drawer.setProp('active', active) } public isActive(drawerId: string): boolean { return this._drawer_active.has(drawerId) } public getDrawer(drawerId: string): Drawer { return this._drawer_component[drawerId] } public setDrawerProp<K extends keyof DrawerProps>( drawerId: string, name: K, value: any ): void { const drawer_component = this.getDrawer(drawerId) drawer_component.setProp(name, value) } private _tick = () => { for (const drawer_id in this._drawer_node) { const { y } = this._drawer_node[drawer_id] const drawer = this._drawer_component[drawer_id] drawer.setProp('y', y) } } private _force = (alpha: number): void => { const entries = Object.entries(this._drawer_node) const n = entries.length for (let i = 0; i < n; i++) { const a_entry = entries[i] const [a_id, a] = a_entry const ay = a.y const ah = a.height for (let j = i + 1; j < n; j++) { const b_entry = entries[j] const [b_id, b] = b_entry const by = b.y const bh = b.height let l = 1 let s = 1 if (ay + ah <= by) { l = by - ay - ah s = -1 } else if (ay <= by) { l = ay + ah - by s = -1 } else if (by + bh <= ay) { l = ay - by - bh } else if (by <= ay) { l = by + bh - ay } else { s = -1 } l = Math.max(l, 3) const k = (s * (alpha * 150)) / l if (!this._drawer_inactivating.has(a_id)) { a.vy += k } if (!this._drawer_inactivating.has(b_id)) { b.vy -= k } } } for (const drawer_id in this._drawer_node) { if (!this._drawer_inactivating.has(drawer_id)) { const node = this._drawer_node[drawer_id] const { y, height } = node const dy = y + height / 2 - this._height / 2 node.vy -= (dy * alpha) / 10 } } } private _on_context_resize = // debounce( () => { // console.log('Cabinet', '_on_context_resize') const { $width, $height } = this.$context this._on_resize($width, $height) } // , 300) private _on_drawer_drag_start = (drawerId: string, y: number) => { // console.log('Cabinet', '_on_drawer_drag_start', y) const node = this._drawer_node[drawerId] if (node) { node.hy = y - node.y node.fy = node.y } } private _on_drawer_dragged = (drawerId: string, y: number) => { // console.log('Cabinet', '_on_drawer_dragged', y) const node = this._drawer_node[drawerId] if (node) { node.fy = y - node.hy node.y = node.fy this._startSimulation() } } private _on_drawer_drag_end = (drawerId: string) => { // console.log('Cabinet', '_on_drawer_drag_end') // this._start_simulation() const node = this._drawer_node[drawerId] if (node) { node.hy = 0 node.fy = undefined } } public addDrawers = (drawers: Dict<CabinetDrawer>) => { for (const drawerId in drawers) { const drawer = drawers[drawerId] this.addDrawer(drawerId, drawer) } } private _drawer_inactivating: Set<string> = new Set() public addDrawer = (drawerId: string, cabinetDrawer: CabinetDrawer) => { // console.log('Cabinet', 'addDrawer') // const { $width } = this.$context const { style = {}, hidden } = this.$props let { component, icon, title, active, state = {}, width = 0, height = KNOB_HEIGHT, } = cabinetDrawer const { y = 0 } = state const { color = 'currentColor', backgroundColor = COLOR_NONE } = style this._drawer[drawerId] = cabinetDrawer const drawer_component = new Drawer( { className: 'cabinet-drawer', component, active, icon, title, y, width, height, hidden, style: { backgroundColor, color, }, }, this.$system, this.$pod ) drawer_component.addEventListener( makeCustomListener('active', () => { // console.log('Cabinet', '_on_drawer_active') // increase zIndex of this drawer on active this._inc_drawer_z_index(drawerId) this._setActive(drawerId, true) this._drawer_y[drawerId] = this._drawer_node[drawerId].y const drawer = this._drawer[drawerId] const { component } = drawer if (component) { this._removeDrawerNode(drawerId) this._startSimulation() } const frame = this._component_frame[drawerId] frame.setProp('disabled', false) this.dispatchEvent('draweractive', { drawerId }) }) ) drawer_component.addEventListener( makeCustomListener('inactive', () => { // console.log('Cabinet', '_on_drawer_inactive') this._setActive(drawerId, false) const drawer = this._drawer[drawerId] const { component } = drawer if (component) { const y = this._drawer_y[drawerId] ?? this._height / 2 this._drawer_inactivating.add(drawerId) setTimeout(() => { this._drawer_inactivating.delete(drawerId) this._startSimulation(0.05) }, 200) this._addDrawerNode(drawerId, y) this._startSimulation(0.05) } const frame = this._component_frame[drawerId] frame.setProp('disabled', true) this.dispatchEvent('drawerinactive', { drawerId }) }) ) drawer_component.addEventListener( makeCustomListener('dragstart', ({ y }) => { // increase this drawer zIndex on dragstart this._inc_drawer_z_index(drawerId) this._drawer_y[drawerId] = y this._on_drawer_drag_start(drawerId, y) }) ) drawer_component.addEventListener( makeCustomListener('dragged', ({ y }) => { this._drawer_y[drawerId] = y this._on_drawer_dragged(drawerId, y) }) ) drawer_component.addEventListener( makeCustomListener('dragend', () => { this._on_drawer_drag_end(drawerId) }) ) this._drawer_component[drawerId] = drawer_component this._cabinet.appendChild(drawer_component) const { frame } = drawer_component this._component_frame[drawerId] = frame if (component) { frame.appendChild(component) } if (!active) { this._addDrawerNode(drawerId, y) } } private _addDrawerNode = (drawerId: string, y: number): void => { const x = 0 const r = KNOB_HEIGHT / 2 const node: SimNode = { _x: x, _y: y, ax: 0, ay: 0, x, y, fx: undefined, fy: undefined, shape: 'rect', r, width: 0, height: KNOB_HEIGHT, vx: 0, vy: 0, hx: 0, hy: 0, } this._drawer_node[drawerId] = node } private _removeDrawerNode = (drawerId: string): void => { delete this._drawer_node[drawerId] } private _startSimulation = (alpha: number = 0.1): void => { // console.log('Cabinet', '_startSimulation') this._simulation.alpha(alpha) this._simulation.start() } public removeDrawer(drawerId: string): void { const drawer = this._drawer_component[drawerId] this._cabinet.removeChild(drawer) delete this._drawer[drawerId] delete this._drawer_component[drawerId] delete this._drawer_node[drawerId] delete this._drawer_y[drawerId] delete this._drawer_active[drawerId] } public getDrawers(): Dict<Drawer> { return this._drawer_component } private _context_unlisten: Unlisten public onMount() { // console.log('Cabinet', 'onMount') const { $width, $height } = this.$context this._width = $width this._height = $height this._context_unlisten = addListeners(this.$context, [ makeResizeListener(this._on_context_resize), ]) this._startSimulation() } public onUnmount() { this._simulation.stop() this._context_unlisten() } private _inc_drawer_z_index = (drawerId: string): void => { // increase zIndex of this drawer const drawer_component = this._drawer_component[drawerId] drawer_component.drawer.$element.style.zIndex = `${this._z_index}` this._z_index++ } private _on_resize = ($width: number, $height: number) => { // console.log('Cabinet', '_on_resize', $width, $height) const dh = $height - this._height const dy = dh / 2 this._width = $width this._height = $height for (const drawer_id in this._drawer_component) { const y = this._drawer_y[drawer_id] ?? 0 const drawer_component = this._drawer_component[drawer_id] const _y = clamp(y + dy, 0, $height - KNOB_HEIGHT + 1) drawer_component.setProp('y', _y) const node = this._drawer_node[drawer_id] if (node) { node.y += dy } } this._tick() } private _hidden: boolean = false public show(animate: boolean): void { this._hidden = false for (const drawer_id in this._drawer_component) { const drawer = this._drawer_component[drawer_id] drawer.show(animate) } } public hide(animate: boolean): void { this._hidden = true for (const drawer_id in this._drawer_component) { const drawer = this._drawer_component[drawer_id] drawer.hide(animate) } } }
the_stack
import * as FluentUIBaseComponent from './baseComponent.js' type DotNetReferenceType = FluentUIBaseComponent.DotNetReferenceType; type IRectangle = FluentUIBaseComponent.IRectangle; type EventGroup = FluentUIBaseComponent.EventGroup; type EventParams = FluentUIBaseComponent.EventParams; const SELECTION_DISABLED_ATTRIBUTE_NAME = 'data-selection-disabled'; const SELECTION_INDEX_ATTRIBUTE_NAME = 'data-selection-index'; const SELECTION_TOGGLE_ATTRIBUTE_NAME = 'data-selection-toggle'; const SELECTION_INVOKE_ATTRIBUTE_NAME = 'data-selection-invoke'; const SELECTION_INVOKE_TOUCH_ATTRIBUTE_NAME = 'data-selection-touch-invoke'; const SELECTALL_TOGGLE_ALL_ATTRIBUTE_NAME = 'data-selection-all-toggle'; const SELECTION_SELECT_ATTRIBUTE_NAME = 'data-selection-select'; const selectionZones = new Map<number, SelectionZone>(); export function registerSelectionZone(dotNet: DotNetReferenceType, root: HTMLElement, props: ISelectionZoneProps) { let selectionZone = new SelectionZone(dotNet, root, props); selectionZones.set(dotNet._id, selectionZone); } export function updateProps(dotNet: DotNetReferenceType, props: ISelectionZoneProps) { let selectionZone = selectionZones.get(dotNet._id); if (typeof selectionZone !== 'undefined' && selectionZone !== null) { selectionZone.props = props; } } export function unregisterSelectionZone(dotNet: DotNetReferenceType) { let selectionZone = selectionZones.get(dotNet._id); if (typeof selectionZone !== 'undefined' && selectionZone !== null) { selectionZone.dispose(); selectionZones.delete(dotNet._id); } } export enum SelectionMode { none, single, multiple } interface ISelectionZoneProps { selectionMode: SelectionMode; isModal: boolean; disableAutoSelectOnInputElements: boolean; enterModalOnTouch: boolean; enableTouchInvocationTarget: boolean; onItemInvokeSet: boolean; } class SelectionZone { dotNet: DotNetReferenceType; root: HTMLElement; props: ISelectionZoneProps; private _events: EventGroup; private _async: FluentUIBaseComponent.Async; private _isCtrlPressed: boolean; private _isShiftPressed: boolean; private _isMetaPressed: boolean; private _isTabPressed: boolean; private _shouldHandleFocus: boolean; private _shouldHandleFocusTimeoutId: number | undefined; private _isTouch: boolean; private _isTouchTimeoutId: number | undefined; constructor(dotNet: DotNetReferenceType, root: HTMLElement, props: ISelectionZoneProps) { this.dotNet = dotNet; this.root = root; this.props = props; const win = FluentUIBaseComponent.getWindow(this.root); this._events = new FluentUIBaseComponent.EventGroup(this); this._async = new FluentUIBaseComponent.Async(this); this._events.on(win, 'keydown', this._updateModifiers); //this._events.on(document, 'click', this._findScrollParentAndTryClearOnEmptyClick); //this._events.on(document.body, 'touchstart', this._onTouchStartCapture, true); //this._events.on(document.body, 'touchend', this._onTouchStartCapture, true); //this._events.on(root, 'keydown', this._onKeyDown); //this._events.on(root, 'keydown', this._onKeyDownCapture, { capture: true }); this._events.on(root, 'mousedown', this._onMouseDown); this._events.on(root, 'mousedown', this._onMouseDownCapture, { capture: true }); this._events.on(root, 'click', this._onClick); //this._events.on(root, 'focus', this._onFocus, { capture: true }); //this._events.on(root, 'doubleclick', this._onDoubleClick); //this._events.on(root, 'contextmenu', this._onContextMenu); } public updateProps(props: ISelectionZoneProps): void { this.props = props; } public dispose(): void { this._events.dispose(); this._async.dispose(); } private _updateModifiers(ev: KeyboardEvent | MouseEvent) { this._isShiftPressed = ev.shiftKey; this._isCtrlPressed = ev.ctrlKey; this._isMetaPressed = ev.metaKey; const keyCode = (ev as KeyboardEvent).keyCode; this._isTabPressed = keyCode ? keyCode === FluentUIBaseComponent.KeyCodes.tab : false; //console.log('updatemodifiers'); } public ignoreNextFocus = (): void => { this._handleNextFocus(false); }; private _onMouseDownCapture = (ev: MouseEvent): void => { let target = ev.target as HTMLElement; if (document.activeElement !== target && !FluentUIBaseComponent.elementContains(document.activeElement as HTMLElement, target)) { this.ignoreNextFocus(); return; } if (!FluentUIBaseComponent.elementContains(target, this.root)) { return; } while (target !== this.root) { if (this._hasAttribute(target, SELECTION_INVOKE_ATTRIBUTE_NAME)) { this.ignoreNextFocus(); break; } target = FluentUIBaseComponent.getParent(target) as HTMLElement; } }; private _onMouseDown = async (ev: MouseEvent): Promise<void> => { this._updateModifiers(ev); let target = ev.target as HTMLElement; const itemRoot = await this._findItemRootAsync(target); // No-op if selection is disabled if (this._isSelectionDisabled(target)) { return; } while (target !== this.root) { if (this._hasAttribute(target, SELECTALL_TOGGLE_ALL_ATTRIBUTE_NAME)) { break; } else if (itemRoot) { if (this._hasAttribute(target, SELECTION_TOGGLE_ATTRIBUTE_NAME)) { break; } else if (this._hasAttribute(target, SELECTION_INVOKE_ATTRIBUTE_NAME)) { break; } else if ( (target === itemRoot || this._shouldAutoSelect(target)) && !this._isShiftPressed && !this._isCtrlPressed && !this._isMetaPressed ) { await this._onInvokeMouseDownAsync(ev, this._getItemIndex(itemRoot)); break; } else if ( this.props.disableAutoSelectOnInputElements && (target.tagName === 'A' || target.tagName === 'BUTTON' || target.tagName === 'INPUT') ) { return; } } target = FluentUIBaseComponent.getParent(target) as HTMLElement; } }; private async _onInvokeMouseDownAsync( ev: MouseEvent | KeyboardEvent, index: number, ): Promise<void> { // Only do work if item is not selected. var selected = await this.dotNet.invokeMethodAsync<boolean>("IsIndexSelected", index); if (selected) { return; } await this._clearAndSelectIndexAsync(index); } private async _clearAndSelectIndexAsync(index: number): Promise<void> { //const { selection } = this.props; let isAlreadySingleSelected: boolean = false; let selectedCount = await this.dotNet.invokeMethodAsync("GetSelectedCount"); if (selectedCount) { var indexSelected = await this.dotNet.invokeMethodAsync<boolean>("IsIndexSelected", index); isAlreadySingleSelected = indexSelected; } if (!isAlreadySingleSelected) { const isModal = this.props.isModal; //await this.dotNet.invokeMethodAsync("ClearAndSelectIndex", index); //selection.setChangeEvents(false); await this.dotNet.invokeMethodAsync("SetChangeEvents", false); //selection.setAllSelected(false); await this.dotNet.invokeMethodAsync("SetAllSelected", false); //selection.setIndexSelected(index, true, true); await this.dotNet.invokeMethodAsync("SetIndexSelected", index, true, true); if (isModal || (this.props.enterModalOnTouch && this._isTouch)) { await this.dotNet.invokeMethodAsync("SetModal", true); if (this._isTouch) { this._setIsTouch(false); } } await this.dotNet.invokeMethodAsync("SetChangeEvents", true); //selection.setChangeEvents(true); } } private _onClick = async (ev: MouseEvent): Promise<void> => { //const { enableTouchInvocationTarget = false } = this.props; this._updateModifiers(ev); let target = ev.target as HTMLElement; const itemRoot = await this._findItemRootAsync(target); const isSelectionDisabled = this._isSelectionDisabled(target); while (target !== this.root) { if (this._hasAttribute(target, SELECTALL_TOGGLE_ALL_ATTRIBUTE_NAME)) { if (!isSelectionDisabled) { await this._onToggleAllClickAsync(ev); } break; } else if (itemRoot) { const index = this._getItemIndex(itemRoot); if (this._hasAttribute(target, SELECTION_TOGGLE_ATTRIBUTE_NAME)) { if (!isSelectionDisabled) { if (this._isShiftPressed) { await this._onItemSurfaceClickAsync(ev, index); } else { await this._onToggleClickAsync(ev, index); } } break; } else if ( (this._isTouch && this.props.enableTouchInvocationTarget && this._hasAttribute(target, SELECTION_INVOKE_TOUCH_ATTRIBUTE_NAME)) || this._hasAttribute(target, SELECTION_INVOKE_ATTRIBUTE_NAME) ) { // Items should be invokable even if selection is disabled. await this._onInvokeClickAsync(ev, index); break; } else if (target === itemRoot) { if (!isSelectionDisabled) { await this._onItemSurfaceClickAsync(ev, index); } else { // if selection is disabled, i.e. SelectionMode is none, then do a plain InvokeItem await this.dotNet.invokeMethodAsync("InvokeItem", index); } break; } else if (target.tagName === 'A' || target.tagName === 'BUTTON' || target.tagName === 'INPUT') { return; } } target = FluentUIBaseComponent.getParent(target) as HTMLElement; } }; private _setIsTouch(isTouch: boolean): void { if (this._isTouchTimeoutId) { this._async.clearTimeout(this._isTouchTimeoutId); this._isTouchTimeoutId = undefined; } this._isTouch = true; if (isTouch) { this._async.setTimeout(() => { this._isTouch = false; }, 300); } } private _hasAttribute(element: HTMLElement, attributeName: string): boolean { let isToggle = false; while (!isToggle && element !== this.root) { isToggle = element.getAttribute(attributeName) === 'true'; element = FluentUIBaseComponent.getParent(element) as HTMLElement; } return isToggle; } private _handleNextFocus(handleFocus: boolean): void { if (this._shouldHandleFocusTimeoutId) { this._async.clearTimeout(this._shouldHandleFocusTimeoutId); this._shouldHandleFocusTimeoutId = undefined; } this._shouldHandleFocus = handleFocus; if (handleFocus) { this._async.setTimeout(() => { this._shouldHandleFocus = false; }, 100); } } private async _findItemRootAsync(target: HTMLElement): Promise<HTMLElement> | undefined { //const { selection } = this.props; while (target !== this.root) { const indexValue = target.getAttribute(SELECTION_INDEX_ATTRIBUTE_NAME); const index = Number(indexValue); if (indexValue !== null && index >= 0) { let count = await this.dotNet.invokeMethodAsync<number>("GetItemsLength"); if (index < count) { break; } } target = FluentUIBaseComponent.getParent(target) as HTMLElement; } if (target === this.root) { return undefined; } return target; } private _isSelectionDisabled(target: HTMLElement): boolean { if (this.props.selectionMode === SelectionMode.none) { return true; } while (target !== this.root) { if (this._hasAttribute(target, SELECTION_DISABLED_ATTRIBUTE_NAME)) { return true; } target = FluentUIBaseComponent.getParent(target) as HTMLElement; } return false; } private _shouldAutoSelect(element: HTMLElement): boolean { return this._hasAttribute(element, SELECTION_SELECT_ATTRIBUTE_NAME); } private _getItemIndex(itemRoot: HTMLElement): number { return Number(itemRoot.getAttribute(SELECTION_INDEX_ATTRIBUTE_NAME)); } private async _onToggleAllClickAsync(ev: MouseEvent): Promise<void> { //const { selection } = this.props; const selectionMode = this.props.selectionMode; if (selectionMode === SelectionMode.multiple) { //selection.toggleAllSelected(); await this.dotNet.invokeMethodAsync("ToggleAllSelected"); ev.stopPropagation(); ev.preventDefault(); } } private async _onToggleClickAsync(ev: MouseEvent | KeyboardEvent, index: number): Promise<void> { //const { selection } = this.props; const selectionMode = this.props.selectionMode; //selection.setChangeEvents(false); await this.dotNet.invokeMethodAsync("SetChangeEvents", false); if (this.props.enterModalOnTouch && this._isTouch) { // && !selection.isIndexSelected(index) && selection.setModal) { let isSelected = await this.dotNet.invokeMethodAsync<boolean>("IsIndexSelected", index); if (!isSelected) { await this.dotNet.invokeMethodAsync("SetModal", true); this._setIsTouch(false); } } if (selectionMode === SelectionMode.multiple) { //selection.toggleIndexSelected(index); await this.dotNet.invokeMethodAsync("ToggleIndexSelected", index); } else if (selectionMode === SelectionMode.single) { //const isSelected = selection.isIndexSelected(index); let isSelected = await this.dotNet.invokeMethodAsync<boolean>("IsIndexSelected", index); const isModal = this.props.isModal; //selection.isModal && selection.isModal(); //selection.setAllSelected(false); await this.dotNet.invokeMethodAsync("SetAllSelected", false); //selection.setIndexSelected(index, !isSelected, true); await this.dotNet.invokeMethodAsync("SetIndexSelected", index, !isSelected, true); if (isModal) { // Since the above call to setAllSelected(false) clears modal state, // restore it. This occurs because the SelectionMode of the Selection // may differ from the SelectionZone. //selection.setModal(true); await this.dotNet.invokeMethodAsync("SetModal", true); } } else { //selection.setChangeEvents(true); await this.dotNet.invokeMethodAsync("SetChangeEvents", true); return; } //selection.setChangeEvents(true); await this.dotNet.invokeMethodAsync("SetChangeEvents", true); ev.stopPropagation(); // NOTE: ev.preventDefault is not called for toggle clicks, because this will kill the browser behavior // for checkboxes if you use a checkbox for the toggle. } private async _onItemSurfaceClickAsync(ev: Event, index: number): Promise<void> { const isToggleModifierPressed = this._isCtrlPressed || this._isMetaPressed; const selectionMode = this.props.selectionMode; if (selectionMode === SelectionMode.multiple) { if (this._isShiftPressed && !this._isTabPressed) { //selection.selectToIndex(index, !isToggleModifierPressed); await this.dotNet.invokeMethodAsync("SelectToIndex", index, !isToggleModifierPressed); } else if (isToggleModifierPressed) { //selection.toggleIndexSelected(index); await this.dotNet.invokeMethodAsync("ToggleIndexSelected", index); } else { await this._clearAndSelectIndexAsync(index); } } else if (selectionMode === SelectionMode.single) { await this._clearAndSelectIndexAsync(index); } } private async _onInvokeClickAsync(ev: MouseEvent | KeyboardEvent, index: number): Promise<void> { //const { selection, onItemInvoked } = this.props; if (this.props.onItemInvokeSet) { await this.dotNet.invokeMethodAsync("InvokeItem", index); //onItemInvoked(selection.getItems()[index], index, ev.nativeEvent); ev.preventDefault(); ev.stopPropagation(); } } }
the_stack
import _ from 'lodash'; import { TileMatrix } from '../matrix/tileMatrix'; import { TileMatrixSet } from '../matrixset/tileMatrixSet'; export class TileDaoUtils { /** * Adjust the tile matrix lengths if needed. Check if the tile matrix width * and height need to expand to account for pixel * number of pixels fitting * into the tile matrix lengths * @param tileMatrixSet tile matrix set * @param tileMatrices tile matrices */ public static adjustTileMatrixLengths(tileMatrixSet: TileMatrixSet, tileMatrices: TileMatrix[]): void { const tileMatrixWidth = tileMatrixSet.max_x - tileMatrixSet.min_x; const tileMatrixHeight = tileMatrixSet.max_y - tileMatrixSet.min_y; tileMatrices.forEach(tileMatrix => { const tempMatrixWidth = Math.floor(tileMatrixWidth / (tileMatrix.pixel_x_size * tileMatrix.tile_width)); const tempMatrixHeight = Math.floor(tileMatrixHeight / (tileMatrix.pixel_y_size * tileMatrix.tile_height)); if (tempMatrixWidth > tileMatrix.matrix_width) { tileMatrix.matrix_width = tempMatrixWidth; } if (tempMatrixHeight > tileMatrix.matrix_height) { tileMatrix.matrix_height = tempMatrixHeight; } }); } /** * Get the zoom level for the provided width and height in the default units * @param widths sorted widths * @param heights sorted heights * @param tileMatrices tile matrices * @param length in default units * @return tile matrix zoom level */ public static getZoomLevelForLength( widths: number[], heights: number[], tileMatrices: TileMatrix[], length: number, ): number { return TileDaoUtils._getZoomLevelForLength(widths, heights, tileMatrices, length, true); } /** * Get the zoom level for the provided width and height in the default units * @param widths sorted widths * @param heights sorted heights * @param tileMatrices tile matrices * @param width in default units * @param height in default units * @return tile matrix zoom level * @since 1.2.1 */ public static getZoomLevelForWidthAndHeight( widths: number[], heights: number[], tileMatrices: TileMatrix[], width: number, height: number, ): number { return TileDaoUtils._getZoomLevelForWidthAndHeight(widths, heights, tileMatrices, width, height, true); } /** * Get the closest zoom level for the provided width and height in the * default units * @param widths sorted widths * @param heights sorted heights * @param tileMatrices tile matrices * @param length in default units * @return tile matrix zoom level * @since 1.2.1 */ public static getClosestZoomLevelForLength( widths: number[], heights: number[], tileMatrices: TileMatrix[], length: number, ): number { return TileDaoUtils._getZoomLevelForLength(widths, heights, tileMatrices, length, false); } /** * Get the closest zoom level for the provided width and height in the * default units * @param widths sorted widths * @param heights sorted heights * @param tileMatrices tile matrices * @param width in default units * @param height in default units * @return tile matrix zoom level * @since 1.2.1 */ public static getClosestZoomLevelForWidthAndHeight( widths: number[], heights: number[], tileMatrices: TileMatrix[], width: number, height: number, ): number { return TileDaoUtils._getZoomLevelForWidthAndHeight(widths, heights, tileMatrices, width, height, false); } /** * Get the zoom level for the provided width and height in the default units * @param widths sorted widths * @param heights sorted heights * @param tileMatrices tile matrices * @param length in default units * @param lengthChecks perform length checks for values too far away from the zoom level * @return tile matrix zoom level */ private static _getZoomLevelForLength( widths: number[], heights: number[], tileMatrices: TileMatrix[], length: number, lengthChecks: boolean, ): number { return TileDaoUtils._getZoomLevelForWidthAndHeight(widths, heights, tileMatrices, length, length, lengthChecks); } /** * Get the zoom level for the provided width and height in the default units * @param widths sorted widths * @param heights sorted heights * @param tileMatrices tile matrices * @param width width in default units * @param height height in default units * @param lengthChecks perform length checks for values too far away from the zoom level * @return tile matrix zoom level * @since 1.2.1 */ private static _getZoomLevelForWidthAndHeight( widths: number[], heights: number[], tileMatrices: TileMatrix[], width: number, height: number, lengthChecks: boolean, ): number { let zoomLevel = null; let widthIndex = _.sortedIndexOf(widths, width); if (widthIndex === -1) { widthIndex = _.sortedIndex(widths, width); } if (widthIndex < 0) { widthIndex = (widthIndex + 1) * -1; } let heightIndex = _.sortedIndexOf(heights, height); if (heightIndex === -1) { heightIndex = _.sortedIndex(heights, height); } if (heightIndex < 0) { heightIndex = (heightIndex + 1) * -1; } if (widthIndex == 0) { if (lengthChecks && width < TileDaoUtils.getMinLength(widths)) { widthIndex = -1; } } else if (widthIndex == widths.length) { if (lengthChecks && width >= TileDaoUtils.getMaxLength(widths)) { widthIndex = -1; } else { --widthIndex; } } else if (TileDaoUtils.closerToZoomIn(widths, width, widthIndex)) { --widthIndex; } if (heightIndex == 0) { if (lengthChecks && height < TileDaoUtils.getMinLength(heights)) { heightIndex = -1; } } else if (heightIndex == heights.length) { if (lengthChecks && height >= TileDaoUtils.getMaxLength(heights)) { heightIndex = -1; } else { --heightIndex; } } else if (TileDaoUtils.closerToZoomIn(heights, height, heightIndex)) { --heightIndex; } if (widthIndex >= 0 || heightIndex >= 0) { let index; if (widthIndex < 0) { index = heightIndex; } else if (heightIndex < 0) { index = widthIndex; } else { index = Math.min(widthIndex, heightIndex); } zoomLevel = TileDaoUtils.getTileMatrixAtLengthIndex(tileMatrices, index).zoom_level; } return zoomLevel; } /** * Determine if the length at the index is closer by a factor of two to the * next zoomed in level / lower index * @param lengths sorted lengths * @param length current length * @param lengthIndex length index * @return true if closer to zoomed in length */ private static closerToZoomIn(lengths: number[], length: number, lengthIndex: number): boolean { // Zoom level distance to the zoomed in length const zoomInDistance = Math.log(length / lengths[lengthIndex - 1]) / Math.log(2); // Zoom level distance to the zoomed out length const zoomOutDistance = Math.log(length / lengths[lengthIndex]) / Math.log(0.5); return zoomInDistance < zoomOutDistance; } /** * Get the tile matrix represented by the current length index * @param tileMatrices tile matrices * @param index index location in sorted lengths * @return tile matrix */ static getTileMatrixAtLengthIndex(tileMatrices: TileMatrix[], index: number): TileMatrix { return tileMatrices[tileMatrices.length - index - 1]; } /** * Get the approximate zoom level for the provided length in the default * units. Tiles may or may not exist for the returned zoom level. The * approximate zoom level is determined using a factor of 2 from the zoom * levels with tiles. * * @param widths sorted widths * @param heights sorted heights * @param tileMatrices tile matrices * @param length length in default units * @return actual or approximate tile matrix zoom level * @since 2.0.2 */ static getApproximateZoomLevelForLength( widths: number[], heights: number[], tileMatrices: TileMatrix[], length: number, ): number { return TileDaoUtils.getApproximateZoomLevelForWidthAndHeight(widths, heights, tileMatrices, length, length); } /** * Get the approximate zoom level for the provided width and height in the * default units. Tiles may or may not exist for the returned zoom level. * The approximate zoom level is determined using a factor of 2 from the * zoom levels with tiles. * * @param widths sorted widths * @param heights sorted heights * @param tileMatrices tile matrices * @param width width in default units * @param height height in default units * @return actual or approximate tile matrix zoom level * @since 2.0.2 */ static getApproximateZoomLevelForWidthAndHeight( widths: number[], heights: number[], tileMatrices: TileMatrix[], width: number, height: number, ): number { const widthZoomLevel = TileDaoUtils.getApproximateZoomLevel(widths, tileMatrices, width); const heightZoomLevel = TileDaoUtils.getApproximateZoomLevel(heights, tileMatrices, height); let expectedZoomLevel; if (widthZoomLevel == null) { expectedZoomLevel = heightZoomLevel; } else if (heightZoomLevel == null) { expectedZoomLevel = widthZoomLevel; } else { expectedZoomLevel = Math.max(widthZoomLevel, heightZoomLevel); } return expectedZoomLevel; } /** * Get the approximate zoom level for length using the factor of 2 rule * between zoom levels * @param lengths sorted lengths * @param tileMatrices tile matrices * @param length length in default units * @return approximate zoom level */ static getApproximateZoomLevel(lengths: number[], tileMatrices: TileMatrix[], length: number): number { let lengthZoomLevel = null; const minLength = lengths[0]; const maxLength = lengths[lengths.length - 1]; // Length is zoomed in further than available tiles if (length < minLength) { const levelsIn = Math.log(length / minLength) / Math.log(0.5); const zoomAbove = Math.floor(levelsIn); const zoomBelow = Math.ceil(levelsIn); const lengthAbove = minLength * Math.pow(0.5, zoomAbove); const lengthBelow = minLength * Math.pow(0.5, zoomBelow); lengthZoomLevel = tileMatrices[tileMatrices.length - 1].zoom_level; if (lengthAbove - length <= length - lengthBelow) { lengthZoomLevel += zoomAbove; } else { lengthZoomLevel += zoomBelow; } } // Length is zoomed out further than available tiles else if (length > maxLength) { const levelsOut = Math.log(length / maxLength) / Math.log(2); const zoomAbove = Math.ceil(levelsOut); const zoomBelow = Math.floor(levelsOut); const lengthAbove = maxLength * Math.pow(2, zoomAbove); const lengthBelow = maxLength * Math.pow(2, zoomBelow); lengthZoomLevel = tileMatrices[0].zoom_level; if (length - lengthBelow <= lengthAbove - length) { lengthZoomLevel -= zoomBelow; } else { lengthZoomLevel -= zoomAbove; } } // Length is between the available tiles else { let lengthIndex = _.sortedIndexOf(lengths, length); if (lengthIndex < 0) { lengthIndex = (lengthIndex + 1) * -1; } const zoomDistance = Math.log(length / lengths[lengthIndex]) / Math.log(0.5); let zoomLevelAbove = TileDaoUtils.getTileMatrixAtLengthIndex(tileMatrices, lengthIndex).zoom_level; zoomLevelAbove += Math.round(zoomDistance); lengthZoomLevel = zoomLevelAbove; } return lengthZoomLevel; } /** * Get the max distance length that matches the tile widths and heights * @param widths sorted tile matrix widths * @param heights sorted tile matrix heights * @return max length * @since 1.2.0 */ static getMaxLengthForTileWidthsAndHeights(widths: number[], heights: number[]): number { const maxWidth = TileDaoUtils.getMaxLength(widths); const maxHeight = TileDaoUtils.getMaxLength(heights); return Math.min(maxWidth, maxHeight); } /** * Get the min distance length that matches the tile widths and heights * @param widths sorted tile matrix widths * @param heights sorted tile matrix heights * @return min length * @since 1.2.0 */ static getMinLengthForTileWidthsAndHeights(widths: number[], heights: number[]): number { const maxWidth = TileDaoUtils.getMinLength(widths); const maxHeight = TileDaoUtils.getMinLength(heights); return Math.max(maxWidth, maxHeight); } /** * Get the max length distance value from the sorted array of lengths * @param lengths sorted tile matrix lengths * @return max length */ static getMaxLength(lengths: number[]): number { return lengths[lengths.length - 1] / 0.51; } /** * Get the min length distance value from the sorted array of lengths * @param lengths sorted tile matrix lengths * @return min length */ static getMinLength(lengths: number[]): number { return lengths[0] * 0.51; } }
the_stack
import * as vscode from "vscode"; import { WebviewWizard, WizardDefinition, SEVERITY, UPDATE_TITLE, WizardPageFieldDefinition, WizardPageSectionDefinition, BUTTONS, PerformFinishResponse, IWizardPage, ValidatorResponseItem, FieldDefinitionState } from "@redhat-developer/vscode-wizard"; import { ClientAccessor, Cluster, SaslMechanism, SaslOption, SslOption } from "../client"; import { ClusterSettings } from "../settings"; import { validateAuthentificationUserName, validateBroker, validateClusterName, validateFile } from "./validators"; import { KafkaExplorer } from "../explorer"; import { ClusterProvider, defaultClusterProviderId, getClusterProviders } from "../kafka-extensions/registry"; import { showErrorMessage } from "./multiStepInput"; import { SaveClusterCommandHandler } from "../commands"; export function openClusterWizard(clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer, context: vscode.ExtensionContext) { const providers = getClusterProviders(); if (providers.length === 1) { return openClusterForm(undefined, clusterSettings, clientAccessor, explorer, context); } const wiz: WebviewWizard = createClusterWizard(providers, clusterSettings, clientAccessor, explorer, context); wiz.open(); } export function openClusterForm(cluster: Cluster | undefined, clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer, context: vscode.ExtensionContext) { const wiz: WebviewWizard = createEditClusterForm(cluster, clusterSettings, clientAccessor, explorer, context); wiz.open(); } interface AuthMechanism { key: string, label: string; } const authMechanisms: Array<AuthMechanism> = [ { key: "none", label: "None" }, { key: "plain", label: "SASL/PLAIN" }, { key: "scram-sha-256", label: "SASL/SCRAM-256" }, { key: "scram-sha-512", label: "SASL/SCRAM-512" } ]; interface ValidationContext { clusterSettings: ClusterSettings; wizard: WebviewWizard | null; } // --- Wizard page fields // Fields for Page 1: const CLUSTER_PROVIDER_ID_FIELD = "clusterProviderId"; // Fields for Page 2: const CLUSTER_NAME_FIELD = "name"; const CLUSTER_BOOTSTRAP_FIELD = "bootstrap"; const DEFAULT_BROKER = 'localhost:9092'; // SASL fields const CLUSTER_SASL_MECHANISM_FIELD = "saslOptions.mechanism"; const CLUSTER_SASL_USERNAME_FIELD = "saslOptions.username"; const CLUSTER_SASL_PASSWORD_FIELD = "saslOptions.password"; // SSL fields const CLUSTER_SSL_FIELD = "ssl"; const CLUSTER_SSL_CA_FIELD = "ssl.ca"; const CLUSTER_SSL_KEY_FIELD = "ssl.key"; const CLUSTER_SSL_CERT_FIELD = "ssl.cert"; // --- Wizard page ID const CLUSTER_PROVIDER_PAGE = 'cluster-provider-page'; const CLUSTER_FORM_PAGE = 'cluster-form-page'; function createClusterWizard(providers: ClusterProvider[], clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer, context: vscode.ExtensionContext): WebviewWizard { const valiationContext = { clusterSettings: clusterSettings, wizard: null } as ValidationContext; const clusterWizardDef: WizardDefinition = { title: "Add New Cluster(s)", hideWizardHeader: true, pages: [ { id: CLUSTER_PROVIDER_PAGE, hideWizardPageHeader: true, fields: [ { id: CLUSTER_PROVIDER_ID_FIELD, label: "Cluster provider:", initialValue: `${defaultClusterProviderId}`, type: "select", optionProvider: { getItems() { return [...providers]; }, getValueItem(provider: string | ClusterProvider) { return (<ClusterProvider>provider).id; }, getLabelItem(provider: string | ClusterProvider) { return (<ClusterProvider>provider).name; } } } ] }, { id: CLUSTER_FORM_PAGE, hideWizardPageHeader: true, fields: createFields(), validator: createValidator(valiationContext), } ], workflowManager: { getNextPage(page: IWizardPage, data: any): IWizardPage | null { if (page.getId() === CLUSTER_PROVIDER_PAGE) { const selectedClusterProvider = getSelectedClusterProvider(data, providers); if (selectedClusterProvider?.id !== defaultClusterProviderId) { return null; } return page.getNextPage(); } return null; }, canFinish(wizard: WebviewWizard, data: any) { const page = wizard.getCurrentPage(); if (page?.getId() === CLUSTER_PROVIDER_PAGE) { const selectedClusterProvider = getSelectedClusterProvider(data, providers); return (selectedClusterProvider !== undefined && selectedClusterProvider.id !== defaultClusterProviderId); } return page?.isPageComplete() || false; }, async performFinish(wizard: WebviewWizard, data: any) { const page = wizard.getCurrentPage(); if (page?.getId() === CLUSTER_FORM_PAGE) { const cluster = createCluster(data); await saveCluster(data, cluster); // Open the cluster in form page openClusterForm(cluster, clusterSettings, clientAccessor, explorer, context); } else { const provider = getSelectedClusterProvider(data, providers); if (provider) { // Collect clusters... let clusters: Cluster[] | undefined; try { clusters = await provider.collectClusters(clusterSettings); if (!clusters || clusters.length === 0) { return null; } } catch (error) { showErrorMessage("Error while collecting cluster(s)", error); return null; } // Save clusters. await saveClusters(clusters); } } return null; } } }; return new WebviewWizard(`new-cluster`, "cluster", context, clusterWizardDef, new Map<string, string>()); } function getSelectedClusterProvider(data: any, providers: ClusterProvider[]): ClusterProvider | undefined { return providers.find(provider => provider.id === data[CLUSTER_PROVIDER_ID_FIELD]); } function createEditClusterForm(cluster: Cluster | undefined, clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer, context: vscode.ExtensionContext): WebviewWizard { const valiationContext = { clusterSettings: clusterSettings, wizard: null } as ValidationContext; const clusterWizardDef: WizardDefinition = { title: `${cluster?.name || 'New Cluster'}`, showDirtyState: true, hideWizardHeader: true, pages: [ { id: `cluster-form-page'}`, hideWizardPageHeader: true, fields: createFields(cluster), validator: createValidator(valiationContext) } ], buttons: [{ id: BUTTONS.FINISH, label: "Save" }], workflowManager: { async performFinish(wizard: WebviewWizard, data: any) { if (!cluster) { cluster = createCluster(data); } // Save cluster await saveCluster(data, cluster); // Update tab title let newTitle: string = cluster.name; return new Promise<PerformFinishResponse | null>((res, rej) => { res({ close: false, success: true, returnObject: null, templates: [ { id: UPDATE_TITLE, content: newTitle }, ] }); }); } } }; const wizard = new WebviewWizard(`${cluster?.id}`, "cluster", context, clusterWizardDef, new Map<string, string>()); valiationContext.wizard = wizard; return wizard; } function createFields(cluster?: Cluster): (WizardPageFieldDefinition | WizardPageSectionDefinition)[] { const tlsConnectionOptions: SslOption | undefined = <SslOption>cluster?.ssl; return [ { id: CLUSTER_NAME_FIELD, label: "Name:", initialValue: `${cluster?.name || ''}`, type: "textbox", placeholder: 'Friendly name' }, { id: CLUSTER_BOOTSTRAP_FIELD, label: "Bootstrap server:", initialValue: `${cluster ? (cluster?.bootstrap || '') : DEFAULT_BROKER}`, type: "textbox", placeholder: 'Broker(s) (localhost:9092,localhost:9093...)' }, { id: 'sasl-section', label: 'Authentication', childFields: [ { id: CLUSTER_SASL_MECHANISM_FIELD, label: "Mechanism:", initialValue: `${cluster?.saslOption?.mechanism || "none"}`, type: "select", optionProvider: { getItems() { return authMechanisms; }, getValueItem(mechanism: AuthMechanism) { return mechanism.key; }, getLabelItem(mechanism: AuthMechanism) { return mechanism.label; } } }, { id: CLUSTER_SASL_USERNAME_FIELD, label: "Username:", initialValue: `${cluster?.saslOption?.username || ''}`, type: "textbox" }, { id: CLUSTER_SASL_PASSWORD_FIELD, label: "Password:", initialValue: `${cluster?.saslOption?.password || ''}`, type: "password" } ] }, { id: 'ssl-section', label: 'SSL', childFields: [ { id: CLUSTER_SSL_FIELD, label: "Enable SSL", initialValue: !(cluster?.ssl === undefined || cluster?.ssl === false) ? 'true' : undefined, type: "checkbox" }, { id: CLUSTER_SSL_CA_FIELD, label: "Certificate Authority:", initialValue: tlsConnectionOptions?.ca, type: "file-picker", placeholder: "Select file in PEM format.", dialogOptions: { canSelectMany: false, filters: { 'All': ['*'], 'PEM': ['pem', 'crt', 'cer', 'key'] } } }, { id: CLUSTER_SSL_KEY_FIELD, label: "Client key:", initialValue: tlsConnectionOptions?.key, type: "file-picker", placeholder: "Select file in PEM format.", dialogOptions: { canSelectMany: false, filters: { 'All': ['*'], 'PEM': ['pem', 'crt', 'cer', 'key'] } } }, { id: CLUSTER_SSL_CERT_FIELD, label: "Client certificate:", initialValue: tlsConnectionOptions?.cert, type: "file-picker", placeholder: "Select file in PEM format.", dialogOptions: { canSelectMany: false, filters: { 'All': ['*'], 'PEM': ['pem', 'crt', 'cer', 'key'] } } } ] } ]; } function createValidator(validationContext: ValidationContext) { return (parameters?: any) => { const clusterName = validationContext.wizard?.title; const diagnostics: Array<ValidatorResponseItem> = []; const fieldRefresh = new Map<string, FieldDefinitionState>(); // 1. Validate cluster name const clusterSettings = validationContext.clusterSettings; const existingClusterNames = clusterSettings.getAll() .filter(c => clusterName === undefined || c.name !== clusterName) .map(c => c.name); const clustername = parameters[CLUSTER_NAME_FIELD]; let result = validateClusterName(clustername, existingClusterNames); if (result) { diagnostics.push( { template: { id: CLUSTER_NAME_FIELD, content: result }, severity: SEVERITY.ERROR } ); } // 2. Validate bootstrap broker const bootstrap = parameters[CLUSTER_BOOTSTRAP_FIELD]; result = validateBroker(bootstrap); if (result) { diagnostics.push( { template: { id: CLUSTER_BOOTSTRAP_FIELD, content: result }, severity: SEVERITY.ERROR } ); } // 3. Validate username if SASL is enabled function isSASLEnabled(data: any) { return data[CLUSTER_SASL_MECHANISM_FIELD] && data[CLUSTER_SASL_MECHANISM_FIELD] !== 'none'; } function isSSLEnabled(data: any) { return (data[CLUSTER_SSL_FIELD] === true || data[CLUSTER_SSL_FIELD] === 'true'); } const saslEnabled = isSASLEnabled(parameters); const sslEnabled = isSSLEnabled(parameters); if (saslEnabled) { const username = parameters[CLUSTER_SASL_USERNAME_FIELD]; result = validateAuthentificationUserName(username); if (result) { diagnostics.push( { template: { id: CLUSTER_SASL_USERNAME_FIELD, content: result }, severity: SEVERITY.ERROR } ); } // check if SSL checkbox is checked if (!sslEnabled) { diagnostics.push( { template: { id: CLUSTER_SSL_FIELD, content: 'SSL should probably be enabled since Authentication is enabled.' }, severity: SEVERITY.WARN } ); } } // 4. Validate certificate files validateCertificateFile(parameters, CLUSTER_SSL_CA_FIELD, diagnostics); validateCertificateFile(parameters, CLUSTER_SSL_KEY_FIELD, diagnostics); validateCertificateFile(parameters, CLUSTER_SSL_CERT_FIELD, diagnostics); // 5. Manage enabled state for SASL and SSL fields fieldRefresh.set(CLUSTER_SASL_USERNAME_FIELD, { enabled: saslEnabled }); fieldRefresh.set(CLUSTER_SASL_PASSWORD_FIELD, { enabled: saslEnabled }); fieldRefresh.set(CLUSTER_SSL_CA_FIELD, { enabled: sslEnabled }); fieldRefresh.set(CLUSTER_SSL_KEY_FIELD, { enabled: sslEnabled }); fieldRefresh.set(CLUSTER_SSL_CERT_FIELD, { enabled: sslEnabled }); return { items: diagnostics, fieldRefresh }; }; } async function saveCluster(data: any, cluster: Cluster) { cluster.name = data[CLUSTER_NAME_FIELD]; cluster.bootstrap = data[CLUSTER_BOOTSTRAP_FIELD]; cluster.saslOption = createSaslOption(data); cluster.ssl = createSsl(data); return saveClusters([cluster]); } async function saveClusters(clusters: Cluster[]) { return vscode.commands.executeCommand(SaveClusterCommandHandler.commandId, clusters); } function createSaslOption(data: any): SaslOption | undefined { const mechanism = data[CLUSTER_SASL_MECHANISM_FIELD] as SaslMechanism; if (mechanism) { const username = data[CLUSTER_SASL_USERNAME_FIELD]; const password = data[CLUSTER_SASL_PASSWORD_FIELD]; return { mechanism, username, password } as SaslOption; } } function createSsl(data: any): SslOption | boolean { const ca = data[CLUSTER_SSL_CA_FIELD]; const key = data[CLUSTER_SSL_KEY_FIELD]; const cert = data[CLUSTER_SSL_CERT_FIELD]; if (ca || key || cert) { return { ca, key, cert } as SslOption; } return data[CLUSTER_SSL_FIELD] === true || data[CLUSTER_SSL_FIELD] === 'true'; } function createCluster(data: any): Cluster { const name = data[CLUSTER_NAME_FIELD]; const bootstrap = data[CLUSTER_BOOTSTRAP_FIELD]; const sanitizedName = name.replace(/[^a-zA-Z0-9]/g, ""); const suffix = Buffer.from(bootstrap).toString("base64").replace(/=/g, ""); return { id: `${sanitizedName}-${suffix}` } as Cluster; } function validateCertificateFile(parameters: any, fieldId: string, diagnostics: Array<ValidatorResponseItem>) { const fileName = parameters[fieldId]; if (!fileName || fileName === '') { return; } const result = validateFile(fileName); if (result) { diagnostics.push( { template: { id: fieldId, content: result }, severity: SEVERITY.ERROR } ); } }
the_stack
import * as _ from 'lodash'; import * as React from 'react'; import { connect } from 'react-redux'; import { toastr } from 'react-redux-toastr'; import { ActionCreators as UndoActionCreators } from 'redux-undo'; import { Accordion, Divider, Grid, Header, Icon, SemanticICONS, Tab } from 'semantic-ui-react'; import { setNodesAndEdges } from 'src/actions/graph'; import { SetSelectedEdge } from 'src/actions/selectedEdge'; import { setSelectedNode } from 'src/actions/selectedNode'; import { store } from 'src/App'; import LoadingBar from 'src/components/misc/LoadingBar'; import NodeSearch from 'src/components/visualization/controls/NodeSearch'; import EdgeInfoTable from 'src/components/visualization/panels/EdgeInfoTable'; import EdgeTimeChart from 'src/components/visualization/panels/EdgeTimechart'; import NodeInfoTable from 'src/components/visualization/panels/NodeInfoTable'; import VisibleScope from 'src/components/visualization/panels/VisibleScope'; import EventTable from 'src/components/visualization/prespectives/EventTable'; import EventTimeline from 'src/components/visualization/prespectives/EventTimeline'; import ForceGraph from 'src/components/visualization/prespectives/ForceGraph'; import MarkdownExport from 'src/components/visualization/prespectives/MarkdownExport'; import TreeGraph from 'src/components/visualization/prespectives/TreeGraph'; import { Graph } from 'src/models/index.js'; import { State } from 'src/reducers'; import { PULL_IN_LIMIT } from 'src/reducers/visibleGraph'; import Upload from 'src/views/Upload'; import { pullInNeighbors, setVisibleEdges, setVisibleEdgeTypes, setVisibleNodes, setVisibleNodeTypes, } from '../actions/visibleGraph'; import VisibleTypeToggles from '../components/visualization/controls/VisibleTypeToggles'; import GraphRedoUndo from './GraphRedoUndo'; const EXLUDED_BY_DEFAULT = ["Loaded", "File Of"]; interface GraphPageState { ready: boolean; } class GraphPage extends React.Component<any, GraphPageState> { private tab: any; // sematnic-ui uses old refs, easier to type hint as any. constructor(props: any) { super(props); this.state = { ready: false }; } public componentDidUpdate(prevProps: any) { // Check if we pulled in the limit. If so, notify user. if (this.props.visibleNodes.length - prevProps.visibleNodes.length === PULL_IN_LIMIT) { toastr.warning( `Pull in limit (${PULL_IN_LIMIT}) reached`, "Double click the node again to pull in more neighbours." ); } } public loadGraph() { fetch( `${process.env.NODE_ENV === "production" ? "" : "http://localhost:8000"}/api/graph/${ this.props.match.params.id }` ) .then(response => response.json()) .then(graphJson => { const graph: Graph = { directed: graphJson.directed, edges: graphJson.links.map((link: any) => { return { from: link.source, id: link.id, label: link.type, properties: link.properties, to: link.target }; }), graph: graphJson.graph, multigraph: graphJson.multigraph, nodes: graphJson.nodes.map((node: any) => { const newNode = Object.assign(node); // 15 = len("255.255.255.255") ; newNode.label = (node._display || "").substring(0, 15); if (newNode.label.length === 15) { newNode.label += "..."; } newNode.color = node._color; return newNode; }) }; // Set the visible edge types store.dispatch(setVisibleNodeTypes(_.uniq(_.map(graph.nodes, "_node_type")))); // Set the visible edge types, excluding what is off by default. store.dispatch( setVisibleEdgeTypes( _.uniq(_.map(graph.edges, "label")).filter( edgeType => !_.includes(EXLUDED_BY_DEFAULT, edgeType) ) ) ); store.dispatch(setNodesAndEdges(graph.nodes, graph.edges)); const alertNodes = graph.nodes.filter(n => n._node_type === "Alert"); if (alertNodes.length > 0) { store.dispatch(setVisibleNodes([...alertNodes])); alertNodes.map(node => store.dispatch(pullInNeighbors(node.id))); store.dispatch(UndoActionCreators.clearHistory()); // Wipe state here } else { // Set base state here const sample = _.sampleSize(graph.nodes, 10); store.dispatch(setVisibleNodes(sample)); store.dispatch(pullInNeighbors(sample[0].id)); store.dispatch(UndoActionCreators.clearHistory()); } this.setState({ ready: true }); }); } public loadAndResetView() { this.tab.state.activeIndex = 0; this.loadGraph(); toastr.info("Evidence added to graph", `Uploaded artifact merged into graph.`, { timeOut: 10000 }); } public componentWillMount() { this.loadGraph(); } public componentWillUnmount = () => { // Reset the graph on unmount. store.dispatch(setVisibleNodeTypes([])); store.dispatch(setVisibleEdgeTypes([])); store.dispatch(setNodesAndEdges([], [])); store.dispatch(setVisibleNodes([])); store.dispatch(setVisibleEdges([])); store.dispatch(setSelectedNode(undefined)); store.dispatch(SetSelectedEdge(undefined)); store.dispatch(UndoActionCreators.clearHistory()); }; public makeDivider(text: string, icon: SemanticICONS) { return ( <Divider horizontal={true}> <Header as="h4"> <Icon name={icon} /> {text} </Header> </Divider> ); } public render() { if (this.state.ready === false) { return <LoadingBar text="Fetching Graph Data" />; } return ( <Grid columns={2} celled="internally" padded={false}> <Grid.Column width={10}> <Tab ref={ref => (this.tab = ref)} menu={{ color: "black", secondary: true, pointing: true, attached: "top" }} panes={[ { menuItem: "Graph", render: () => ( <ForceGraph visibleEdges={this.props.visibleEdges} visibleNodes={this.props.visibleNodes} /> ) }, { menuItem: "Tree", render: () => ( <TreeGraph visibleEdges={this.props.visibleEdges} visibleNodes={this.props.visibleNodes} /> ) }, { menuItem: "Timeline", render: () => ( <EventTimeline visibleEdges={this.props.visibleEdges} visibleNodes={this.props.visibleNodes} /> ) }, { menuItem: "Table", render: () => ( <EventTable visibleEdges={this.props.visibleEdges} visibleNodes={this.props.visibleNodes} /> ) }, { menuItem: "Markdown", render: () => ( <MarkdownExport visibleEdges={this.props.visibleEdges} visibleNodes={this.props.visibleNodes} /> ) }, { menuItem: "Add Evidence", render: () => ( // Add evidence <Upload postRoute={`/add/${this.props.match.params.id}`} postUploadHandler={this.loadAndResetView.bind(this)} /> ) } ]} /> </Grid.Column> <Grid.Column width={6} stretched={false} style={{ overflowY: "auto", maxHeight: "100vh" }} > <Grid.Row centered={true}> <VisibleScope nodes={this.props.nodes.length} edges={this.props.edges.length} visibleNodes={this.props.visibleNodes.length} visibleEdges={this.props.visibleEdges.length} latestEvent={this.props.latestEvent} earliestEvent={this.props.earliestEvent} /> </Grid.Row> {<br /> /* Empty row to force a newline? */} <Grid.Row> <Accordion defaultActiveIndex={[0, 1, 2, 3, 4, 5, 6]} exclusive={false} panels={[ { key: "node_search", title: { children: this.makeDivider("Node Search", "search") }, content: { children: <NodeSearch nodes={this.props.nodes} /> } }, { key: "graph_controls", title: { children: this.makeDivider("Graph Controls", "configure") }, content: { children: <GraphRedoUndo /> } }, { key: "node_visibility_controls", title: { children: this.makeDivider("Node/Edge Visibility", "eye") }, content: { children: ( <VisibleTypeToggles nodes={this.props.nodes} edges={this.props.edges} visibleEdgeTypes={this.props.visibleEdgeTypes} visibleNodeTypes={this.props.visibleNodeTypes} /> ) } }, { key: "node_info", title: { children: this.makeDivider("Node Info", "info circle") }, content: { children: <NodeInfoTable node={this.props.selectedNode} /> } }, { key: "edge_info", title: { children: this.makeDivider("Edge Info", "info circle") }, content: { children: [ <EdgeInfoTable key="table" edge={this.props.selectedEdge} />, false && ( <EdgeTimeChart key="timechart" edge={this.props.selectedEdge} latestEvent={this.props.latestEvent} earliestEvent={this.props.earliestEvent} /> ) ] } } ]} /> </Grid.Row> </Grid.Column> </Grid> ); } } const mapStateToProps = (state: State) => ({ visibleNodes: state.visibleGraph.present.visibleNodes, visibleEdges: state.visibleGraph.present.visibleEdges, selectedNode: state.selectedNode.node, selectedEdge: state.selectedEdge.edge, nodes: state.graph.nodes, edges: state.graph.edges, visibleNodeTypes: state.visibleGraph.present.visibleNodeTypes, visibleEdgeTypes: state.visibleGraph.present.visibleEdgeTypes, latestEvent: state.visibleGraph.present.latestEvent, earliestEvent: state.visibleGraph.present.earliestEvent }); export default connect<any, any, any>(mapStateToProps)(GraphPage);
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; import { Store, select } from '@ngrx/store'; import { identity, isNil } from 'lodash/fp'; import { combineLatest, Subject } from 'rxjs'; import { filter, pluck, takeUntil } from 'rxjs/operators'; import { LayoutFacadeService, Sidebar } from 'app/entities/layout/layout.facade'; import { NgrxStateAtom } from 'app/ngrx.reducers'; import { routeParams } from 'app/route.selectors'; import { Regex } from 'app/helpers/auth/regex'; import { pending, EntityStatus } from 'app/entities/entities'; import { GetDestination, UpdateDestination, TestDestination , EnableDisableDestination, DeleteDestination } from 'app/entities/destinations/destination.actions'; import { destinationFromRoute, getStatus, updateStatus, destinationEnableStatus, deleteStatus, testConnectionStatus } from 'app/entities/destinations/destination.selectors'; import { Destination, regions } from 'app/entities/destinations/destination.model'; import { Router } from '@angular/router'; import { trigger, state, animate, transition, style, keyframes } from '@angular/animations'; import { KVData } from 'app/entities/node-credentials/node-credential.model'; const fadeEnable = trigger('fadeEnable', [ state('inactive', style({})), state('active', style({})), transition('inactive <=> active', [ animate('0.3s', keyframes([ style({transform: 'translateX(0%)'}), style({transform: 'translateX(100%)'}), style({transform: 'translateX(0%)'}) ])) ]) ]); const fadeDisable = trigger('fadeDisable', [ state('inactive', style({})), state('active', style({})), transition('inactive <=> active', [ animate('0.3s', keyframes([ style({transform: 'translateX(0%)'}), style({transform: 'translateX(-100%)'}), style({transform: 'translateX(0%)'}) ])) ]) ]); type DestinationTabName = 'details'; enum UrlTestState { Inactive, Loading, Success, Failure } export enum WebhookIntegrationTypes { SERVICENOW = 'ServiceNow', SPLUNK = 'Splunk', ELK_KIBANA = 'ELK', CUSTOM = 'Custom' } export enum StorageIntegrationTypes { MINIO = 'Minio', AMAZON_S3 = 'S3' } export enum IntegrationTypes { WEBHOOK = 'Webhook', STORAGE = 'Storage' } @Component({ selector: 'app-data-feed-details', templateUrl: './data-feed-details.component.html', styleUrls: ['./data-feed-details.component.scss'], animations: [fadeEnable, fadeDisable] }) export class DataFeedDetailsComponent implements OnInit, OnDestroy { public tabValue: DestinationTabName = 'details'; public destination: Destination; public updateForm: FormGroup; public saveInProgress = false; public testInProgress = false; public saveSuccessful = false; public hookStatus = UrlTestState.Inactive; private isDestroyed = new Subject<boolean>(); public deleteModalVisible = false; public state = 'inactive'; public regionSelected: string; public regionList = regions; public regionName: string; public serviceIntegrations = { webhook: { WebhookIntegrationTypes }, storage: { StorageIntegrationTypes } }; public integrations = {IntegrationTypes}; constructor( private fb: FormBuilder, private store: Store<NgrxStateAtom>, private layoutFacade: LayoutFacadeService, private router: Router ) { } ngOnInit(): void { this.layoutFacade.showSidebar(Sidebar.Settings); this.store.select(routeParams).pipe( pluck('id'), filter(identity), takeUntil(this.isDestroyed)) .subscribe((id: string) => { this.store.dispatch(new GetDestination({ id })); }); combineLatest([ this.store.select(getStatus), this.store.select(destinationFromRoute) ]).pipe( filter(([status, destination]) => status === EntityStatus.loadingSuccess && !isNil(destination)), takeUntil(this.isDestroyed)) .subscribe(([_, destination]) => { this.destination = destination; this.updateForm.controls.name.setValue(this.destination.name); this.updateForm.controls.url.setValue(this.destination.url); if (this.destination.integration_types === IntegrationTypes.STORAGE) { this.destination.meta_data.forEach((v) => { if (v.key === 'bucket') { this.updateForm.controls.bucket.setValue(v.value); } if (v.key === 'region') { this.regionName = v.value; this.regionSelected = v.value; } }); } }); this.updateForm = this.fb.group({ // Must stay in sync with error checks in data-feed-details.component.html name: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], // Note that URL here may be FQDN -or- IP! url: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], bucket: this.destination?.services === StorageIntegrationTypes.AMAZON_S3 ? ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]] : null }); this.store.pipe( select(updateStatus), takeUntil(this.isDestroyed), filter(status => this.saveInProgress && !pending(status))) .subscribe((res) => { this.saveInProgress = false; this.saveSuccessful = (res === EntityStatus.loadingSuccess); if (this.saveSuccessful) { this.updateForm.markAsPristine(); } }); } selectChangeHandlers(region: string): void { this.regionSelected = region; } metaDataValue(): Array<KVData> { if (this.destination.integration_types === IntegrationTypes.STORAGE ) { if (this.destination.services === StorageIntegrationTypes.AMAZON_S3 ) { return Array<KVData>( { key: 'bucket', value: this.updateForm.controls['bucket'].value.trim() }, { key: 'region', value: this.regionSelected } ); } if (this.destination.services === StorageIntegrationTypes.MINIO ) { return Array<KVData>( { key: 'bucket', value: this.updateForm.controls['bucket'].value.trim() } ); } } } public saveDataFeed(): void { this.saveSuccessful = false; this.saveInProgress = true; const destinationObj = { id: this.destination.id, name: this.updateForm.controls['name'].value.trim(), url: this.updateForm.controls['url'].value.trim(), secret: this.destination.secret, enable: this.destination.enable, integration_types: this.destination.integration_types, meta_data: this.destination.integration_types === IntegrationTypes.STORAGE ? this.metaDataValue() : this.destination.meta_data, services: this.destination.services }; this.store.dispatch(new UpdateDestination({ destination: destinationObj })); this.destination = destinationObj; } public sendTestForDataFeedUrl(): void { this.testInProgress = true; const destinationObj = { ...this.destination, name: this.updateForm.controls['name'].value.trim(), url: this.updateForm.controls['url'].value.trim(), secret: this.destination.secret, enable: this.destination.enable, integration_types: this.destination.integration_types, meta_data: this.destination.integration_types === IntegrationTypes.STORAGE ? this.metaDataValue() : this.destination.meta_data, services: this.destination.services }; this.store.dispatch(new TestDestination({destination: destinationObj})); this.store.pipe( select(testConnectionStatus), takeUntil(this.isDestroyed), filter(status => !pending(status))) .subscribe(res => { if (res === EntityStatus.loadingSuccess || EntityStatus.loadingFailure) { this.testInProgress = false; } }); } public get nameCtrl(): FormControl { return <FormControl>this.updateForm.controls.name; } public get bucketCtrl(): FormControl { return <FormControl>this.updateForm.controls.bucket; } public get urlCtrl(): FormControl { return <FormControl>this.updateForm.controls.url; } public enableDestination(val: boolean) { const destinationEnableObj = { id: this.destination.id, enable: val }; this.store.dispatch(new EnableDisableDestination({enableDisable: destinationEnableObj})); this.store.pipe( select(destinationEnableStatus), takeUntil(this.isDestroyed), filter(status => !pending(status))) .subscribe(res => { if (res === EntityStatus.loadingSuccess) { this.state = this.state === 'active' ? 'inactive' : 'active'; this.destination.enable = val; } }); } public deleteDataFeed() { this.store.dispatch(new DeleteDestination(this.destination)); this.store.pipe( select(deleteStatus), takeUntil(this.isDestroyed), filter(status => !pending(status))) .subscribe(res => { if (res === EntityStatus.loadingSuccess) { this.router.navigate(['/settings/data-feeds']); } }); } public closeDeleteModal(): void { this.deleteModalVisible = false; } public openDeleteModal(): void { this.deleteModalVisible = true; } ngOnDestroy(): void { this.isDestroyed.next(true); this.isDestroyed.complete(); } public cancel(): void { this.router.navigate(['/settings/data-feeds']); } public disableOnsave(service: string) { const isDisable = this.saveInProgress || !this.updateForm.valid || !this.updateForm.dirty || !this.destination?.enable; if (service === StorageIntegrationTypes.AMAZON_S3 ) { return isDisable && this.regionSelected === this.regionName; } else { return isDisable ; } } public showUrl() { return !(this.destination?.integration_types === IntegrationTypes.STORAGE) || this.destination?.services === StorageIntegrationTypes.MINIO; } public enableBtn() { return !this.destination?.enable ? 'is-enable enable-btn' : 'is-disable enable-btn'; } public disableBtn() { return this.destination?.enable ? 'is-enable disable-btn' : 'is-disable disable-btn'; } }
the_stack
import 'es6-promise/auto'; // polyfill Promise on IE import { CommandRegistry } from '@phosphor/commands'; import { Message } from '@phosphor/messaging'; import { BoxPanel, CommandPalette, ContextMenu, DockPanel, Menu, MenuBar, Widget } from '@phosphor/widgets'; import '../style/index.css'; const commands = new CommandRegistry(); function createMenu(): Menu { let sub1 = new Menu({ commands }); sub1.title.label = 'More...'; sub1.title.mnemonic = 0; sub1.addItem({ command: 'example:one' }); sub1.addItem({ command: 'example:two' }); sub1.addItem({ command: 'example:three' }); sub1.addItem({ command: 'example:four' }); let sub2 = new Menu({ commands }); sub2.title.label = 'More...'; sub2.title.mnemonic = 0; sub2.addItem({ command: 'example:one' }); sub2.addItem({ command: 'example:two' }); sub2.addItem({ command: 'example:three' }); sub2.addItem({ command: 'example:four' }); sub2.addItem({ type: 'submenu', submenu: sub1 }); let root = new Menu({ commands }); root.addItem({ command: 'example:copy' }); root.addItem({ command: 'example:cut' }); root.addItem({ command: 'example:paste' }); root.addItem({ type: 'separator' }); root.addItem({ command: 'example:new-tab' }); root.addItem({ command: 'example:close-tab' }); root.addItem({ command: 'example:save-on-exit' }); root.addItem({ type: 'separator' }); root.addItem({ command: 'example:open-task-manager' }); root.addItem({ type: 'separator' }); root.addItem({ type: 'submenu', submenu: sub2 }); root.addItem({ type: 'separator' }); root.addItem({ command: 'example:close' }); return root; } class ContentWidget extends Widget { static createNode(): HTMLElement { let node = document.createElement('div'); let content = document.createElement('div'); let input = document.createElement('input'); input.placeholder = 'Placeholder...'; content.appendChild(input); node.appendChild(content); return node; } constructor(name: string) { super({ node: ContentWidget.createNode() }); this.setFlag(Widget.Flag.DisallowLayout); this.addClass('content'); this.addClass(name.toLowerCase()); this.title.label = name; this.title.closable = true; this.title.caption = `Long description for: ${name}`; } get inputNode(): HTMLInputElement { return this.node.getElementsByTagName('input')[0] as HTMLInputElement; } protected onActivateRequest(msg: Message): void { if (this.isAttached) { this.inputNode.focus(); } } } function main(): void { commands.addCommand('example:cut', { label: 'Cut', mnemonic: 1, iconClass: 'fa fa-cut', execute: () => { console.log('Cut'); } }); commands.addCommand('example:copy', { label: 'Copy File', mnemonic: 0, iconClass: 'fa fa-copy', execute: () => { console.log('Copy'); } }); commands.addCommand('example:paste', { label: 'Paste', mnemonic: 0, iconClass: 'fa fa-paste', execute: () => { console.log('Paste'); } }); commands.addCommand('example:new-tab', { label: 'New Tab', mnemonic: 0, caption: 'Open a new tab', execute: () => { console.log('New Tab'); } }); commands.addCommand('example:close-tab', { label: 'Close Tab', mnemonic: 2, caption: 'Close the current tab', execute: () => { console.log('Close Tab'); } }); commands.addCommand('example:save-on-exit', { label: 'Save on Exit', mnemonic: 0, caption: 'Toggle the save on exit flag', execute: () => { console.log('Save on Exit'); } }); commands.addCommand('example:open-task-manager', { label: 'Task Manager', mnemonic: 5, isEnabled: () => false, execute: () => { } }); commands.addCommand('example:close', { label: 'Close', mnemonic: 0, iconClass: 'fa fa-close', execute: () => { console.log('Close'); } }); commands.addCommand('example:one', { label: 'One', execute: () => { console.log('One'); } }); commands.addCommand('example:two', { label: 'Two', execute: () => { console.log('Two'); } }); commands.addCommand('example:three', { label: 'Three', execute: () => { console.log('Three'); } }); commands.addCommand('example:four', { label: 'Four', execute: () => { console.log('Four'); } }); commands.addCommand('example:black', { label: 'Black', execute: () => { console.log('Black'); } }); commands.addCommand('example:clear-cell', { label: 'Clear Cell', execute: () => { console.log('Clear Cell'); } }); commands.addCommand('example:cut-cells', { label: 'Cut Cell(s)', execute: () => { console.log('Cut Cell(s)'); } }); commands.addCommand('example:run-cell', { label: 'Run Cell', execute: () => { console.log('Run Cell'); } }); commands.addCommand('example:cell-test', { label: 'Cell Test', execute: () => { console.log('Cell Test'); } }); commands.addCommand('notebook:new', { label: 'New Notebook', execute: () => { console.log('New Notebook'); } }); commands.addKeyBinding({ keys: ['Accel X'], selector: 'body', command: 'example:cut' }); commands.addKeyBinding({ keys: ['Accel C'], selector: 'body', command: 'example:copy' }); commands.addKeyBinding({ keys: ['Accel V'], selector: 'body', command: 'example:paste' }); commands.addKeyBinding({ keys: ['Accel J', 'Accel J'], selector: 'body', command: 'example:new-tab' }); commands.addKeyBinding({ keys: ['Accel M'], selector: 'body', command: 'example:open-task-manager' }); let menu1 = createMenu(); menu1.title.label = 'File'; menu1.title.mnemonic = 0; let menu2 = createMenu(); menu2.title.label = 'Edit'; menu2.title.mnemonic = 0; let menu3 = createMenu(); menu3.title.label = 'View'; menu3.title.mnemonic = 0; let bar = new MenuBar(); bar.addMenu(menu1); bar.addMenu(menu2); bar.addMenu(menu3); bar.id = 'menuBar'; let palette = new CommandPalette({ commands }); palette.addItem({ command: 'example:cut', category: 'Edit' }); palette.addItem({ command: 'example:copy', category: 'Edit' }); palette.addItem({ command: 'example:paste', category: 'Edit' }); palette.addItem({ command: 'example:one', category: 'Number' }); palette.addItem({ command: 'example:two', category: 'Number' }); palette.addItem({ command: 'example:three', category: 'Number' }); palette.addItem({ command: 'example:four', category: 'Number' }); palette.addItem({ command: 'example:black', category: 'Number' }); palette.addItem({ command: 'example:new-tab', category: 'File' }); palette.addItem({ command: 'example:close-tab', category: 'File' }); palette.addItem({ command: 'example:save-on-exit', category: 'File' }); palette.addItem({ command: 'example:open-task-manager', category: 'File' }); palette.addItem({ command: 'example:close', category: 'File' }); palette.addItem({ command: 'example:clear-cell', category: 'Notebook Cell Operations' }); palette.addItem({ command: 'example:cut-cells', category: 'Notebook Cell Operations' }); palette.addItem({ command: 'example:run-cell', category: 'Notebook Cell Operations' }); palette.addItem({ command: 'example:cell-test', category: 'Console' }); palette.addItem({ command: 'notebook:new', category: 'Notebook' }); palette.id = 'palette'; let contextMenu = new ContextMenu({ commands }); document.addEventListener('contextmenu', (event: MouseEvent) => { if (contextMenu.open(event)) { event.preventDefault(); } }); contextMenu.addItem({ command: 'example:cut', selector: '.content' }); contextMenu.addItem({ command: 'example:copy', selector: '.content' }); contextMenu.addItem({ command: 'example:paste', selector: '.content' }); contextMenu.addItem({ command: 'example:one', selector: '.p-CommandPalette' }); contextMenu.addItem({ command: 'example:two', selector: '.p-CommandPalette' }); contextMenu.addItem({ command: 'example:three', selector: '.p-CommandPalette' }); contextMenu.addItem({ command: 'example:four', selector: '.p-CommandPalette' }); contextMenu.addItem({ command: 'example:black', selector: '.p-CommandPalette' }); contextMenu.addItem({ command: 'notebook:new', selector: '.p-CommandPalette-input' }); contextMenu.addItem({ command: 'example:save-on-exit', selector: '.p-CommandPalette-input' }); contextMenu.addItem({ command: 'example:open-task-manager', selector: '.p-CommandPalette-input' }); contextMenu.addItem({ type: 'separator', selector: '.p-CommandPalette-input' }); document.addEventListener('keydown', (event: KeyboardEvent) => { commands.processKeydownEvent(event); }); let r1 = new ContentWidget('Red'); let b1 = new ContentWidget('Blue'); let g1 = new ContentWidget('Green'); let y1 = new ContentWidget('Yellow'); let r2 = new ContentWidget('Red'); let b2 = new ContentWidget('Blue'); // let g2 = new ContentWidget('Green'); // let y2 = new ContentWidget('Yellow'); let dock = new DockPanel(); dock.addWidget(r1); dock.addWidget(b1, { mode: 'split-right', ref: r1 }); dock.addWidget(y1, { mode: 'split-bottom', ref: b1 }); dock.addWidget(g1, { mode: 'split-left', ref: y1 }); dock.addWidget(r2, { ref: b1 }); dock.addWidget(b2, { mode: 'split-right', ref: y1 }); dock.id = 'dock'; let savedLayouts: DockPanel.ILayoutConfig[] = []; commands.addCommand('save-dock-layout', { label: 'Save Layout', caption: 'Save the current dock layout', execute: () => { savedLayouts.push(dock.saveLayout()); palette.addItem({ command: 'restore-dock-layout', category: 'Dock Layout', args: { index: savedLayouts.length - 1 } }); } }); commands.addCommand('restore-dock-layout', { label: args => { return `Restore Layout ${args.index as number}`; }, execute: args => { dock.restoreLayout(savedLayouts[args.index as number]); } }); palette.addItem({ command: 'save-dock-layout', category: 'Dock Layout', rank: 0 }); BoxPanel.setStretch(dock, 1); let main = new BoxPanel({ direction: 'left-to-right', spacing: 0 }); main.id = 'main'; main.addWidget(palette); main.addWidget(dock); window.onresize = () => { main.update(); }; Widget.attach(bar, document.body); Widget.attach(main, document.body); } window.onload = main;
the_stack
import { Asset, CanonicalRequest, ContentType, EditorInterface, ScheduledAction, Tag, Team, User, TagVisibility, KeyValueMap, Entry, QueryOptions, Upload, } from './entities' import { CollectionResponse, ContentEntityType, Link, WithOptionalId, SearchQuery } from './utils' type Snapshot<T> = { sys: { space?: Link status?: Link publishedVersion?: number archivedVersion?: number archivedBy?: Link archivedAt?: string deletedVersion?: number deletedBy?: Link deletedAt?: string snapshotType: string snapshotEntityType: string } snapshot: T } export interface SpaceAPI { /** * @deprecated since version 4.0.0 * Please using `cma.contentType.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getCachedContentTypes: () => ContentType[] /** * @deprecated since version 4.0.0 * Consider using `cma.contentType.get` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getContentType: (id: string) => Promise<ContentType> /** * @deprecated since version 4.0.0 * Consider using `cma.contentType.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getContentTypes: <Query extends SearchQuery = SearchQuery>( query?: Query ) => Promise<CollectionResponse<ContentType>> /** * @deprecated since version 4.0.0 * Consider using `cma.contentType.create` or `cma.contentType.createWithId` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ createContentType: (data: WithOptionalId<ContentType>) => Promise<ContentType> /** * @deprecated since version 4.0.0 * Consider using `cma.contentType.update` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ updateContentType: (data: ContentType) => Promise<ContentType> /** * @deprecated since version 4.0.0 * Consider using `cma.contentType.delete` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ deleteContentType: (contentTypeId: string) => Promise<void> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.get` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getEntry: <Fields extends KeyValueMap = KeyValueMap>(id: string) => Promise<Entry<Fields>> /** * @deprecated since version 4.0.0 * Consider using `cma.snapshot.getForEntry` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getEntrySnapshots: <Fields extends KeyValueMap = KeyValueMap>( id: string ) => Promise<CollectionResponse<Snapshot<Entry<Fields>>>> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getEntries: <Fields, Query extends SearchQuery = SearchQuery>( query?: Query ) => Promise<CollectionResponse<Entry<Fields>>> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.create` or `cma.entry.createWithId` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ createEntry: <Fields>( contentTypeId: string, data: WithOptionalId<Entry<Fields>> ) => Promise<Entry<Fields>> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.update` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ updateEntry: <Fields extends KeyValueMap = KeyValueMap>( data: Entry<Fields> ) => Promise<Entry<Fields>> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.publish` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ publishEntry: <Fields extends KeyValueMap = KeyValueMap>( data: Entry<Fields> ) => Promise<Entry<Fields>> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.unpublish` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ unpublishEntry: <Fields extends KeyValueMap = KeyValueMap>( data: Entry<Fields> ) => Promise<Entry<Fields>> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.archive` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ archiveEntry: <Fields extends KeyValueMap = KeyValueMap>( data: Entry<Fields> ) => Promise<Entry<Fields>> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.unarchive` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ unarchiveEntry: <Fields extends KeyValueMap = KeyValueMap>( data: Entry<Fields> ) => Promise<Entry<Fields>> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.delete` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ deleteEntry: <Fields extends KeyValueMap = KeyValueMap>(data: Entry<Fields>) => Promise<void> /** * @deprecated since version 4.0.0 * Consider using `cma.entry.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getPublishedEntries: <Fields, Query extends SearchQuery = SearchQuery>( query?: Query ) => Promise<CollectionResponse<Entry<Fields>>> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.get` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getAsset: (id: string) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getAssets: <Query extends SearchQuery = SearchQuery>( query?: Query ) => Promise<CollectionResponse<Asset>> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.create` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ createAsset: (data: WithOptionalId<Asset>) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.update` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ updateAsset: (data: Asset) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.delete` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ deleteAsset: (data: Asset) => Promise<void> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.publish` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ publishAsset: (data: Asset) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.unpublish` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ unpublishAsset: (data: Asset) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.archive` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ archiveAsset: (data: Asset) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.processForLocale` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ processAsset: (data: Asset, locale: string) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.unarchive` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ unarchiveAsset: (data: Asset) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.asset.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getPublishedAssets: <Query extends SearchQuery = SearchQuery>( query?: Query ) => Promise<CollectionResponse<Asset>> /** * @deprecated since version 4.0.0 * Consider using `cma.upload.create` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ createUpload: (base64data: string) => Promise<Upload> /** * @deprecated since version 4.0.0 * Consider polling `cma.asset.get` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ waitUntilAssetProcessed: (assetId: string, locale: string) => Promise<Asset> /** * @deprecated since version 4.0.0 * Consider using `cma.user.getManyForSpace` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details * Returns all users who belong to the space. */ getUsers: () => Promise<CollectionResponse<User>> /** * @deprecated since version 4.0.0 * Consider using `cma.editorInterface.get` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details * Returns editor interface for a given content type */ getEditorInterface: (contentTypeId: string) => Promise<EditorInterface> /** * @deprecated since version 4.0.0 * Consider using `cma.editorInterface.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details * Returns editor interfaces for a given environment */ getEditorInterfaces: () => Promise<CollectionResponse<EditorInterface>> /** * @deprecated since version 4.0.0 * Consider using `cma.scheduledActions.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details * Returns a list of scheduled actions for a given entity */ getEntityScheduledActions: ( entityType: ContentEntityType, entityId: string ) => Promise<ScheduledAction[]> /** * @deprecated since version 4.0.0 * Consider using `cma.scheduledActions.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details * Returns a list of scheduled actions for the currenst space & environment */ getAllScheduledActions: () => Promise<ScheduledAction[]> /** * @deprecated since version 4.0.0 * Consider using `cma.appSignedRequest.create` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ signRequest: (request: CanonicalRequest) => Promise<Record<string, string>> /** * @deprecated since version 4.0.0 * Consider using `cma.tag.create` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ createTag: (id: string, name: string, visibility?: TagVisibility) => Promise<Tag> /** * @deprecated since version 4.0.0 * Consider using `cma.tag.getMany` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ readTags: (skip: number, limit: number) => Promise<CollectionResponse<Tag>> /** * @deprecated since version 4.0.0 * Consider using `cma.tag.update` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ updateTag: (id: string, name: string, version: number) => Promise<Tag> /** * @deprecated since version 4.0.0 * Consider using `cma.tag.delete` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ deleteTag: (id: string, version: number) => Promise<boolean> /** * @deprecated since version 4.0.0 * Consider using `cma.team.get` instead * See https://www.contentful.com/developers/docs/extensibility/app-framework/sdk/#using-the-contentful-management-library for more details */ getTeams: (query: QueryOptions) => Promise<CollectionResponse<Team>> }
the_stack
import { ConnectionProvider, useConnection, useWallet, WalletProvider, } from "@solana/wallet-adapter-react"; import * as web3 from "@solana/web3.js"; import { getLedgerWallet, getPhantomWallet, getSlopeWallet, getSolflareWallet, } from "@solana/wallet-adapter-wallets"; import { useCallback, useEffect, useMemo, useState, } from "react"; import { WalletModalProvider, } from "@solana/wallet-adapter-react-ui"; import Console from "./Console"; import { ResponsiveMonacoEditor } from "./Monaco"; import WalletButton from "./WalletButton"; import { useSlotInfo } from "./useWeb3"; import Tree, { TreeProvider } from "./Tree"; import { monaco } from "react-monaco-editor"; import Parser from "web-tree-sitter"; import Tabs from "./Tabs"; import { markEditorErrors } from "./Editor"; import { useLanguageParser } from "./useTreeSitter"; import { LLVMProvider, useFileSystem, useLLVM } from "./useLLVM"; import { useExampleCode, useSysroot } from "./useAlon"; import { LogProvider, useLogs } from "./Log"; import { SaveIcon, TrashIcon, UploadIcon } from "@heroicons/react/outline"; import SHA from "jssha"; import * as sha3 from "js-sha3"; import { useAsyncFn, useMountedState } from "react-use"; import Modal from "react-modal"; import * as zip from "@zip.js/zip.js"; import { TokenAccounts } from "./TokenAccounts"; import { useRef } from "react"; const App = () => { const wallets = useMemo( () => [ getPhantomWallet(), getSlopeWallet(), getSolflareWallet(), getLedgerWallet(), ], [] ); return ( <ConnectionProvider endpoint={web3.clusterApiUrl("devnet")}> <WalletProvider wallets={wallets}> <WalletModalProvider> <LogProvider> <LLVMProvider> <Main /> </LLVMProvider> </LogProvider> </WalletModalProvider> </WalletProvider> </ConnectionProvider> ); }; const SlotInfo = () => { const slotInfo = useSlotInfo(); return ( <dl> <div className="grid grid-cols-2 gap-4 text-xs"> <dt className="font-medium text-gray-500">Slot Number</dt> <dd className="text-gray-900 justify-self-end">{slotInfo?.slot.toLocaleString() ?? '-'}</dd> </div> <div className="grid grid-cols-2 gap-4 text-xs"> <dt className="font-medium text-gray-500">Root Number</dt> <dd className="text-gray-900 justify-self-end">{slotInfo?.root.toLocaleString() ?? '-'}</dd> </div> <div className="grid grid-cols-2 gap-4 text-xs"> <dt className="font-medium text-gray-500">Parent Number</dt> <dd className="text-gray-900 justify-self-end">{slotInfo?.parent.toLocaleString() ?? '-'}</dd> </div> </dl> ); } const Main = () => { const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor | null>(null); const handleEditorMount = useCallback((editor: monaco.editor.IStandaloneCodeEditor) => { setEditor(editor); }, [setEditor]); const sysrootLoadState = useSysroot(); const sysrootLoaded = !sysrootLoadState.loading && sysrootLoadState.value === true; useExampleCode(editor, sysrootLoaded); const parser = useLanguageParser("tree-sitter-c.wasm"); const [tree, setTree] = useState<Parser.Tree | null>(null); useEffect(() => { if (!editor) { return; } const changeModelHandler = editor.onDidChangeModel(event => { editor.updateOptions({ readOnly: event.newModelUrl?.path.startsWith("/usr") || !event.newModelUrl?.path.endsWith(".c") }); setTree(null); }); return () => { changeModelHandler.dispose(); } }, [editor]); const { fs, sync } = useFileSystem(); const [files, setFiles] = useState<any[]>([]); const getFileName = useCallback(node => node.name, []); const getFileChildren = useCallback(node => { if (!node.isFolder) return undefined; return Object.values(node.contents).sort((a: any, b: any): number => { if (a.isFolder === b.isFolder) { return (a.name as string).localeCompare(b); } return a.isFolder ? -1 : 1; }); }, []); const handleFileClicked = useCallback(node => { if (!editor || !fs) return; const uri = monaco.Uri.file(fs.getPath(node)); let model = monaco.editor.getModel(uri) if (model === null) { const contents = !node.contents ? "" : new TextDecoder().decode(node.contents); model = monaco.editor.createModel(contents, undefined, uri); } editor.setModel(model); }, [editor, fs]); useEffect(() => { let isMounted = true; if (!fs || !sysrootLoaded) { if (isMounted) setFiles([]); return; } if (isMounted) setFiles(["/project", "/usr/include/solana"].map(path => fs.lookupPath(path, {}).node)); return () => { isMounted = false; } }, [fs, sysrootLoaded]); const log = useLogs(); const { llvm, compiler } = useLLVM(); const [compilation, handleClickCompile] = useAsyncFn(async () => { if (!editor || !llvm || !fs || !compiler || !sysrootLoaded) { return; } const getSourceFileNames = (node: any): string[] => { const names = []; if (node.isFolder) { for (const child of Object.values(node.contents)) { names.push(...getSourceFileNames(child)); } } else { const nodePath = fs.getPath(node); if (nodePath.endsWith(".c")) { names.push(nodePath); } } return names; }; const root = fs.lookupPath("/project", {}).node; const sourceFileNames = getSourceFileNames(root); const baseCompilerArgs = [ "-Werror", "-O2", "-fno-builtin", "-std=c17", "-isystem/usr/include/clang", "-isystem/usr/include/solana", "-mrelocation-model", "pic", "-pic-level", "2", "-emit-obj", "-I/project/", "-triple", "bpfel-unknown-unknown-bpfel+solana", ]; log.write("compiler", "Compiling with arguments:") log.write("compiler", baseCompilerArgs); for (const sourceFileName of sourceFileNames) { const compilerArgs = [...baseCompilerArgs, "-o", `${sourceFileName.slice(0, -2)}.o`, sourceFileName]; const compilerArgsList = new llvm.StringList(); compilerArgs.forEach(arg => compilerArgsList.push_back(arg)); const compileResult = await compiler.compile(compilerArgsList); if (!compileResult.success) { log.write("compiler", "Error while compiling:"); log.write("compiler", compileResult.diags); for (const sourceFileName of sourceFileNames) { try { fs.unlink(`${sourceFileName.slice(0, -2)}.o`); } catch { } } return; } } try { fs.unlink("/project/program.so"); } catch { } const linkerArgs = [ "-z", "notext", "-shared", "--Bdynamic", "/usr/share/bpf.ld", "--entry", "entrypoint", "/usr/lib/libcompiler_builtins.rlib", "-o", "/project/program.so", ]; for (const sourceFileName of sourceFileNames) { linkerArgs.push(`${sourceFileName.slice(0, -2)}.o`); } const linkerArgsList = new llvm.StringList(); linkerArgs.forEach(arg => linkerArgsList.push_back(arg)); log.write("compiler", "Linking with arguments:"); log.write("compiler", linkerArgs); const linkResult = await compiler.linkBpf(linkerArgsList); for (const sourceFileName of sourceFileNames) { try { fs.unlink(`${sourceFileName.slice(0, -2)}.o`); } catch { } } if (!linkResult.success) { log.write("compiler", "Error while linking:"); log.write("compiler", linkResult.err); return; } log.write("compiler", `Successfully linked 'program.so'.`); sync(); }, [log, editor, fs, sync, llvm, compiler, sysrootLoaded]); const [testRunner, handleClickRunTests] = useAsyncFn(async () => { if (!editor || !llvm || !fs || !compiler || !sysrootLoaded) { return; } const getSourceFileNames = (node: any): string[] => { const names = []; if (node.isFolder) { for (const child of Object.values(node.contents)) { names.push(...getSourceFileNames(child)); } } else { const nodePath = fs.getPath(node); if (nodePath.endsWith(".c")) { names.push(nodePath); } } return names; }; const root = fs.lookupPath("/project", {}).node; const sourceFileNames = getSourceFileNames(root); const baseCompilerArgs = [ "-Werror", "-O2", "-fno-builtin", "-std=c17", "-isystem/usr/include/clang", "-isystem/usr/include/solana", "-mrelocation-model", "pic", "-pic-level", "2", "-emit-obj", "-I/project/", "-triple", "wasm32-unknown-unknown", "-DALON_TEST", ]; log.write("compiler", "Compiling tests with arguments:") log.write("compiler", baseCompilerArgs); for (const sourceFileName of sourceFileNames) { const compilerArgs = [...baseCompilerArgs, "-o", `${sourceFileName.slice(0, -2)}.o`, sourceFileName]; const compilerArgsList = new llvm.StringList(); compilerArgs.forEach(arg => compilerArgsList.push_back(arg)); const compileResult = await compiler.compile(compilerArgsList); if (!compileResult.success) { log.write("compiler", "Error while compiling tests:"); log.write("compiler", compileResult.diags); for (const sourceFileName of sourceFileNames) { try { fs.unlink(`${sourceFileName.slice(0, -2)}.o`); } catch { } } return; } } try { fs.unlink("/project/test.wasm"); } catch { } const linkerArgs = [ "--no-entry", "--import-memory", "--export-all", "--allow-undefined", "-o", "/project/test.wasm", ]; for (const sourceFileName of sourceFileNames) { linkerArgs.push(`${sourceFileName.slice(0, -2)}.o`); } const linkerArgsList = new llvm.StringList(); linkerArgs.forEach(arg => linkerArgsList.push_back(arg)); log.write("compiler", "Linking tests with arguments:"); log.write("compiler", linkerArgs); const linkResult = await compiler.linkWasm(linkerArgsList); for (const sourceFileName of sourceFileNames) { try { fs.unlink(`${sourceFileName.slice(0, -2)}.o`); } catch { } } if (!linkResult.success) { log.write("compiler", "Error while linking tests:"); log.write("compiler", linkResult.err); return; } log.write("compiler", `Successfully linked 'test.wasm'.`); const bytes = fs.readFile("/project/test.wasm"); try { fs.unlink(`/project/test.wasm`); } catch { } console.log("LINKED"); const memory = new WebAssembly.Memory({ initial: 2 }); const buffer = new Uint8Array(memory.buffer); const slice = (ptr: number, len: number) => { return buffer.slice(ptr, ptr + Number(len)); } const blake3 = await import("blake3/browser"); console.log("BEFORE"); try { const { instance } = await WebAssembly.instantiate(bytes, { env: { memory, sol_panic_(file: number, len: number, line: number, column: number) { throw new Error(`Panic in ${new TextDecoder().decode(slice(file, len))} at ${line}:${column}`); }, sol_log_(ptr: number, len: number) { log.write("compiler", `Program log: ${new TextDecoder().decode(slice(ptr, len))}`); }, sol_log_64_(a: number, b: number, c: number, d: number, e: number) { log.write("compiler", `Program log: ${a}, ${b}, ${c}, ${d}, ${e}`); }, sol_log_compute_units_() { log.write("compiler", `Program consumption: __ units remaining`); }, sol_log_pubkey(ptr: number) { log.write("compiler", `Program log: ${new web3.PublicKey(slice(ptr, 32)).toBase58()}`); }, sol_create_program_address(seeds: number, seeds_len: number, program_id: number, program_address: number) { let payload = Buffer.of(); for (let i = 0; i < seeds_len; i++) { const view = new DataView(buffer.buffer, seeds + i * 16, 16); payload = Buffer.concat([payload, Buffer.from(slice(view.getUint32(0, true), view.getUint32(8, true)))]); } payload = Buffer.concat([payload, Buffer.from(slice(program_id, 32)), Buffer.from("ProgramDerivedAddress")]); const hasher = new SHA("SHA-256", "UINT8ARRAY"); hasher.update(payload); const hash = hasher.getHash("UINT8ARRAY"); if (web3.PublicKey.isOnCurve(hash)) { return BigInt(1); } buffer.set(hash, program_address); return BigInt(0); }, sol_try_find_program_address(seeds: number, seeds_len: number, program_id: number, program_address: number, bump_seed: number) { for (let nonce = 255; nonce > 0; nonce--) { let payload = Buffer.of(); for (let i = 0; i < seeds_len; i++) { const view = new DataView(buffer.buffer, seeds + i * 16, 16); payload = Buffer.concat([payload, Buffer.from(slice(view.getUint32(0, true), view.getUint32(8, true)))]); } payload = Buffer.concat([payload, Buffer.of(nonce), Buffer.from(slice(program_id, 32)), Buffer.from("ProgramDerivedAddress")]); const hasher = new SHA("SHA-256", "UINT8ARRAY"); hasher.update(payload); const hash = hasher.getHash("UINT8ARRAY"); if (!web3.PublicKey.isOnCurve(hash)) { buffer.set(hash, program_address); buffer.set([nonce], bump_seed); return BigInt(0); } } return BigInt(1); }, sol_sha256: (bytes: number, bytes_len: number, result_ptr: number) => { const hasher = new SHA("SHA-256", "UINT8ARRAY"); for (let i = 0; i < bytes_len; i++) { // A slice is assumed to be 16 bytes. // Offset 0 is a 4-byte LE number depicting the slice's pointer. // 8 is a 4-byte LE number depicting the slice's length. const view = new DataView(buffer.buffer, bytes + i * 16, 16); hasher.update(slice(view.getUint32(0, true), view.getUint32(8, true))); } buffer.set(hasher.getHash("UINT8ARRAY"), result_ptr); return BigInt(0); }, sol_keccak256: (bytes: number, bytes_len: number, result_ptr: number) => { const hasher = sha3.keccak256.create(); for (let i = 0; i < bytes_len; i++) { // A slice is assumed to be 16 bytes. // Offset 0 is a 4-byte LE number depicting the slice's pointer. // 8 is a 4-byte LE number depicting the slice's length. const view = new DataView(buffer.buffer, bytes + i * 16, 16); hasher.update(slice(view.getUint32(0, true), view.getUint32(8, true))); } buffer.set(hasher.digest(), result_ptr); return BigInt(0); }, sol_blake3: (bytes: number, bytes_len: number, result_ptr: number) => { const hasher = blake3.createHash(); for (let i = 0; i < bytes_len; i++) { // A slice is assumed to be 16 bytes. // Offset 0 is a 4-byte LE number depicting the slice's pointer. // 8 is a 4-byte LE number depicting the slice's length. const view = new DataView(buffer.buffer, bytes + i * 16, 16); hasher.update(slice(view.getUint32(0, true), view.getUint32(8, true))); } buffer.set(hasher.digest(), result_ptr); return BigInt(0); }, sol_invoke_signed_c: (_instruction: any, _account_infos: any, _account_infos_len: any, _signer_seeds: any, _signer_seeds_len: any) => { return BigInt(0); }, sol_alloc_free_: (size: BigInt, ptr: number) => { } } }); console.log("AFTER"); const tests = Object.entries(instance.exports).filter(([key,]) => key.startsWith("test_")); let count = 1; for (const [testName, testFunction] of tests) { const formattedTestName = testName.substring("test_".length).replace("__", "::"); try { // @ts-ignore testFunction(); log.write("compiler", `\u001b[32m[${count}/${tests.length}] ${formattedTestName} ✓ success!\u001b[0m\n`); } catch (err) { // @ts-ignore log.write("compiler", `\u001b[31m[${count}/${tests.length}] ${formattedTestName} ✗ failed\u001b[0m\n\n${err.stack}`); } count += 1; } } catch (err) { console.error(err); } sync(); }, [log, editor, fs, sync, llvm, compiler, sysrootLoaded]); const handleTrashLogsClicked = useCallback((scope: string) => { log.clear(scope); }, [log]); const handleSaveLogsClicked = useCallback((scope: string) => { const logs = log.get(scope) ?? []; if (logs.length === 0) return; saveAs(new Blob([JSON.stringify(logs)]), `${scope}_logs.txt`); }, [log]); const [importModalIsOpened, setImportModalIsOpened] = useState(false); const [importUrl, setImportUrl] = useState(""); const modalStyles = { overlay: { backgroundColor: 'rgba(0, 0, 0, 0.75)', display: 'flex', justifyContent: 'center', alignItems: 'center', } }; const handleImportSourceArchiveClicked = useCallback(async () => { if (!fs) { return; } const url = importUrl; setImportModalIsOpened(false); setImportUrl(""); log.write("alon", `Downloading ZIP archive from '${url}'...`); const blob = await (await fetch(`https://cors.bridged.cc/${url}`, { headers: { "x-cors-grida-api-key": "7a571699-418f-4f84-83b8-51393c448c40", } })).blob(); log.write("alon", "Unpacking ZIP archive..."); const reader = new zip.ZipReader(new zip.BlobReader(blob)); const entries = await reader.getEntries(); const recursiveDelete = (node: any) => { const path = fs.getPath(node); const model = monaco.editor.getModels().find(model => model.uri.path === path); if (model) { model.dispose(); } if (node.isFolder) { Object.values(node.contents).forEach(recursiveDelete); fs.rmdir(path); } else { fs.unlink(path); } }; const result = fs.lookupPath("/project", {}); Object.values((result.node as any).contents).forEach(recursiveDelete); for (const entry of entries) { const path = "/project/" + entry.filename.slice(entry.filename.indexOf("/") + 1); if (entry.directory) { try { fs.mkdir(path); } catch { } continue; } const bytes = await entry.getData!(new zip.Uint8ArrayWriter()); fs.writeFile(path, bytes); log.write("alon", `Unpacked source archive file '${path}'.`); } await reader.close(); log.write("alon", "Source ZIP archive unpacked."); sync(); }, [fs, log, importUrl, setImportUrl, sync]); const { connection } = useConnection(); const { publicKey } = useWallet(); const handleClickAirdrop = useCallback(async () => { if (!connection || !publicKey) { return; } log.write("alon", `Requesting an airdrop for 1 SOL to <a class="underline text-gray-700" href="https://explorer.solana.com/address/${publicKey.toBase58()}?cluster=devnet">${publicKey.toBase58()}</a>.`); try { const transactionId = await connection.requestAirdrop(publicKey, 1 * web3.LAMPORTS_PER_SOL); log.write("alon", `Waiting for the airdrop transaction for 1 SOL to be fully confirmed. Transaction ID: <a class="underline text-gray-700" href="https://explorer.solana.com/tx/${transactionId}?cluster=devnet">${transactionId}</a>`) await connection.confirmTransaction(transactionId); log.write("alon", `Airdrop transaction <a class="underline text-gray-700" href="https://explorer.solana.com/tx/${transactionId}?cluster=devnet">${transactionId}</a> has been fully confirmed.`); } catch (err) { // @ts-ignore log.write("alon", `An error occurred while attempting to airdrop 1 SOL to <a class="underline text-gray-700" href="https://explorer.solana.com/address/${publicKey.toBase58()}?cluster=devnet">${publicKey.toBase58()}</a>.\n\n${err.stack}`) } }, [log, connection, publicKey]); const [autoRunTests, setAutoRunTests] = useState(false); const autoRunTestTimeoutHandle = useRef<number | null>(null); const isMounted = useMountedState(); const handleChangeCode = useCallback((newCode: string, event: monaco.editor.IModelContentChangedEvent) => { if (!fs || !editor || !parser) { return; } const model = editor.getModel(); if (!model) { return; } fs.writeFile(model.uri.path, newCode); if (autoRunTests) { if (autoRunTestTimeoutHandle.current) { clearTimeout(autoRunTestTimeoutHandle.current); } autoRunTestTimeoutHandle.current = setTimeout(() => { if (isMounted()) { handleClickRunTests(); } }, 250) as any; } if (!tree) { const newTree = parser.parse(newCode); markEditorErrors(newTree, editor); setTree(newTree); return; } if (event.changes.length > 0) { for (const change of event.changes) { const startIndex = change.rangeOffset; const oldEndIndex = change.rangeOffset + change.rangeLength; const newEndIndex = change.rangeOffset + change.text.length; const startPosition = editor.getModel()!.getPositionAt(startIndex); const oldEndPosition = editor.getModel()!.getPositionAt(oldEndIndex); const newEndPosition = editor.getModel()!.getPositionAt(newEndIndex); tree.edit({ startIndex, oldEndIndex, newEndIndex, startPosition: { row: startPosition.lineNumber, column: startPosition.column }, oldEndPosition: { row: oldEndPosition.lineNumber, column: oldEndPosition.column }, newEndPosition: { row: newEndPosition.lineNumber, column: newEndPosition.column }, }); } const newTree = parser.parse(newCode, tree); markEditorErrors(newTree, editor); setTree(newTree); } }, [fs, editor, parser, tree, autoRunTests, handleClickRunTests, isMounted]); return ( <> <div className="font-mono antialiased grid grid-flow-row auto-rows-min-auto w-full h-full max-h-full"> <div className=" bg-gray-200 border-b"> <div className="flex"> <button className={`bg-gray-100 px-2 py-1 text-xs border-r text-center flex whitespace-nowrap gap-2 ${sysrootLoaded && !compilation.loading && !testRunner.loading ? "hover:bg-gray-300" : "animate-pulse bg-gray-200 cursor-default"}`} disabled={!sysrootLoaded || compilation.loading || testRunner.loading} onClick={handleClickCompile}> Compile <span className="text-gray-600">(F1)</span> </button> <button className={`bg-gray-100 px-2 py-1 text-xs border-r text-center flex whitespace-nowrap gap-2 ${sysrootLoaded && !compilation.loading && !testRunner.loading ? "hover:bg-gray-300" : "animate-pulse bg-gray-200 cursor-default"}`} disabled={!sysrootLoaded || compilation.loading || testRunner.loading} onClick={handleClickRunTests}> Run Tests <span className="text-gray-600">(F2)</span> </button> <div className={`bg-gray-100 px-2 py-1 text-xs border-r text-center flex whitespace-nowrap gap-2 ${sysrootLoaded && !compilation.loading ? "hover:bg-gray-300" : "bg-gray-200 cursor-default"}`}> <input type="checkbox" disabled={!sysrootLoaded || compilation.loading} checked={autoRunTests} onChange={() => setAutoRunTests(checked => !checked)} /> <label>Auto-run Tests</label> <span className="text-gray-600">(F3)</span> </div> <button className={`bg-gray-100 px-2 py-1 text-xs border-r text-center flex whitespace-nowrap gap-2 ${connection && publicKey ? "hover:bg-gray-300" : "bg-gray-200 cursor-default"}`} disabled={!connection || !publicKey} onClick={handleClickAirdrop}> Airdrop 1 SOL <span className="text-gray-600">(F4)</span> </button> </div> </div> <div className="w-full h-full grid grid-flow-col auto-cols-min-auto"> <div className="border-r p-4 flex flex-col gap-4" style={{ width: "24rem" }}> <p className="text-2xl leading-7 font-bold">Alon</p> <SlotInfo /> <WalletButton className="w-full" /> <div> <TokenAccounts /> </div> <div className="flex flex-col h-full"> <div className="flex-grow-0 font-lg leading-6 mb-1 flex justify-between"> Files <button onClick={() => setImportModalIsOpened(true)} disabled={!sysrootLoaded} className={`${!sysrootLoaded ? `cursor-default` : ``}`}> <UploadIcon className={`w-5 h-5 p-0.5 bg-gray-100 rounded-lg ${!sysrootLoaded ? `text-gray-400` : `hover:bg-gray-300`}`} /> </button> </div> <div className={`relative flex-grow border text-xs overflow-y-auto scrollbar-thin scrollbar-thumb-gray-400 scrollbar-track-gray-200 ${sysrootLoaded ? "" : "animate-pulse"}`}> <TreeProvider data={files} getName={getFileName} getChildren={getFileChildren} onClicked={handleFileClicked}> <Tree<any> className="absolute top-0 left-0 bottom-0 right-0" /> </TreeProvider> </div> </div> </div> <div className={`w-full h-full flex flex-col ${sysrootLoaded ? "" : "animate-pulse"}`}> <Tabs editor={editor} /> <div className={`w-full h-full bg-gray-100 ${sysrootLoaded ? "" : "animate-pulse"}`}> <ResponsiveMonacoEditor options={{ fontSize: 12, padding: { top: 16, }, model: null, }} editorDidMount={handleEditorMount} onChange={handleChangeCode} /> </div> </div> <div className="flex flex-col gap-1 border-l" style={{ width: "36rem" }}> <div className="border-b flex-grow flex flex-col"> <div className="px-2 py-1 text-sm font-medium flex justify-between items-center"> Compiler Logs <div className="flex gap-1"> <button> <SaveIcon className="w-5 h-5 p-0.5 bg-gray-100 hover:bg-gray-300 rounded-lg" onClick={() => handleSaveLogsClicked("compiler")} /> </button> <button> <TrashIcon className="w-5 h-5 p-0.5 bg-gray-100 hover:bg-gray-300 rounded-lg" onClick={() => handleTrashLogsClicked("compiler")} /> </button> </div> </div> <Console scope="compiler" /> </div> <div className="border-b flex-grow flex flex-col"> <div className="px-2 py-1 text-sm font-medium flex justify-between items-center"> Alon Logs <div className="flex gap-1"> <button> <SaveIcon className="w-5 h-5 p-0.5 bg-gray-100 hover:bg-gray-300 rounded-lg" onClick={() => handleSaveLogsClicked("alon")} /> </button> <button> <TrashIcon className="w-5 h-5 p-0.5 bg-gray-100 hover:bg-gray-300 rounded-lg" onClick={() => handleTrashLogsClicked("alon")} /> </button> </div> </div> <Console scope="alon" /> </div> </div> </div> </div > <Modal isOpen={importModalIsOpened} onRequestClose={() => setImportModalIsOpened(false)} style={modalStyles} className="font-mono"> <div className="p-4 py-6 flex flex-col gap-2 m-auto bg-white w-96"> <div className="py-2 break-words"> Provide a link to a ZIP archive containing your source files. </div> <div className="flex flex-col gap-4"> <input type="url" className="p-2 border" placeholder="https://github.com/lithdew/alon-sysroot/archive/refs/heads/master.zip" value={importUrl} onChange={(event) => setImportUrl(event.target.value)} /> <div> <button className="flex w-full" onClick={handleImportSourceArchiveClicked}> <span className="rounded px-4 py-1 bg-gray-900 hover:bg-gray-700 text-white appearance-none shadow-lg w-full">Import</span> </button> </div> </div> </div> </Modal> </> ); }; export default App;
the_stack
// tslint:disable: max-func-body-length object-literal-key-quotes import * as assert from "assert"; import { getResourceInfo, getResourcesInfo, ResourceInfo } from "../../extension.bundle"; import { IPartialDeploymentTemplate } from "../support/diagnostics"; import { parseTemplate } from "../support/parseTemplate"; suite("ResourceInfo", () => { suite("split names", () => { function createSplitNameTest(nameAsJsonString: string, expected: string[]): void { test(nameAsJsonString, async () => { const dt = parseTemplate({ resources: [ { name: nameAsJsonString, type: "ms.abc/def" } ] }); // tslint:disable-next-line: no-non-null-assertion const info = getResourceInfo(dt.topLevelScope.rootObject!.getPropertyValue('resources')!.asArrayValue!.elements[0].asObjectValue!)!; const actual = info.nameSegmentExpressions; assert.deepStrictEqual(actual, expected); }); } createSplitNameTest("simple string", ["'simple string'"]); createSplitNameTest("simple string/separated", ["'simple string'", "'separated'"]); createSplitNameTest("simple string/separated/again", ["'simple string'", "'separated'", "'again'"]); createSplitNameTest("[]", ['']); createSplitNameTest("[variables('a')]", ["variables('a')"]); createSplitNameTest("[concat(variables('a'), variables('b'))]", ["concat(variables('a'), variables('b'))"]); createSplitNameTest("[concat(variables('a'), '/', variables('b'))]", ["variables('a')", "variables('b')"]); createSplitNameTest("[concat(variables('a'), '/b')]", ["variables('a')", "'b'"]); createSplitNameTest("[concat(variables('a'), '/b', '/', variables('c'))]", ["variables('a')", "'b'", "variables('c')"]); }); suite("split types", () => { function createSplitTypeTest(typeAsJsonString: string, expected: string[]): void { test(typeAsJsonString, async () => { const dt = parseTemplate({ resources: [ { name: "name", type: typeAsJsonString } ] }); // tslint:disable-next-line: no-non-null-assertion const info = getResourceInfo(dt.topLevelScope.rootObject!.getPropertyValue('resources')!.asArrayValue!.elements[0].asObjectValue!); // tslint:disable-next-line: no-non-null-assertion const actual = info!.typeSegmentExpressions; assert.deepStrictEqual(actual, expected); }); } suite("invalid types", () => { createSplitTypeTest("", ["''"]); createSplitTypeTest("simple string", ["'simple string'"]); createSplitTypeTest("simple string/separated", ["'simple string/separated'"]); createSplitTypeTest("[]", ['']); createSplitTypeTest("[variables('a')]", ["variables('a')"]); createSplitTypeTest("[concat(variables('a'), variables('b'))]", ["concat(variables('a'), variables('b'))"]); }); suite("simple strings", () => { createSplitTypeTest("Microsoft.Sql/servers", ["'Microsoft.Sql/servers'"]); createSplitTypeTest("Microsoft.Sql/servers/firewallRules", ["'Microsoft.Sql/servers'", "'firewallRules'"]); createSplitTypeTest("Microsoft.Sql/servers/firewallRules/another", ["'Microsoft.Sql/servers'", "'firewallRules'", "'another'"]); }); suite('expressions', () => { createSplitTypeTest("[variables('sqlservers')]", ["variables('sqlservers')"]); createSplitTypeTest("[concat('Microsoft.Sql/servers')]", ["'Microsoft.Sql/servers'"]); createSplitTypeTest("[concat('Microsoft.Sql', '/servers')]", ["'Microsoft.Sql/servers'"]); createSplitTypeTest("[concat('Microsoft.Sql/', 'servers')]", ["'Microsoft.Sql/servers'"]); createSplitTypeTest("[concat('Microsoft.Sql', '/', 'servers')]", ["'Microsoft.Sql/servers'"]); createSplitTypeTest("[concat('Microsoft.Sql', '/', variables('servers'))]", ["concat('Microsoft.Sql/', variables('servers'))"]); // This one is ambiguous - we don't know if variables('a') or variables('b') contains a '/'. If they do, they're separate segments, otherwise a single segment. // Like with names, we always assume that variables/variables do *not* contain slashes. But this is just one way to interpret this. createSplitTypeTest("[concat('Microsoft.Sql', '/', variables('a'), variables('b'))]", ["concat('Microsoft.Sql/', concat(variables('a'), variables('b')))"]); createSplitTypeTest("[concat('Microsoft.Sql', '/', variables('servers'),'/', variables('grandchild'))]", ["concat('Microsoft.Sql/', variables('servers'))", "variables('grandchild')"]); createSplitTypeTest("[concat('Microsoft.Sql', '/', variables('servers'),'/', 'grandchild')]", ["concat('Microsoft.Sql/', variables('servers'))", "'grandchild'"]); // Again, assuming "/servers" and variables('other') must go together because there's no '/' in between. // Not currently optimizing the expression as well as we could createSplitTypeTest("[concat('Microsoft.Sql', '/servers', variables('other'),'/', 'grandchild')]", ["concat('Microsoft.Sql/', concat('servers', variables('other')))", "'grandchild'"]); createSplitTypeTest("[concat('Microsoft.Sql', variables('slashservers'),'/', 'grandchild')]", ["concat('Microsoft.Sql', variables('slashservers'))", "'grandchild'"]); createSplitTypeTest("[concat('Microsoft.Sql/servers/', variables('servers'))]", ["'Microsoft.Sql/servers'", "variables('servers')"]); createSplitTypeTest("[concat('Microsoft.Sql/servers/other2', variables('servers'))]", ["'Microsoft.Sql/servers'", "concat('other2', variables('servers'))"]); createSplitTypeTest("[concat('Microsoft.Sql/servers/other2/', variables('servers'))]", ["'Microsoft.Sql/servers'", "'other2'", "variables('servers')"]); createSplitTypeTest("Microsoft.Sql/servers", ["'Microsoft.Sql/servers'"]); createSplitTypeTest("Microsoft.Sql/servers/firewallRules", ["'Microsoft.Sql/servers'", "'firewallRules'"]); createSplitTypeTest("Microsoft.Sql/servers/firewallRules/another", ["'Microsoft.Sql/servers'", "'firewallRules'", "'another'"]); }); createSplitTypeTest("[variables('a')]", ["variables('a')"]); createSplitTypeTest("[concat(variables('a'), variables('b'))]", ["concat(variables('a'), variables('b'))"]); createSplitTypeTest("[concat(variables('a'), '/', variables('b'))]", ["variables('a')", "variables('b')"]); createSplitTypeTest("[concat(variables('a'), '/b')]", ["variables('a')", "'b'"]); createSplitTypeTest("[concat(variables('a'), '/b', '/', variables('c'))]", ["variables('a')", "'b'", "variables('c')"]); createSplitTypeTest("[concat(variables('a'), '/b')]", ["variables('a')", "'b'"]); createSplitTypeTest("[concat('ms.abc', '/', parameters('b'))]", ["concat('ms.abc/', parameters('b'))"]); createSplitTypeTest("[concat('ms.abc', '/', parameters('b'))]", ["concat('ms.abc/', parameters('b'))"]); createSplitTypeTest("[concat('ms.abc/', parameters('b'))]", ["concat('ms.abc/', parameters('b'))"]); createSplitTypeTest("[concat(parameters('a'), '/def/', parameters('b'))]", ["parameters('a')", "'def'", "parameters('b')"]); }); suite("fullTypeExpression", () => { function createFullTypeTest( typeSegmentExpressions: string[], expected: string | undefined ): void { const testName = JSON.stringify(typeSegmentExpressions); test(testName, () => { const ri = new ResourceInfo([], typeSegmentExpressions); const typeName = ri.getFullTypeExpression(); assert.deepStrictEqual(typeName, expected); }); } createFullTypeTest([], undefined); createFullTypeTest([`'a'`], `'a'`); createFullTypeTest([`'ms.abc'`], `'ms.abc'`); createFullTypeTest([`'ms.abc'`, `'def'`], `'ms.abc/def'`); createFullTypeTest([`'ms.abc'`, `'def'`, `'ghi'`], `'ms.abc/def/ghi'`); suite("expressions", () => { createFullTypeTest([`parameters('abc')`], `parameters('abc')`); createFullTypeTest([`parameters('abc')`, `'def'`], `concat(parameters('abc'), '/def')`); createFullTypeTest([`'abc'`, `parameters('def')`], `concat('abc/', parameters('def'))`); createFullTypeTest([`parameters('abc')`, `parameters('def')`], `concat(parameters('abc'), '/', parameters('def'))`); createFullTypeTest([`parameters('abc')`, `'def'`, `parameters('ghi')`], `concat(parameters('abc'), '/def/', parameters('ghi'))`); }); suite("coalesce consequence strings", () => { createFullTypeTest( [ `parameters('a')`, `'b'`, `'c'`, `'d'`, `parameters('e')`, `parameters('f')`, `'g'`, `'h'` ], `concat(parameters('a'), '/b/c/d/', parameters('e'), '/', parameters('f'), '/g/h')`); }); }); suite("shortTypeExpression", () => { function createShortTypeTest( typeSegmentExpressions: string[], expected: string | undefined ): void { const testName = JSON.stringify(typeSegmentExpressions); test(testName, () => { const ri = new ResourceInfo([], typeSegmentExpressions); const typeName = ri.shortTypeExpression; assert.deepStrictEqual(typeName, expected); }); } createShortTypeTest([], undefined); createShortTypeTest([`'a'`], `'a'`); createShortTypeTest([`'ms.abc'`], `'ms.abc'`); createShortTypeTest([`'ms.abc'`, `'def'`], `'def'`); createShortTypeTest([`'ms.abc'`, `'def'`, `'ghi'`], `'ghi'`); suite("expressions", () => { createShortTypeTest([`parameters('abc')`], `parameters('abc')`); createShortTypeTest([`parameters('abc')`, `'def'`], `'def'`); createShortTypeTest([`'abc'`, `parameters('def')`], `parameters('def')`); createShortTypeTest([`parameters('abc')`, `parameters('def')`], `parameters('def')`); createShortTypeTest([`parameters('abc')`, `'def'`, `parameters('ghi')`], `parameters('ghi')`); }); suite("coalesce consecutive strings", () => { createShortTypeTest( [ `parameters('a')`, `'b'`, `'c'`, `'d'`, `parameters('e')`, `parameters('f')`, `'g'`, `'h'` ], `'h'`); }); }); suite("fullNameExpression", () => { function createFullNameTest( nameSegmentExpressions: string[], expected: string | undefined ): void { const testName = JSON.stringify(nameSegmentExpressions); test(testName, () => { const ri = new ResourceInfo(nameSegmentExpressions, []); const typeName = ri.getFullNameExpression(); assert.deepStrictEqual(typeName, expected); }); } createFullNameTest([], undefined); createFullNameTest([`'a'`], `'a'`); createFullNameTest([`'abc'`, `'def'`], `'abc/def'`); createFullNameTest([`'abc'`, `'def'`, `'ghi'`], `'abc/def/ghi'`); suite("expressions", () => { createFullNameTest([`parameters('abc')`], `parameters('abc')`); createFullNameTest([`parameters('abc')`, `'def'`], `concat(parameters('abc'), '/def')`); createFullNameTest([`'abc'`, `parameters('def')`], `concat('abc/', parameters('def'))`); createFullNameTest([`parameters('abc')`, `parameters('def')`], `concat(parameters('abc'), '/', parameters('def'))`); createFullNameTest([`parameters('abc')`, `'def'`, `parameters('ghi')`], `concat(parameters('abc'), '/def/', parameters('ghi'))`); }); suite("coalesce consequence strings", () => { createFullNameTest( [ `parameters('a')`, `'b'`, `'c'`, `'d'`, `123`, `456`, `parameters('e')`, `parameters('f')`, `'g'`, `'h'` ], `concat(parameters('a'), '/b/c/d/', 123, '/', 456, '/', parameters('e'), '/', parameters('f'), '/g/h')`); }); }); suite("shortNameExpression", () => { function createShortNameTest( nameSegmentExpressions: string[], expected: string | undefined ): void { const testName = JSON.stringify(nameSegmentExpressions); test(testName, () => { const ri = new ResourceInfo(nameSegmentExpressions, []); const typeName = ri.shortNameExpression; assert.deepStrictEqual(typeName, expected); }); } createShortNameTest([], undefined); createShortNameTest([`'a'`], `'a'`); createShortNameTest([`'abc'`, `'def'`], `'def'`); createShortNameTest([`'abc'`, `'def'`, `'ghi'`], `'ghi'`); suite("expressions", () => { createShortNameTest([`parameters('abc')`], `parameters('abc')`); createShortNameTest([`parameters('abc')`, `'def'`], `'def'`); createShortNameTest([`'abc'`, `parameters('def')`], `parameters('def')`); createShortNameTest([`parameters('abc')`, `parameters('def')`], `parameters('def')`); createShortNameTest([`parameters('abc')`, `'def'`, `parameters('ghi')`], `parameters('ghi')`); }); suite("coalesce consequence strings", () => { createShortNameTest( [ `parameters('a')`, `'b'`, `'c'`, `'d'`, `123`, `456`, `parameters('e')`, `parameters('f')`, `'g'`, `'h'` ], `'h'`); }); }); suite("IResource getFriendlyName", () => { function createFriendlyNameTest( resource: ResourceInfo, expectedWithShortResourceName: string | undefined, expectedWithFullResourceName: string | undefined ): void { const testName = JSON.stringify(`${resource.getFullTypeExpression()}: ${resource.getFullNameExpression()}`); test(`${testName} (short name)`, () => { const actualShort = resource.getFriendlyResourceLabel({}); assert.deepStrictEqual(actualShort, expectedWithShortResourceName); }); test(`${testName} (full name)`, () => { const actualFull = resource.getFriendlyResourceLabel({ fullName: true }); assert.deepStrictEqual(actualFull, expectedWithFullResourceName); }); } createFriendlyNameTest( // simple string name with parent new ResourceInfo( [`'parent name'`, `'my name'`], [`'Microsoft.AAD/domainServices'`]), `my name (domainServices)`, `parent name/my name (domainServices)` ); // simple param/var name createFriendlyNameTest( new ResourceInfo( ["variables('b')"], [`'Microsoft.AAD/domainServices'`]), // tslint:disable-next-line: no-invalid-template-strings '${b} (domainServices)', // tslint:disable-next-line: no-invalid-template-strings '${b} (domainServices)'); // interpolatable name createFriendlyNameTest( new ResourceInfo( ["'prefix'", "variables('b')"], [`'Microsoft.AAD/domainServices'`]), // tslint:disable-next-line: no-invalid-template-strings '${b} (domainServices)', // tslint:disable-next-line: no-invalid-template-strings 'prefix/${b} (domainServices)'); // name with expression createFriendlyNameTest( new ResourceInfo( ["add(add(1, 2), '/', variables('b'))"], [`'Microsoft.AAD/domainServices'`]), // tslint:disable-next-line: no-invalid-template-strings "[add(add(1, 2), '/', ${b})] (domainServices)", // tslint:disable-next-line: no-invalid-template-strings "[add(add(1, 2), '/', ${b})] (domainServices)"); // simple type name with parent createFriendlyNameTest( new ResourceInfo( [`'my name'`], [`'Microsoft.AAD/domainServices/abc'`]), // tslint:disable-next-line: no-invalid-template-strings "my name (abc)", // tslint:disable-next-line: no-invalid-template-strings "my name (abc)" ); // type name with simple var/param createFriendlyNameTest( new ResourceInfo( [`'my name'`], [`variables('typeName')`]), // tslint:disable-next-line: no-invalid-template-strings "my name (${typeName})", // tslint:disable-next-line: no-invalid-template-strings "my name (${typeName})" ); // type name with expression createFriendlyNameTest( new ResourceInfo( [`'my name'`], [`add(1, variables('typeName'))`]), // tslint:disable-next-line: no-invalid-template-strings "my name ([add(1, ${typeName})])", // tslint:disable-next-line: no-invalid-template-strings "my name ([add(1, ${typeName})])"); }); suite("getResourceIdExpression", () => { function createResourceIdTest( testName: string, resource: ResourceInfo, expected: string | undefined ): void { testName = testName + JSON.stringify(`${resource.getFullTypeExpression()}: ${resource.getFullNameExpression()}`); test(testName, () => { const resourceId = resource.getResourceIdExpression(); assert.deepStrictEqual(resourceId, expected); }); } suite("empty name or type", () => { createResourceIdTest("", new ResourceInfo([], []), undefined); createResourceIdTest("", new ResourceInfo(['a'], []), undefined); createResourceIdTest("", new ResourceInfo([], ['a']), undefined); }); createResourceIdTest( "type has expressions", new ResourceInfo( [`'a'`], [`parameters('a')`, `'b'`] ), `resourceId(concat(parameters('a'), '/b'), 'a')`); createResourceIdTest( "names with multiple segments (they are not coalesced)", new ResourceInfo( [`'a'`, `'b'`, `variables('v1')`, `'c'`], [`'microsoft.abc/def'`] ), `resourceId('microsoft.abc/def', 'a', 'b', variables('v1'), 'c')`); }); suite("getResourcesInfo", () => { test("101-azure-database-migration-service", async () => { const template: IPartialDeploymentTemplate = { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "resources": [ { "type": "Microsoft.Compute/virtualMachines", "name": "[variables('sourceServerName')]", "dependsOn": [ "[resourceId('Microsoft.Network/networkInterfaces', variables('sourceNicName'))]" ], "resources": [ { "type": "extensions", "name": "SqlIaasExtension", "dependsOn": [ "[concat('Microsoft.Compute/virtualMachines/', variables('sourceServerName'))]" ] }, { "type": "extensions", "name": "CustomScriptExtension", "dependsOn": [ "[concat('Microsoft.Compute/virtualMachines/', variables('sourceServerName'))]", "[concat('Microsoft.Compute/virtualMachines/', concat(variables('sourceServerName'),'/extensions/SqlIaasExtension'))]" ] } ] }, { "type": "Microsoft.DataMigration/services", "name": "[variables('DMSServiceName')]", "properties": { "virtualSubnetId": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('adVNet'), variables('defaultSubnetName'))]" }, "resources": [ { "type": "projects", "name": "SqlToSqlDbMigrationProject", "dependsOn": [ "[resourceId('Microsoft.DataMigration/services', variables('DMSServiceName'))]" ] } ], "dependsOn": [ "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('adVNet'), variables('defaultSubnetName'))]" ] }, { "type": "Microsoft.Network/networkInterfaces", "name": "[variables('sourceNicName')]", "dependsOn": [ "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('adVNet'), variables('defaultSubnetName'))]", "[resourceId('Microsoft.Network/publicIpAddresses', variables('publicIPSourceServer'))]" ], "properties": { "ipConfigurations": [ { "name": "ipconfig", "properties": { "subnet": { "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('adVNet'), variables('defaultSubnetName'))]" } } } ] } }, { "type": "Microsoft.Network/networkSecurityGroups", "name": "[variables('sourceServerNSG')]" }, { "type": "Microsoft.Network/publicIPAddresses", "name": "[variables('publicIPSourceServer')]" }, { "type": "Microsoft.Network/virtualNetworks", "name": "[variables('adVNet')]", "properties": { "addressSpace": { "addressPrefixes": [ "10.2.0.0/24" ] }, "SUBNETS": [ { "name": "default", "properties": { "addressPrefix": "10.2.0.0/24" } } ], }, "resources": [ { "type": "Subnets", "name": "[variables('defaultSubnetName')]", "dependsOn": [ "[resourceId('Microsoft.Network/virtualNetworks', variables('adVNet'))]" ] } ] }, { "type": "Microsoft.Storage/storageAccounts", "name": "[variables('storageAccountName')]" }, { "type": "Microsoft.Sql/servers", "name": "[concat(variables('targetServerName'))]", "resources": [ { "type": "databases", "name": "[variables('databaseName')]", "dependsOn": [ "[resourceId('Microsoft.Sql/servers', concat(variables('targetServerName')))]" ], "resources": [ { "name": "Import", "type": "extensions", "dependsOn": [ "[resourceId('Microsoft.Sql/servers/databases', variables('targetServerName'), variables('databaseName'))]" ] } ] }, { "type": "firewallrules", "name": "AllowAllWindowsAzureIps", "dependsOn": [ "[resourceId('Microsoft.Sql/servers', concat(variables('targetServerName')))]" ] } ] } ] }; const dt = parseTemplate(template); const infos = getResourcesInfo({ scope: dt.topLevelScope, recognizeDecoupledChildren: false }); const actual = infos.map(info => ({ name: info.shortNameExpression, type: info.getFullTypeExpression(), resourceId: info.getResourceIdExpression(), parent: info.parent?.shortNameExpression })); const expected = [ { "type": "'Microsoft.Compute/virtualMachines'", "name": "variables('sourceServerName')", resourceId: "resourceId('Microsoft.Compute/virtualMachines', variables('sourceServerName'))", parent: undefined, }, { "type": "'Microsoft.Compute/virtualMachines/extensions'", "name": "'SqlIaasExtension'", resourceId: "resourceId('Microsoft.Compute/virtualMachines/extensions', variables('sourceServerName'), 'SqlIaasExtension')", parent: "variables('sourceServerName')" }, { "type": "'Microsoft.Compute/virtualMachines/extensions'", "name": "'CustomScriptExtension'", resourceId: "resourceId('Microsoft.Compute/virtualMachines/extensions', variables('sourceServerName'), 'CustomScriptExtension')", parent: "variables('sourceServerName')" }, { "type": "'Microsoft.DataMigration/services'", "name": "variables('DMSServiceName')", resourceId: "resourceId('Microsoft.DataMigration/services', variables('DMSServiceName'))", parent: undefined }, { "type": "'Microsoft.DataMigration/services/projects'", "name": "'SqlToSqlDbMigrationProject'", resourceId: "resourceId('Microsoft.DataMigration/services/projects', variables('DMSServiceName'), 'SqlToSqlDbMigrationProject')", parent: "variables('DMSServiceName')" }, { "type": "'Microsoft.Network/networkInterfaces'", "name": "variables('sourceNicName')", resourceId: `resourceId('Microsoft.Network/networkInterfaces', variables('sourceNicName'))`, parent: undefined }, { "type": "'Microsoft.Network/networkSecurityGroups'", "name": "variables('sourceServerNSG')", resourceId: "resourceId('Microsoft.Network/networkSecurityGroups', variables('sourceServerNSG'))", parent: undefined }, { "type": "'Microsoft.Network/publicIPAddresses'", "name": "variables('publicIPSourceServer')", resourceId: "resourceId('Microsoft.Network/publicIPAddresses', variables('publicIPSourceServer'))", parent: undefined }, { "type": "'Microsoft.Network/virtualNetworks'", "name": "variables('adVNet')", resourceId: "resourceId('Microsoft.Network/virtualNetworks', variables('adVNet'))", parent: undefined }, { "type": "'Microsoft.Network/virtualNetworks/Subnets'", "name": "variables('defaultSubnetName')", resourceId: `resourceId('Microsoft.Network/virtualNetworks/Subnets', variables('adVNet'), variables('defaultSubnetName'))`, parent: "variables('adVNet')" }, { "type": "'Microsoft.Network/virtualNetworks/subnets'", "name": "'default'", resourceId: "resourceId('Microsoft.Network/virtualNetworks/subnets', variables('adVNet'), 'default')", parent: "variables('adVNet')" }, { "type": "'Microsoft.Storage/storageAccounts'", "name": "variables('storageAccountName')", resourceId: "resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))", parent: undefined }, { "type": "'Microsoft.Sql/servers'", "name": "concat(variables('targetServerName'))", resourceId: "resourceId('Microsoft.Sql/servers', concat(variables('targetServerName')))", parent: undefined }, { "type": "'Microsoft.Sql/servers/databases'", "name": "variables('databaseName')", resourceId: "resourceId('Microsoft.Sql/servers/databases', concat(variables('targetServerName')), variables('databaseName'))", parent: "concat(variables('targetServerName'))" }, { "type": "'Microsoft.Sql/servers/databases/extensions'", "name": "'Import'", resourceId: "resourceId('Microsoft.Sql/servers/databases/extensions', concat(variables('targetServerName')), variables('databaseName'), 'Import')", parent: "variables('databaseName')" }, { "type": "'Microsoft.Sql/servers/firewallrules'", "name": "'AllowAllWindowsAzureIps'", resourceId: "resourceId('Microsoft.Sql/servers/firewallrules', concat(variables('targetServerName')), 'AllowAllWindowsAzureIps')", parent: "concat(variables('targetServerName'))" } ]; assert.deepStrictEqual(actual, expected); }); }); });
the_stack
export function create(args?: string[], config?: { phantomPath?: string, shimPath?: string, logger?: { info?: winstonLeveledLogMethod, debug?: winstonLeveledLogMethod, error?: winstonLeveledLogMethod, warn?: winstonLeveledLogMethod, }, logLevel?: 'debug' | 'info' | 'warn' | 'error', }): Promise<PhantomJS>; export interface winstonLeveledLogMethod { (message: string, callback: (...args: any[]) => void): any; (message: string, meta: any, callback: (...args: any[]) => void): any; (message: string, ...meta: any[]): any; (infoObject: any): any; } export interface PhantomJS { callback(fn: (pageNum: number, numPages: number) => string): IPhantomCallback; createPage(): Promise<WebPage>; exit(returnValue?: number): void; } export interface WebPage { open(url: string): Promise<string>; open(url: string, settings: IOpenWebPageSettings): Promise<string>; on(event: 'onResourceRequested', runOnPhantom: false, listener: (requestData: IRequestData, networkRequest: { abort: () => void, changeUrl: (newUrl: string) => void, setHeader: (key: string, value: string) => void }) => void): Promise<{ pageId: string }>; on(event: 'onResourceRequested', listener: (requestData: IRequestData, networkRequest: { abort: () => void, changeUrl: (newUrl: string) => void, setHeader: (key: string, value: string) => void }) => void): Promise<{ pageId: string }>; on(event: 'onLoadFinished', runOnPhantom: false, listener: (status: 'success' | 'fail') => void): Promise<{ pageId: string }>; on(event: 'onLoadFinished', listener: (status: 'success' | 'fail') => void): Promise<{ pageId: string }>; on(event: 'onAlert', runOnPhantom: false, listener: (msg: string) => void): Promise<{ pageId: string }>; on(event: 'onAlert', listener: (msg: string) => void): Promise<{ pageId: string }>; on(event: 'onCallback', runOnPhantom: false, listener: (data: any) => void): Promise<{ pageId: string }>; on(event: 'onCallback', listener: (data: any) => void): Promise<{ pageId: string }>; on(event: 'onClosing', runOnPhantom: false, listener: (closingPage: any) => void): Promise<{ pageId: string }>; on(event: 'onClosing', listener: (closingPage: any) => void): Promise<{ pageId: string }>; on(event: 'onConfirm', runOnPhantom: false, listener: (msg: string) => void): Promise<{ pageId: string }>; on(event: 'onConfirm', listener: (msg: string) => void): Promise<{ pageId: string }>; on(event: 'onConsoleMessage', runOnPhantom: false, listener: (msg: string, lineNum: number, sourceId: string) => void): Promise<{ pageId: string }>; on(event: 'onConsoleMessage', listener: (msg: string, lineNum: number, sourceId: string) => void): Promise<{ pageId: string }>; on(event: 'onError', runOnPhantom: false, listener: (msg: string, trace: { file: string, line: string, function: string }[]) => void): Promise<{ pageId: string }>; on(event: 'onError', listener: (msg: string, trace: { file: string, line: string, function: string }[]) => void): Promise<{ pageId: string }>; on(event: 'onFilePicker', runOnPhantom: false, listener: (oldFile: any) => void): Promise<{ pageId: string }>; on(event: 'onFilePicker', listener: (oldFile: any) => void): Promise<{ pageId: string }>; on(event: 'onInitialized', runOnPhantom: false, listener: () => void): Promise<{ pageId: string }>; on(event: 'onInitialized', listener: () => void): Promise<{ pageId: string }>; on(event: 'onLoadStarted', runOnPhantom: false, listener: () => void): Promise<{ pageId: string }>; on(event: 'onLoadStarted', listener: () => void): Promise<{ pageId: string }>; on(event: 'onNavigationRequested', runOnPhantom: false, listener: (url: string, type: 'Undefined' | 'LinkClicked' | 'FormSubmitted' | 'BackOrForward' | 'Reload' | 'FormResubmitted' | 'Other', willNavigate: boolean, main: boolean) => void): Promise<{ pageId: string }>; on(event: 'onNavigationRequested', listener: (url: string, type: 'Undefined' | 'LinkClicked' | 'FormSubmitted' | 'BackOrForward' | 'Reload' | 'FormResubmitted' | 'Other', willNavigate: boolean, main: boolean) => void): Promise<{ pageId: string }>; on(event: 'onPageCreated', runOnPhantom: false, listener: (newPage: any) => void): Promise<{ pageId: string }>; on(event: 'onPageCreated', listener: (newPage: any) => void): Promise<{ pageId: string }>; on(event: 'onPrompt', runOnPhantom: false, listener: (msg: string, defaultVal: string) => void): Promise<{ pageId: string }>; on(event: 'onPrompt', listener: (msg: string, defaultVal: string) => void): Promise<{ pageId: string }>; on(event: 'onResourceError', runOnPhantom: false, listener: (resourceError: { id: string, url: string, errorCode: number, errorString: string }) => void): Promise<{ pageId: string }>; on(event: 'onResourceError', listener: (resourceError: { id: string, url: string, errorCode: number, errorString: string }) => void): Promise<{ pageId: string }>; on(event: 'onResourceReceived', runOnPhantom: false, listener: (response: IResponse) => void): Promise<{ pageId: string }>; on(event: 'onResourceReceived', listener: (response: IResponse) => void): Promise<{ pageId: string }>; on(event: 'onResourceTimeout', runOnPhantom: false, listener: (request: IRequestData & { errorCode: number, errorString: string }) => void): Promise<{ pageId: string }>; on(event: 'onResourceTimeout', listener: (request: IRequestData & { errorCode: number, errorString: string }) => void): Promise<{ pageId: string }>; on(event: 'onUrlChanged', runOnPhantom: false, listener: (targetUrl: string) => void): Promise<{ pageId: string }>; on(event: 'onUrlChanged', listener: (targetUrl: string) => void): Promise<{ pageId: string }>; off(event: 'onResourceRequested' | 'onLoadFinished' | 'onAlert' | 'onCallback' | 'onClosing' | 'onConfirm' | 'onConsoleMessage' | 'onError' | 'onFilePicker' | 'onInitialized' | 'onLoadStarted' | 'onNavigationRequested' | 'onPageCreated' | 'onPrompt' | 'onResourceError' | 'onResourceReceived' | 'onResourceTimeout' | 'onUrlChanged'): Promise<{ pageId: string }>; close(): Promise<void>; evaluate<R>(callback: () => R): Promise<R>; evaluate<T, R>(callback: (arg: T) => R, arg: T): Promise<R>; evaluate<T1, T2, R>(callback: (arg1: T1, arg2: T2) => R, arg1: T1, arg2: T2): Promise<R>; evaluate<T1, T2, T3, R>(callback: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: T2, arg3: T3): Promise<R>; evaluate<R>(callback: (...args: any[]) => R, ...args: any[]): Promise<R>; includeJs(url: string): Promise<void>; injectJs(filename: string): Promise<boolean>; sendEvent(mouseEventType: string, mouseX?: number, mouseY?: number, button?: string): Promise<void>; sendEvent(keyboardEventType: string, key: string, null1?: void, null2?: void, modifier?: number): Promise<void>; render(filename: string): Promise<void>; render(filename: string, options?: { format?: string; quality?: string; }): Promise<void>; renderBase64(type: string): Promise<string>; setContent(html: string, url: string): Promise<string>; property(key: 'content' | 'plainText' | 'focusedFrameName' | 'frameContent' | 'frameName' | 'framePlainText' | 'frameTitle' | 'libraryPath' | 'offlineStoragePath' | 'title' | 'url' | 'windowName'): Promise<string>; property(key: 'framesName' | 'pagesWindowName' | 'pages'): Promise<string[]>; property(key: 'canGoBack' | 'canGoForward' | 'navigationLocked' | 'ownsPages'): Promise<boolean>; property(key: 'framesCount' | 'offlineStorageQuota' | 'zoomFactor'): Promise<number>; property(key: 'clipRect'): Promise<{ top: number, left: number, width: number, height: number }>; property(key: 'cookies'): Promise<ICookie[]>; property(key: 'customHeaders'): Promise<{ [key: string]: string }>; property(key: 'paperSize'): Promise<IPaperSizeOptions>; property(key: 'scrollPosition'): Promise<{ top: number, left: number }>; property(key: 'viewportSize'): Promise<{ width: number, height: number }>; property<T>(key: string): Promise<T>; property<T>(key: string, value: T): Promise<void>; setting(key: 'javascriptEnabled' | 'loadImages' | 'localToRemoteUrlAccessEnabled' | 'XSSAuditingEnabled' | 'webSecurityEnabled'): Promise<boolean>; setting(key: 'userAgent' | 'userName' | 'password'): Promise<string>; setting(key: 'resourceTimeout'): Promise<number>; setting<T>(key: string): Promise<T>; setting<T>(key: string, value: T): Promise<T>; addCookie(cookie: ICookie): Promise<boolean>; deleteCookie(cookieName: string): Promise<boolean>; clearCookies(): Promise<void>; } export interface ICookie { name: string, value: string, domain?: string, path: string, httponly?: boolean, secure?: boolean, expires?: string } export interface IPaperSizeOptions { width?: string; height?: string; format?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid'; orientation?: 'portrait' | 'landscape'; margin?: string | { top?: string; left?: string; bottom?: string; right?: string; }; header?: { height: string, contents: IPhantomCallback }; footer?: { height: string; contents: IPhantomCallback }; } export interface IOpenWebPageSettings { operation?: 'GET' | 'POST' | 'HEAD' | 'DELETE' | 'PUT' | string; encoding?: 'utf8' | string; headers?: { [s: string]: string }; data?: string; } /** * The phantom.callback object */ export interface IPhantomCallback { transform: true; target: Function; method: 'callback'; parent: 'phantom' } export interface IResponse { id: string; url: string; time: Date; headers: { name: string, value: string }[]; bodySize: number; contentType: string; redirectURL: string; stage: 'start' | 'end'; status: number; statusText: string; } export interface IRequestData { id: number; method: string; url: string; time: Date; headers: { name: string, value: string }[]; }
the_stack
import { fromBase64, fromHex } from "@cosmjs/encoding"; import { Coin, IndexedTx, Msg, PubKey, StdSignature } from "@cosmjs/sdk38"; import { Address, Algorithm, SendTransaction, TokenTicker } from "@iov/bcp"; import { decodeAmount, decodeFullSignature, decodePubkey, decodeSignature, parseFee, parseMsg, parseSignedTx, parseTxsResponseSigned, parseTxsResponseUnsigned, parseUnsignedTx, } from "./decode"; import * as testdata from "./testdata.spec"; import cosmoshub from "./testdata/cosmoshub.json"; import { BankToken } from "./types"; describe("decode", () => { const defaultPubkey = { algo: Algorithm.Secp256k1, data: fromBase64("AtQaCqFnshaZQp6rIkvAPyzThvCvXSDO+9AzbxVErqJP"), }; const defaultSignature = fromBase64( "1nUcIH0CLT0/nQ0mBTDrT6kMG20NY/PsH7P2gc4bpYNGLEYjBmdWevXUJouSE/9A/60QG9cYeqyTe5kFDeIPxQ==", ); const defaultFullSignature = { nonce: testdata.nonce, pubkey: defaultPubkey, signature: defaultSignature, }; const defaultAmount = { fractionalDigits: 6, quantity: "11657995", tokenTicker: "ATOM" as TokenTicker, }; const defaultMemo = "Best greetings"; const defaultSendTransaction: SendTransaction = { kind: "bcp/send", chainId: testdata.chainId, sender: "cosmos1h806c7khnvmjlywdrkdgk2vrayy2mmvf9rxk2r" as Address, recipient: "cosmos1z7g5w84ynmjyg0kqpahdjqpj7yq34v3suckp0e" as Address, amount: defaultAmount, memo: defaultMemo, }; const defaultFee = { tokens: { fractionalDigits: 6, quantity: "5000", tokenTicker: "ATOM" as TokenTicker, }, gasLimit: "200000", }; const defaultTokens: readonly BankToken[] = [ { fractionalDigits: 6, ticker: "ATOM", denom: "uatom", }, ]; describe("decodePubkey", () => { it("works for secp256k1", () => { const pubkey: PubKey = { type: "tendermint/PubKeySecp256k1", value: "AtQaCqFnshaZQp6rIkvAPyzThvCvXSDO+9AzbxVErqJP", }; expect(decodePubkey(pubkey)).toEqual(defaultPubkey); }); it("works for ed25519", () => { const pubkey: PubKey = { type: "tendermint/PubKeyEd25519", value: "s69CnMgLTpuRyEfecjws3mWssBrOICUx8C2O1DkKSto=", }; expect(decodePubkey(pubkey)).toEqual({ algo: Algorithm.Ed25519, data: fromHex("b3af429cc80b4e9b91c847de723c2cde65acb01ace202531f02d8ed4390a4ada"), }); }); it("throws for unsupported types", () => { // https://github.com/tendermint/tendermint/blob/v0.33.0/crypto/sr25519/codec.go#L12 const pubkey: PubKey = { type: "tendermint/PubKeySr25519", value: "N4FJNPE5r/Twz55kO1QEIxyaGF5/HTXH6WgLQJWsy1o=", }; expect(() => decodePubkey(pubkey)).toThrowError(/unsupported pubkey type/i); }); }); describe("decodeSignature", () => { it("works", () => { const signature = "1nUcIH0CLT0/nQ0mBTDrT6kMG20NY/PsH7P2gc4bpYNGLEYjBmdWevXUJouSE/9A/60QG9cYeqyTe5kFDeIPxQ=="; expect(decodeSignature(signature)).toEqual(defaultSignature); }); }); describe("decodeFullSignature", () => { it("works", () => { const fullSignature: StdSignature = { pub_key: { type: "tendermint/PubKeySecp256k1", value: "AtQaCqFnshaZQp6rIkvAPyzThvCvXSDO+9AzbxVErqJP", }, signature: "1nUcIH0CLT0/nQ0mBTDrT6kMG20NY/PsH7P2gc4bpYNGLEYjBmdWevXUJouSE/9A/60QG9cYeqyTe5kFDeIPxQ==", }; expect(decodeFullSignature(fullSignature, testdata.nonce)).toEqual(defaultFullSignature); }); }); describe("decodeAmount", () => { it("works", () => { const amount: Coin = { denom: "uatom", amount: "11657995", }; expect(decodeAmount(defaultTokens, amount)).toEqual(defaultAmount); }); }); describe("parseMsg", () => { it("works for bank send transaction", () => { const msg: Msg = { type: "cosmos-sdk/MsgSend", value: { from_address: "cosmos1h806c7khnvmjlywdrkdgk2vrayy2mmvf9rxk2r", to_address: "cosmos1z7g5w84ynmjyg0kqpahdjqpj7yq34v3suckp0e", amount: [ { denom: "uatom", amount: "11657995", }, ], }, }; expect(parseMsg(msg, defaultMemo, testdata.chainId, defaultTokens)).toEqual(defaultSendTransaction); }); }); describe("parseFee", () => { it("works", () => { const fee = { amount: [ { denom: "uatom", amount: "5000", }, ], gas: "200000", }; expect(parseFee(fee, defaultTokens)).toEqual(defaultFee); }); }); describe("parseUnsignedTx", () => { it("works for bank send transaction", () => { expect(parseUnsignedTx(cosmoshub.tx.value, testdata.chainId, defaultTokens)).toEqual( testdata.sendTxJson, ); }); }); describe("parseSignedTx", () => { it("works", () => { expect(parseSignedTx(cosmoshub.tx.value, testdata.chainId, testdata.nonce, defaultTokens)).toEqual( testdata.signedTxJson, ); }); }); describe("parseTxsResponseUnsigned", () => { it("works", () => { const currentHeight = 2923; const txsResponse: IndexedTx = { height: 2823, hash: testdata.txId, code: 0, rawLog: '[{"msg_index":0,"success":true,"log":""}]', logs: [], tx: cosmoshub.tx, timestamp: "2020-02-14T11:35:41Z", }; const expected = { transaction: testdata.sendTxJson, height: 2823, confirmations: 101, transactionId: testdata.txId, log: '[{"msg_index":0,"success":true,"log":""}]', }; expect(parseTxsResponseUnsigned(testdata.chainId, currentHeight, txsResponse, defaultTokens)).toEqual( expected, ); }); }); describe("parseTxsResponseSigned", () => { it("works", () => { const currentHeight = 2923; const txsResponse: IndexedTx = { height: 2823, hash: testdata.txId, code: 0, rawLog: '[{"msg_index":0,"success":true,"log":""}]', logs: [], tx: cosmoshub.tx, timestamp: "2020-02-14T11:35:41Z", }; const expected = { ...testdata.signedTxJson, height: 2823, confirmations: 101, transactionId: testdata.txId, log: '[{"msg_index":0,"success":true,"log":""}]', }; expect( parseTxsResponseSigned(testdata.chainId, currentHeight, testdata.nonce, txsResponse, defaultTokens), ).toEqual(expected); }); }); }); /* Some output from sample rest queries: $ wasmcli tx send $(wasmcli keys show validator -a) $(wasmcli keys show fred -a) 98765stake -y { "height": "4", "txhash": "8A4613D62884EF8BB9BCCDDA3833D560701908BF17FE82A570EECCBACEF94A91", "raw_log": "[{\"msg_index\":0,\"log\":\"\",\"events\":[{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"send\"},{\"key\":\"sender\",\"value\":\"cosmos16qu479grzwanyzav6xvtzncgdjkwhqw7vy2pje\"},{\"key\":\"module\",\"value\":\"bank\"}]},{\"type\":\"transfer\",\"attributes\":[{\"key\":\"recipient\",\"value\":\"cosmos1ltkhnmdcqemmd2tkhnx7qx66tq7e0wykw2j85k\"},{\"key\":\"amount\",\"value\":\"98765stake\"}]}]}]", "logs": [ { "msg_index": 0, "log": "", "events": [ { "type": "message", "attributes": [ { "key": "action", "value": "send" }, { "key": "sender", "value": "cosmos16qu479grzwanyzav6xvtzncgdjkwhqw7vy2pje" }, { "key": "module", "value": "bank" } ] }, { "type": "transfer", "attributes": [ { "key": "recipient", "value": "cosmos1ltkhnmdcqemmd2tkhnx7qx66tq7e0wykw2j85k" }, { "key": "amount", "value": "98765stake" } ] } ] } ], "gas_wanted": "200000", "gas_used": "53254" } $ wasmcli query tx 8A4613D62884EF8BB9BCCDDA3833D560701908BF17FE82A570EECCBACEF94A91 { "height": "4", "txhash": "8A4613D62884EF8BB9BCCDDA3833D560701908BF17FE82A570EECCBACEF94A91", "raw_log": "[{\"msg_index\":0,\"log\":\"\",\"events\":[{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"send\"},{\"key\":\"sender\",\"value\":\"cosmos16qu479grzwanyzav6xvtzncgdjkwhqw7vy2pje\"},{\"key\":\"module\",\"value\":\"bank\"}]},{\"type\":\"transfer\",\"attributes\":[{\"key\":\"recipient\",\"value\":\"cosmos1ltkhnmdcqemmd2tkhnx7qx66tq7e0wykw2j85k\"},{\"key\":\"amount\",\"value\":\"98765stake\"}]}]}]", "logs": [ { "msg_index": 0, "log": "", "events": [ { "type": "message", "attributes": [ { "key": "action", "value": "send" }, { "key": "sender", "value": "cosmos16qu479grzwanyzav6xvtzncgdjkwhqw7vy2pje" }, { "key": "module", "value": "bank" } ] }, { "type": "transfer", "attributes": [ { "key": "recipient", "value": "cosmos1ltkhnmdcqemmd2tkhnx7qx66tq7e0wykw2j85k" }, { "key": "amount", "value": "98765stake" } ] } ] } ], "gas_wanted": "200000", "gas_used": "53254", "tx": { "type": "cosmos-sdk/StdTx", "value": { "msg": [ { "type": "cosmos-sdk/MsgSend", "value": { "from_address": "cosmos16qu479grzwanyzav6xvtzncgdjkwhqw7vy2pje", "to_address": "cosmos1ltkhnmdcqemmd2tkhnx7qx66tq7e0wykw2j85k", "amount": [ { "denom": "stake", "amount": "98765" } ] } } ], "fee": { "amount": [], "gas": "200000" }, "signatures": [ { "pub_key": { "type": "tendermint/PubKeySecp256k1", "value": "A11L8EitFnA6YsZ2QSnbMNmK+qI2kxyevDtSfhPqOwcp" }, "signature": "qCeKoqZeaL0LThKrUXHLgu72jwTiF+DseSBjcKHtcONE0kIdybwYJpuYg3Jj71hmfync+daHNdqgJlPRma0pPA==" } ], "memo": "" } }, "timestamp": "2020-02-03T17:06:58Z" } $ wasmcli query account $(wasmcli keys show fred -a) { "type": "cosmos-sdk/Account", "value": { "address": "cosmos1ltkhnmdcqemmd2tkhnx7qx66tq7e0wykw2j85k", "coins": [ { "denom": "stake", "amount": "98765" } ], "public_key": "", "account_number": 7, "sequence": 0 } } $ wasmcli query account $(wasmcli keys show validator -a) { "type": "cosmos-sdk/Account", "value": { "address": "cosmos16qu479grzwanyzav6xvtzncgdjkwhqw7vy2pje", "coins": [ { "denom": "stake", "amount": "899901235" }, { "denom": "validatortoken", "amount": "1000000000" } ], "public_key": "cosmospub1addwnpepqdw5huzg45t8qwnzcemyz2wmxrvc474zx6f3e84u8df8uyl28vrjjnp9v4p", "account_number": 3, "sequence": 2 } } */
the_stack
import {NodePath} from '@babel/traverse'; import * as babel from '@babel/types'; import {VisitorOption} from './estraverse-shim'; export type VisitResult = VisitorOption|null|undefined|void; export type VisitorCallback<N extends babel.Node> = (node: N, parent: babel.Node|undefined|null, path: NodePath<N>) => VisitResult; export interface Visitor { readonly enter?: VisitorCallback<babel.Node>; readonly leave?: VisitorCallback<babel.Node>; readonly enterIdentifier?: VisitorCallback<babel.Identifier>; readonly leaveIdentifier?: VisitorCallback<babel.Identifier>; readonly enterLiteral?: VisitorCallback<babel.Literal>; readonly leaveLiteral?: VisitorCallback<babel.Literal>; readonly enterProgram?: VisitorCallback<babel.Program>; readonly leaveProgram?: VisitorCallback<babel.Program>; readonly enterExpressionStatement?: VisitorCallback<babel.ExpressionStatement>; readonly leaveExpressionStatement?: VisitorCallback<babel.ExpressionStatement>; readonly enterBlockStatement?: VisitorCallback<babel.BlockStatement>; readonly leaveBlockStatement?: VisitorCallback<babel.BlockStatement>; readonly enterEmptyStatement?: VisitorCallback<babel.EmptyStatement>; readonly leaveEmptyStatement?: VisitorCallback<babel.EmptyStatement>; readonly enterDebuggerStatement?: VisitorCallback<babel.DebuggerStatement>; readonly leaveDebuggerStatement?: VisitorCallback<babel.DebuggerStatement>; readonly enterWithStatement?: VisitorCallback<babel.WithStatement>; readonly leaveWithStatement?: VisitorCallback<babel.WithStatement>; readonly enterReturnStatement?: VisitorCallback<babel.ReturnStatement>; readonly leaveReturnStatement?: VisitorCallback<babel.ReturnStatement>; readonly enterLabeledStatement?: VisitorCallback<babel.LabeledStatement>; readonly leaveLabeledStatement?: VisitorCallback<babel.LabeledStatement>; readonly enterBreakStatement?: VisitorCallback<babel.BreakStatement>; readonly leaveBreakStatement?: VisitorCallback<babel.BreakStatement>; readonly enterContinueStatement?: VisitorCallback<babel.ContinueStatement>; readonly leaveContinueStatement?: VisitorCallback<babel.ContinueStatement>; readonly enterIfStatement?: VisitorCallback<babel.IfStatement>; readonly leaveIfStatement?: VisitorCallback<babel.IfStatement>; readonly enterSwitchStatement?: VisitorCallback<babel.SwitchStatement>; readonly leaveSwitchStatement?: VisitorCallback<babel.SwitchStatement>; readonly enterSwitchCase?: VisitorCallback<babel.SwitchCase>; readonly leaveSwitchCase?: VisitorCallback<babel.SwitchCase>; readonly enterThrowStatement?: VisitorCallback<babel.ThrowStatement>; readonly leaveThrowStatement?: VisitorCallback<babel.ThrowStatement>; readonly enterTryStatement?: VisitorCallback<babel.TryStatement>; readonly leaveTryStatement?: VisitorCallback<babel.TryStatement>; readonly enterCatchClause?: VisitorCallback<babel.CatchClause>; readonly leaveCatchClause?: VisitorCallback<babel.CatchClause>; readonly enterWhileStatement?: VisitorCallback<babel.WhileStatement>; readonly leaveWhileStatement?: VisitorCallback<babel.WhileStatement>; readonly enterDoWhileStatement?: VisitorCallback<babel.DoWhileStatement>; readonly leaveDoWhileStatement?: VisitorCallback<babel.DoWhileStatement>; readonly enterForStatement?: VisitorCallback<babel.ForStatement>; readonly leaveForStatement?: VisitorCallback<babel.ForStatement>; readonly enterForInStatement?: VisitorCallback<babel.ForInStatement>; readonly leaveForInStatement?: VisitorCallback<babel.ForInStatement>; readonly enterForOfStatement?: VisitorCallback<babel.ForOfStatement>; readonly leaveForOfStatement?: VisitorCallback<babel.ForOfStatement>; readonly enterFunctionDeclaration?: VisitorCallback<babel.FunctionDeclaration>; readonly leaveFunctionDeclaration?: VisitorCallback<babel.FunctionDeclaration>; readonly enterVariableDeclaration?: VisitorCallback<babel.VariableDeclaration>; readonly leaveVariableDeclaration?: VisitorCallback<babel.VariableDeclaration>; readonly enterVariableDeclarator?: VisitorCallback<babel.VariableDeclarator>; readonly leaveVariableDeclarator?: VisitorCallback<babel.VariableDeclarator>; readonly enterThisExpression?: VisitorCallback<babel.ThisExpression>; readonly leaveThisExpression?: VisitorCallback<babel.ThisExpression>; readonly enterArrayExpression?: VisitorCallback<babel.ArrayExpression>; readonly leaveArrayExpression?: VisitorCallback<babel.ArrayExpression>; readonly enterObjectExpression?: VisitorCallback<babel.ObjectExpression>; readonly leaveObjectExpression?: VisitorCallback<babel.ObjectExpression>; readonly enterProperty?: VisitorCallback<babel.Property>; readonly leaveProperty?: VisitorCallback<babel.Property>; readonly enterFunctionExpression?: VisitorCallback<babel.FunctionExpression>; readonly leaveFunctionExpression?: VisitorCallback<babel.FunctionExpression>; readonly enterArrowFunctionExpression?: VisitorCallback<babel.ArrowFunctionExpression>; readonly leaveArrowFunctionExpression?: VisitorCallback<babel.ArrowFunctionExpression>; readonly enterYieldExpression?: VisitorCallback<babel.YieldExpression>; readonly leaveYieldExpression?: VisitorCallback<babel.YieldExpression>; readonly enterSuper?: VisitorCallback<babel.Super>; readonly leaveSuper?: VisitorCallback<babel.Super>; readonly enterUnaryExpression?: VisitorCallback<babel.UnaryExpression>; readonly leaveUnaryExpression?: VisitorCallback<babel.UnaryExpression>; readonly enterUpdateExpression?: VisitorCallback<babel.UpdateExpression>; readonly leaveUpdateExpression?: VisitorCallback<babel.UpdateExpression>; readonly enterBinaryExpression?: VisitorCallback<babel.BinaryExpression>; readonly leaveBinaryExpression?: VisitorCallback<babel.BinaryExpression>; readonly enterAssignmentExpression?: VisitorCallback<babel.AssignmentExpression>; readonly leaveAssignmentExpression?: VisitorCallback<babel.AssignmentExpression>; readonly enterLogicalExpression?: VisitorCallback<babel.LogicalExpression>; readonly leaveLogicalExpression?: VisitorCallback<babel.LogicalExpression>; readonly enterMemberExpression?: VisitorCallback<babel.MemberExpression>; readonly leaveMemberExpression?: VisitorCallback<babel.MemberExpression>; readonly enterConditionalExpression?: VisitorCallback<babel.ConditionalExpression>; readonly leaveConditionalExpression?: VisitorCallback<babel.ConditionalExpression>; readonly enterCallExpression?: VisitorCallback<babel.CallExpression>; readonly leaveCallExpression?: VisitorCallback<babel.CallExpression>; readonly enterNewExpression?: VisitorCallback<babel.NewExpression>; readonly leaveNewExpression?: VisitorCallback<babel.NewExpression>; readonly enterSequenceExpression?: VisitorCallback<babel.SequenceExpression>; readonly leaveSequenceExpression?: VisitorCallback<babel.SequenceExpression>; readonly enterTemplateLiteral?: VisitorCallback<babel.TemplateLiteral>; readonly leaveTemplateLiteral?: VisitorCallback<babel.TemplateLiteral>; readonly enterTaggedTemplateExpression?: VisitorCallback<babel.TaggedTemplateExpression>; readonly leaveTaggedTemplateExpression?: VisitorCallback<babel.TaggedTemplateExpression>; readonly enterTemplateElement?: VisitorCallback<babel.TemplateElement>; readonly leaveTemplateElement?: VisitorCallback<babel.TemplateElement>; readonly enterSpreadElement?: VisitorCallback<babel.SpreadElement>; readonly leaveSpreadElement?: VisitorCallback<babel.SpreadElement>; readonly enterPattern?: VisitorCallback<babel.Pattern>; readonly leavePattern?: VisitorCallback<babel.Pattern>; readonly enterAssignmentProperty?: VisitorCallback<babel.AssignmentProperty>; readonly leaveAssignmentProperty?: VisitorCallback<babel.AssignmentProperty>; readonly enterObjectPattern?: VisitorCallback<babel.ObjectPattern>; readonly leaveObjectPattern?: VisitorCallback<babel.ObjectPattern>; readonly enterObjectMethod?: VisitorCallback<babel.ObjectMethod>; readonly leaveObjectMethod?: VisitorCallback<babel.ObjectMethod>; readonly enterObjectProperty?: VisitorCallback<babel.ObjectProperty>; readonly leaveObjectProperty?: VisitorCallback<babel.ObjectProperty>; readonly enterArrayPattern?: VisitorCallback<babel.ArrayPattern>; readonly leaveArrayPattern?: VisitorCallback<babel.ArrayPattern>; readonly enterRestElement?: VisitorCallback<babel.RestElement>; readonly leaveRestElement?: VisitorCallback<babel.RestElement>; readonly enterAssignmentPattern?: VisitorCallback<babel.AssignmentPattern>; readonly leaveAssignmentPattern?: VisitorCallback<babel.AssignmentPattern>; readonly enterMethod?: VisitorCallback<babel.Method>; readonly leaveMethod?: VisitorCallback<babel.Method>; readonly enterClassMethod?: VisitorCallback<babel.ClassMethod>; readonly leaveClassMethod?: VisitorCallback<babel.ClassMethod>; readonly enterClassDeclaration?: VisitorCallback<babel.ClassDeclaration>; readonly leaveClassDeclaration?: VisitorCallback<babel.ClassDeclaration>; readonly enterClassExpression?: VisitorCallback<babel.ClassExpression>; readonly leaveClassExpression?: VisitorCallback<babel.ClassExpression>; readonly enterMetaProperty?: VisitorCallback<babel.MetaProperty>; readonly leaveMetaProperty?: VisitorCallback<babel.MetaProperty>; readonly enterModuleDeclaration?: VisitorCallback<babel.ModuleDeclaration>; readonly leaveModuleDeclaration?: VisitorCallback<babel.ModuleDeclaration>; readonly enterModuleSpecifier?: VisitorCallback<babel.ModuleSpecifier>; readonly leaveModuleSpecifier?: VisitorCallback<babel.ModuleSpecifier>; readonly enterImportDeclaration?: VisitorCallback<babel.ImportDeclaration>; readonly leaveImportDeclaration?: VisitorCallback<babel.ImportDeclaration>; readonly enterImportSpecifier?: VisitorCallback<babel.ImportSpecifier>; readonly leaveImportSpecifier?: VisitorCallback<babel.ImportSpecifier>; readonly enterImportDefaultSpecifier?: VisitorCallback<babel.ImportDefaultSpecifier>; readonly leaveImportDefaultSpecifier?: VisitorCallback<babel.ImportDefaultSpecifier>; readonly enterImportNamespaceSpecifier?: VisitorCallback<babel.ImportNamespaceSpecifier>; readonly leaveImportNamespaceSpecifier?: VisitorCallback<babel.ImportNamespaceSpecifier>; readonly enterExportNamedDeclaration?: VisitorCallback<babel.ExportNamedDeclaration>; readonly leaveExportNamedDeclaration?: VisitorCallback<babel.ExportNamedDeclaration>; readonly enterExportSpecifier?: VisitorCallback<babel.ExportSpecifier>; readonly leaveExportSpecifier?: VisitorCallback<babel.ExportSpecifier>; readonly enterExportDefaultDeclaration?: VisitorCallback<babel.ExportDefaultDeclaration>; readonly leaveExportDefaultDeclaration?: VisitorCallback<babel.ExportDefaultDeclaration>; readonly enterExportAllDeclaration?: VisitorCallback<babel.ExportAllDeclaration>; readonly leaveExportAllDeclaration?: VisitorCallback<babel.ExportAllDeclaration>; }
the_stack
import { addHook } from 'pirates'; import type { ArrayExpression, ArrayPattern, AssignmentPattern, BinaryExpression, CallExpression, Expression, Identifier, Literal, MemberExpression, Node, ObjectExpression, ObjectPattern, Property, RestElement, SpreadElement, UnaryExpression } from 'estree'; // @ts-ignore import abstractSyntaxTree from 'abstract-syntax-tree'; import { inDebugMode } from '@deepkit/core'; import { escape, escapeHtml } from './utils'; import { voidElements } from './template'; const { parse, generate, replace } = abstractSyntaxTree; export function transform(code: string, filename: string) { if (inDebugMode()) return code; //for CommonJs its jsx_runtime_1.jsx, for ESM its _jsx. ESM is handled in loader.ts#transformSource if (code.indexOf('.jsx(') === -1 && code.indexOf('.jsxs(') === -1) return code; // console.log('optimize code for', filename, optimizeJSX(code)); return optimizeJSX(code); } addHook(transform, { exts: ['.js', '.tsx'] }); class NotSerializable { } export function parseCode(code: string) { return parse(code); } export function generateCode(ast: Node) { return generate(ast); } function serializeValue(node: Literal | UnaryExpression): any { if (node.type === 'Literal') { return node.value; } if (node.type === 'UnaryExpression' && node.argument?.type === 'Literal') { return node.argument.value; } return NotSerializable; } /** * Our strategy is to convert ObjectExpressions to a BinaryExpression that has basically like * * p1 + '=' + p1Value + ' ' + p2 + '=' + p2Value + ... * * concatExpressions() can then further optimise it down to one big literal (or several literals depending on where non-literals are used). */ function optimizeAttributes(jsxRuntime: string, node: ObjectExpression): any { const expressions: ConcatableType[] = []; for (const p of node.properties) { if (p.type === 'SpreadElement') return node; if (isPattern(p.value)) return node; const value = p.value.type === 'UnaryExpression' ? p.value.argument : p.value; if (expressions.length) { expressions.push(createEscapedLiteral(' ')); } if (p.key.type === 'Identifier') { expressions.push(createEscapedLiteral(p.key.name)); } else { expressions.push(p.key); } expressions.push(createEscapedLiteral('="')); if (value.type !== 'Literal' && !isPattern(value) && !isCreateElementCall(value) && !isEscapeCall(value) && !isHtmlCall(value)) { expressions.push(toSafeString(jsxRuntime, toEscapeAttributeCall(jsxRuntime, value))); } else { if (value.type === 'Literal') { expressions.push(createEscapedLiteral(value.value)); } else { expressions.push(value); } } expressions.push(createEscapedLiteral('"')); } if (expressions.length >= 2) return concatExpressions(jsxRuntime, expressions); return createEscapedLiteral(''); } function isPattern(e: Node): e is ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression { return e.type === 'ArrayPattern' || e.type === 'ObjectPattern' || e.type === 'AssignmentPattern' || e.type === 'RestElement' || e.type === 'MemberExpression'; } //jsx_runtime_1.jsx() function isCjsJSXCall(node: Node): boolean { if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression') { const expression = node.callee; return expression.property && expression.property.type === 'Identifier' && (expression.property.name === 'jsx' || expression.property?.name === 'jsxs'); } return false; } function unwrapCallExpression(node: Node): MemberExpression | Identifier | undefined { if (node.type === 'CallExpression' && node.callee.type === 'SequenceExpression' && node.callee.expressions[0] && node.callee.expressions[0].type === 'Literal' && node.callee.expressions[0].value === 0 && node.callee.expressions[1]) { if (node.callee.expressions[1].type === 'MemberExpression') return node.callee.expressions[1]; if (node.callee.expressions[1].type === 'Identifier') return node.callee.expressions[1]; } if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression') { return node.callee; } return; } //(0, jsx_runtime_1.jsx) function isAvoidedThisCjsJSXCall(node: Node): boolean { const expression = unwrapCallExpression(node); if (expression && expression.type === 'MemberExpression') { return !!expression.property && expression.property.type === 'Identifier' && (expression.property.name === 'jsx' || expression.property?.name === 'jsxs'); } return false; } function isESMJSXCall(node: Node): boolean { return node.type === 'CallExpression' && node.callee.type === 'Identifier' && (node.callee.name === '_jsx' || node.callee.name === '_jsxs'); } /** * We convert * * _jsx.createElement("div", { id: "123" }, void 0) * -> "<div id=\"123\"></div>" * * _jsx.createElement("div", { children: "Test" }, void 0) * -> "<div>Test</div>" * * _jsx.createElement("div", Object.assign({ id: "123" }, { children: "Test" }), void 0) * -> "<div id=\"123\">Test</div>" * * _jsx.createElement("div", Object.assign({ id: "123" }, { children: _jsx.createElement('b", { children: "strong' }, void 0) }), void 0); * -> "<div id=\"123\">" + "<b>strong</b>" + "</div>" */ function optimizeNode(node: Expression, root: boolean = true): Expression { if (node.type !== 'CallExpression') return node; if (node.callee.type !== 'MemberExpression') return node; if (node.callee.object.type !== 'Identifier') return node; const isCreateElementExpression = node.callee.property.type === 'Identifier' && node.callee.property?.name === 'createElement'; if (!isCreateElementExpression) return node; const jsxRuntime = node.callee.object.name; //if first argument is a Fragment, we optimise for that if (node.arguments[0].type === 'MemberExpression' && node.arguments[0].object.type === 'Identifier' && node.arguments[0].property.type === 'Identifier' && node.arguments[0].property.name === 'Fragment') { //we normalize Fragments (or all createElement(var)) to have as second parameter the attributes. //since Fragments don't have attributes, this is always an empty object, so we skip that const concat: Expression[] = []; let optimisedString: boolean = true; let strings: string[] = []; for (let i = 2; i < node.arguments.length; i++) { const a = node.arguments[i]; if (a && a.type !== 'SpreadElement') { const o = optimizeNode(a, false); concat.push(o); const staticString = extractStaticString(o); if (staticString !== noStaticValue) { strings.push(staticString); } else { optimisedString = false; } } } //all arguments are string literals, which can merge to one big string const result = optimisedString ? createEscapedLiteral(strings.join('')) : concatExpressions(jsxRuntime, concat); const safeString = getSafeString(result); if (safeString !== undefined) { if (root) return createRenderObjectWithEscapedChildren(safeString); return safeString; } if (root) return createRenderObjectWithEscapedChildren(result); return result; } //go deeper if possible for (let i = 2; i < node.arguments.length; i++) { const a = node.arguments[i]; if (a && a.type === 'CallExpression') { node.arguments[i] = optimizeNode(a, false); } } let tag: any = ''; //we only optimize attributes when we have createElement(string) if (node.arguments[0].type === 'Literal') { tag = node.arguments[0].value; const attributes = node.arguments[1]; if (isObjectAssignCall(attributes)) { //when we have here Object.assign still, then it includes a spread operator, which we can't optimise. return node; } else { if (node.arguments[1] && node.arguments[1].type === 'ObjectExpression') { const ori = node.arguments[1]; node.arguments[1] = optimizeAttributes(jsxRuntime, ori); if (ori === node.arguments[1]) { //we did not change the attributes to a better option, so we stop optimizing further. return node; } } } } //check if we can concatenate (+) arguments let canBeConcatenated = true; for (let i = 1; i < node.arguments.length; i++) { const a = node.arguments[i]; if (a && a.type !== 'SpreadElement' && !isConcatenatable(a)) { canBeConcatenated = false; break; } } if (canBeConcatenated) { const args = node.arguments as (Literal | CallExpression)[]; const attributes = args[1]; const concat: Expression[] = []; const closing = voidElements[tag] ? '/>' : '>'; if (tag) { if (attributes.type === 'Literal' && !attributes.value) { //no attributes concat.push(createEscapedLiteral('<' + tag + closing)); } else { concat.push(createEscapedLiteral('<' + tag + ' ')); concat.push(attributes); concat.push(createEscapedLiteral(closing)); } } for (let i = 2; i < node.arguments.length; i++) { let e = node.arguments[i]; if (e.type !== 'SpreadElement') { concat.push(e); } } if (tag && closing === '>') { concat.push(createEscapedLiteral('</' + tag + '>')); } if (concat.length === 0) { return node; } if (node.arguments[0].type !== 'Literal') { //for custom elements, we only merge its arguments if (node.arguments[2]) { node.arguments[2] = optimiseArguments(jsxRuntime, concat, false); node.arguments.splice(3); } //todo: convert to {render:, attributes:, children: } return node; } // //concatExpressions tries to convert everything to one big literal if possible // //alternatively returns an renderObject expression with array children. return optimiseArguments(jsxRuntime, concat, root); } return node; } function optimiseArguments(jsxRuntime: string, expressions: ConcatableType[], root: boolean): Expression { if (expressions.length === 0) throw new Error('No expression for optimise arguments'); if (expressions.length === 1) { const e = expressions[0]; const htmlArg = getHtmlCallArg(e); const value = htmlArg ? extractStaticString(htmlArg) : extractStaticString(e); if (value !== noStaticValue) { expressions[0] = toSafeString(jsxRuntime, createEscapedLiteral(value)); } } const result = expressions.length === 1 ? toOptimisedArrayExpression(expressions) : concatExpressions(jsxRuntime, expressions); const safeString = getSafeString(result); if (safeString !== undefined) { if (root) return createRenderObjectWithEscapedChildren(safeString); return safeString; } if (root) return createRenderObjectWithEscapedChildren(result); return result; } function concatExpressions(jsxRuntime: string, expressions: ConcatableType[]): ConcatableType { if (expressions.length < 2) { console.dir(expressions, { depth: null }); throw new Error('concatExpressions requires at least 2 expressions'); } const normalizedExpressions: ConcatableType[] = []; //todo: can this BinaryExpression check be entirely be removed? for (let e of expressions) { if (e.type === 'BinaryExpression' && !isOptimisedBinaryExpression(e)) { //check if its ours BinaryExpression from concatExpressions. If so do not merge. //we merge later at the end of the pipeline //unwrap existing binaryExpression to avoid brackets: a + (b + (c + d)) + e for (const a of extractBinaryExpressions(e)) { normalizedExpressions.push(a); } } else if (isOptimisedArrayExpression(e)) { for (const a of e.elements) { if (a.type === 'SpreadElement') continue; normalizedExpressions.push(a); } } else { normalizedExpressions.push(e); } } function mergeLiterals(expression: Expression[]): ConcatableType[] { const result: ConcatableType[] = []; let lastLiteral: Literal | undefined; //try to optimise static values together for (let e of expression) { if (e.type === 'Literal' && !(e as any).escape) { //we need to escape it e.value = escapeHtml(e.value); (e as any).escape = true; } const htmlArg = getHtmlCallArg(e); const value = htmlArg ? extractStaticString(htmlArg) : extractStaticString(e); if (value === noStaticValue) { lastLiteral = undefined; result.push(e); } else { if (lastLiteral) { lastLiteral.value += value; } else { lastLiteral = createEscapedLiteral(value); result.push(toSafeString(jsxRuntime, lastLiteral)); } } } return result; } let optimizedExpressions = mergeLiterals(normalizedExpressions); if (optimizedExpressions.length === 1) { return optimizedExpressions[0]; } const allExpressionsConcatable = optimizedExpressions.every(e => { return isOptimisedBinaryExpression(e) || isHtmlCall(e) || isSafeCall(e) || isEscapedLiteral(e) || getSafeString(e) !== undefined || isUserEscapeCall(e) || isOptimisedHtmlString(e); }); const lastStep: ConcatableType[] = []; for (let e of optimizedExpressions) { if (e.type === 'BinaryExpression') { //unwrap existing binaryExpression to avoid brackets: a + (b + (c + d)) + e for (const a of extractBinaryExpressions(e)) { lastStep.push(a); } } else { lastStep.push(e); } } optimizedExpressions = mergeLiterals(lastStep); // console.log('allExpressionsConcatable', allExpressionsConcatable); // console.dir(optimizedExpressions, { depth: null }); if (!allExpressionsConcatable) { //we can't optimise this as one big binary expression //we have to return it as array return toOptimisedArrayExpression(optimizedExpressions); } let lastBinaryExpression: OptimisedBinaryExpression | undefined; for (let i = 1; i < optimizedExpressions.length; i++) { lastBinaryExpression = { type: 'BinaryExpression', _optimised: true, left: lastBinaryExpression || normalizeLastStep(optimizedExpressions[0]), right: normalizeLastStep(optimizedExpressions[i]), operator: '+', }; } if (!lastBinaryExpression) throw new Error('Could not build binary expression'); return lastBinaryExpression; } function normalizeLastStep(e: Expression): Expression { const safeCallArg = getSafeCallArg(e); if (safeCallArg !== undefined) return safeCallArg; const safeString = getSafeString(e); if (safeString !== undefined) return safeString; const htmlCall = getHtmlCallArg(e); if (htmlCall !== undefined) return htmlCall; if (isUserEscapeCall(e) || isHtmlCall(e)) { //convert from `escape(e)` to `escape(e).htmlString` //and from `html(e)` to `html(e).htmlString` return { type: 'MemberExpression', object: e, computed: false, property: { type: 'Identifier', name: 'htmlString' } } as MemberExpression; } return e; } function toOptimisedArrayExpression(expressions: ConcatableType[]): ArrayExpression { const arrayExpression: OptimisedArrayExpression = { type: 'ArrayExpression', _optimised: true, elements: [], }; for (let e of expressions) { arrayExpression.elements.push(e); } return arrayExpression; } function createRenderObjectWithEscapedChildren(children?: Expression, render: Expression = { type: 'Identifier', name: 'undefined' }, attributes: Expression = { type: 'Identifier', name: 'undefined' }): Expression { const o: ObjectExpression = { type: 'ObjectExpression', properties: [ { type: 'Property', key: { type: 'Identifier', name: 'render' }, value: render, kind: 'init', computed: false, method: false, shorthand: false }, { type: 'Property', key: { type: 'Identifier', name: 'attributes' }, value: attributes, kind: 'init', computed: false, method: false, shorthand: false } ] }; if (children) { o.properties.push({ type: 'Property', key: { type: 'Identifier', name: 'childrenEscaped' }, value: children, kind: 'init', computed: false, method: false, shorthand: false }); } return o; } function isRenderObject(e: Node) { return e.type === 'ObjectExpression' && e.properties[0] && e.properties[0].type === 'Property' && e.properties[0].key.type === 'Identifier' && e.properties[0].key.name === 'render' ; } function isObjectAssignCall(e: Node) { return e.type === 'CallExpression' && e.callee.type === 'MemberExpression' && e.callee.object.type === 'Identifier' && e.callee.object.name === 'Object' && e.callee.property.type === 'Identifier' && e.callee.property.name === 'assign' ; } function createEscapedLiteral(v: string | number | boolean | null | RegExp | undefined): Literal { return { type: 'Literal', value: v, escape: true } as any; } function isEscapedLiteral(e: Node): boolean { return e.type === 'Literal' && (e as any).escape === true; } function isCreateElementCall(e: Node) { return e.type === 'CallExpression' && e.callee.type === 'MemberExpression' && e.callee.object.type === 'Identifier' && e.callee.property.type === 'Identifier' && e.callee.property.name === 'createElement'; } function isConcatenatable(e: Expression): boolean { return extractStaticString(e) !== undefined || e.type === 'Identifier'; } function toHtmlCall(jsxRuntime: string, expression: Expression): CallExpression { return { type: 'CallExpression', callee: { type: 'MemberExpression', object: { type: 'Identifier', name: jsxRuntime }, computed: false, optional: false, property: { type: 'Identifier', name: 'html' } }, optional: false, arguments: [expression] }; } // function toEscapeCall(jsxRuntime: string, expression: Expression): CallExpression { // return { // type: 'CallExpression', // callee: { // type: 'MemberExpression', // object: { type: 'Identifier', name: jsxRuntime }, // computed: false, // optional: false, // property: { type: 'Identifier', name: 'escape' } // }, // optional: false, // arguments: [expression] // }; // } function toEscapeAttributeCall(jsxRuntime: string, expression: Expression): CallExpression { return { type: 'CallExpression', callee: { type: 'MemberExpression', object: { type: 'Identifier', name: jsxRuntime }, computed: false, optional: false, property: { type: 'Identifier', name: 'escapeAttribute' } }, optional: false, arguments: [expression] }; } export const noStaticValue: unique symbol = Symbol(''); export function extractStaticString(e: Expression | SpreadElement): string | typeof noStaticValue { if (e.type === 'Literal') return '' + e.value; if (e.type === 'TemplateLiteral' && e.expressions.length === 0) { return e.quasis.map(v => v.value.cooked).join(''); } const safeString = getSafeString(e); if (safeString !== undefined) return extractStaticString(safeString); return noStaticValue; } function unwrapSpread(e: Expression | SpreadElement): Expression { return e.type === 'SpreadElement' ? e.argument : e; } function isHtmlCall(object: Expression | SpreadElement): boolean { return getHtmlCallArg(object) !== undefined; } function getHtmlCallArg(e: Expression | SpreadElement): Expression | undefined { const expression = unwrapCallExpression(e); if (!expression) return; if (e.type === 'CallExpression' && expression.type === 'MemberExpression' && expression.object.type === 'Identifier' && expression.object.name === '_jsx' && expression.property.type === 'Identifier' && expression.property.name === 'html' && e.arguments[0]) return unwrapSpread(e.arguments[0]); if (e.type === 'CallExpression' && expression.type === 'MemberExpression' && expression.object.type === 'Identifier' && expression.property.type === 'Identifier' && expression.property.name === 'html' && e.arguments[0]) return unwrapSpread(e.arguments[0]); if (e.type === 'CallExpression' && expression.type === 'Identifier' && expression.name === 'html' && e.arguments[0]) { return unwrapSpread(e.arguments[0]); } return; } function isSafeCall(object: Expression | SpreadElement): boolean { return getSafeCallArg(object) !== undefined; } function getSafeCallArg(e: Expression | SpreadElement): Expression | undefined { const expression = unwrapCallExpression(e); if (!expression) return; if (e.type === 'CallExpression' && expression.type === 'MemberExpression' && expression.object.type === 'Identifier' && expression.object.name === '_jsx' && expression.property.type === 'Identifier' && expression.property.name === 'safe' && e.arguments[0]) return unwrapSpread(e.arguments[0]); if (e.type === 'CallExpression' && expression.type === 'MemberExpression' && expression.object.type === 'Identifier' && expression.property.type === 'Identifier' && expression.property.name === 'safe' && e.arguments[0]) return unwrapSpread(e.arguments[0]); if (e.type === 'CallExpression' && expression.type === 'Identifier' && expression.name === 'safe' && e.arguments[0]) { return unwrapSpread(e.arguments[0]); } return; } function isChildren(e: Expression | SpreadElement): boolean { if (e.type === 'MemberExpression' && (e.object.type === 'Identifier' || e.object.type === 'ThisExpression') && e.property.type === 'Identifier' && e.property.name === 'children') return true; if (e.type === 'Identifier' && e.name === 'children') { return true; } return false; } function getSafeString(e: Expression | SpreadElement): Expression | undefined { if (e.type === 'ObjectExpression' && e.properties.length === 1 && e.properties[0].type === 'Property' && e.properties[0].key.type === 'MemberExpression' && e.properties[0].key.property.type === 'Identifier' && e.properties[0].key.property.name === 'safeString' && !isPattern(e.properties[0].value) ) { return e.properties[0].value; } return; } function toSafeString(jsxRuntime: string, e: Expression): ObjectExpression { return { type: 'ObjectExpression', properties: [ { type: 'Property', key: { type: 'MemberExpression', object: { type: 'Identifier', name: jsxRuntime }, computed: false, property: { type: 'Identifier', name: 'safeString' } } as MemberExpression, value: e, kind: 'init', computed: true, method: false, shorthand: false } ] }; } function isEscapeCall(e: Expression | SpreadElement): boolean { const expression = unwrapCallExpression(e); if (!expression) return false; return e.type === 'CallExpression' && expression.type === 'MemberExpression' && expression.object.type === 'Identifier' && expression.property.type === 'Identifier' && (expression.property.name === 'escape' || expression.property.name === 'escapeAttribute') ; } export function isOptimisedHtmlString(e: Expression | SpreadElement): boolean { //utils_1.escape(page).htmlString //or (0, utils_1.escape)(page).htmlString if (e.type !== 'MemberExpression') return false; const expression = unwrapCallExpression(e.object); if (!expression) return false; return expression.type === 'MemberExpression' && expression.property.type === 'Identifier' && expression.property.name === 'escape' && e.property.type === 'Identifier' && e.property.name === 'htmlString'; } function isUserEscapeCall(e: Expression | SpreadElement): boolean { const expression = unwrapCallExpression(e); if (!expression) return false; if (e.type === 'CallExpression' && expression.type === 'MemberExpression' && expression.object.type === 'Identifier' && expression.property.type === 'Identifier' && (expression.property.name === 'escape')) { return true; } return e.type === 'CallExpression' && expression.type === 'Identifier' && expression.name === 'escape' && e.arguments[0] !== undefined; } function extractChildrenFromObjectExpressionProperties(props: Array<Property | SpreadElement>): Expression | undefined { for (let i = 0; i < props.length; i++) { const prop = props[i]; if (prop.type === 'Property' && prop.key.type === 'Identifier' && prop.key.name === 'children') { props.splice(i, 1); return prop.value as Expression; } } return; } type ConcatableType = Expression | Identifier; type OptimisedBinaryExpression = BinaryExpression & { _optimised?: boolean }; type OptimisedArrayExpression = ArrayExpression & { _optimised?: boolean }; function isOptimisedArrayExpression(e: Expression): e is OptimisedArrayExpression { return e.type === 'ArrayExpression' && (e as any)._optimised === true; } function isOptimisedBinaryExpression(e: Expression): e is OptimisedBinaryExpression { return e.type === 'BinaryExpression' && (e as any)._optimised === true; } function extractBinaryExpressions(e: BinaryExpression, expressions?: Expression[]): Expression[] { expressions ||= []; if (e.left.type === 'BinaryExpression') { extractBinaryExpressions(e.left, expressions); } else { expressions.push(e.left); } if (e.right.type === 'BinaryExpression') { extractBinaryExpressions(e.right, expressions); } else { expressions.push(e.right); } return expressions; } /** * We convert .jsx/.jsxs back to createElement syntax to have one optimization syntax. * createElement is used by TSX as well as fallback when `<div {...props} something=123>` is used. * * * _jsx("div", { id: "123" }, void 0) * -> _jsx.createElement("div", {id: "123"}} * * _jsx("div", { children: "Test" }, void 0) * -> _jsx.createElement("div", {}, "Test") * * _jsx("div", Object.assign({ id: "123" }, { children: "Test" }), void 0) * -> _jsx.createElement("div", {id: "123"}, "Test"} * * _jsx("div", Object.assign({ id: "123" }, { children: _jsx('b", { children: "strong' }, void 0) }), void 0); * -> _jsx.createElement("div", {id: "123"}, _jsx.createElement("b", {}, "strong")) */ function convertNodeToCreateElement(node: Expression): Expression { if (node.type !== 'CallExpression') return node; let isCJS = isCjsJSXCall(node); const isAvoidedCJS = isAvoidedThisCjsJSXCall(node); const isESM = isESMJSXCall(node); if (!isCJS && !isESM && !isAvoidedCJS) return node; if (isESM) { //rewrite to _jsx.createElement node.callee = { type: 'MemberExpression', object: { type: 'Identifier', name: '_jsx' }, computed: false, property: { type: 'Identifier', name: 'createElement' } } as MemberExpression; } else if (isAvoidedCJS) { //convert (0, x)() to x() if (node.type === 'CallExpression' && node.callee.type === 'SequenceExpression') { const expression = node.callee.expressions[1]; node.callee = expression; isCJS = true; } } if (isCJS) { if (node.callee.type === 'MemberExpression' && node.callee.property.type === 'Identifier') { node.callee.property.name = 'createElement'; } } node.arguments.splice(2); //remove void 0 if (!node.arguments[1]) return node; if (node.arguments[1].type === 'CallExpression' && node.arguments[1].callee.type === 'MemberExpression' && node.arguments[1].callee.object.type === 'Identifier' && node.arguments[1].callee.object.name === 'Object') { //Object.assign(), means we have 2 entries, one with attributes, and second with `children` // Object.assign({id: 123}, {children: "Test"}) or // Object.assign({}, props, { id: "123" }, { children: "Test" }) const objectAssignsArgs = node.arguments[1].arguments; const lastArgument = objectAssignsArgs[objectAssignsArgs.length - 1]; if (lastArgument.type !== 'ObjectExpression') throw new Error(`Expect ObjectExpression, got ${JSON.stringify(lastArgument)}`); const children = extractChildrenFromObjectExpressionProperties(lastArgument.properties); if (children) { if (children.type === 'ArrayExpression') { node.arguments.push(...children.elements.map(v => convertNodeToCreateElement(v as Expression))); } else { node.arguments.push(convertNodeToCreateElement(children)); } } if (objectAssignsArgs.length > 2) { //remove last objectAssignsArgs.splice(objectAssignsArgs.length - 1, 1); } else { if (objectAssignsArgs[0].type === 'ObjectExpression') { node.arguments[1] = { type: 'ObjectExpression', properties: objectAssignsArgs[0].properties }; } } } else if (node.arguments[1].type === 'ObjectExpression') { //simple {} const children = extractChildrenFromObjectExpressionProperties(node.arguments[1].properties); if (children) { if (children.type === 'ArrayExpression') { node.arguments.push(...children.elements.map(v => convertNodeToCreateElement(v as Expression))); } else { node.arguments.push(convertNodeToCreateElement(children)); } } } return node; } export function optimizeJSX(code: string): string { const tree = parse(code); replace(tree, (node: any) => { if (isESMJSXCall(node) || isCjsJSXCall(node) || isAvoidedThisCjsJSXCall(node)) { return optimizeNode(convertNodeToCreateElement(node), true); } return node; }); return generate(tree); } export function convertJsxCodeToCreateElement(code: string): string { const tree = parse(code); replace(tree, (node: any) => { if (isESMJSXCall(node) || isCjsJSXCall(node) || isAvoidedThisCjsJSXCall(node)) { return convertNodeToCreateElement(node); } return node; }); return generate(tree); }
the_stack
/// <reference types="node"/> import * as fxn from 'fxn'; export class APIConstructor { format(obj: any, arrInterface?: string[]): { meta: { total: number; count: number; offset: number; error: any; summary: string | null | undefined; resource: any; }; data: any; }; meta(total: number, count: number, offset: number, error: any, summary?: string | null, resource?: any): { total: number; count: number; offset: number; error: any; summary: string | null | undefined; resource: any; }; error(message: string, details: string): { meta: { total: number; count: number; offset: number; error: any; summary: string | null | undefined; resource: any; }; data: never[]; }; spoof(obj: any, useResource?: boolean): { meta: { total: number; count: number; offset: number; error: any; summary: string | null | undefined; resource: any; }; data: any; }; response(itemArray: any, arrInterface: any, useResource?: boolean): { meta: { total: number; count: number; offset: number; error: any; summary: string | null | undefined; resource: any; }; data: any; }; resourceFromArray(arr: any[]): { name: string; fields: any[]; }; resourceFromModelArray(modelArray: any, arrInterface: any): any; } export const API: APIConstructor; export const APIResource: any; export class Application extends fxn.Application { constructor(); /** * HTTP Error */ error(req: any, res: any, start: any, status: number, message: string, err: any): void; } export class Controller extends fxn.Controller { /** * Set HTTP status code for this response. If OPTIONS mode, default to 200. * @param {Number} code */ status(value: number): boolean; /** * Using API formatting, send an http.ServerResponse indicating there was a Bad Request (400) * @param {string} msg Error message to send * @param {Object} details Any additional details for the error (must be serializable) * @return {boolean} */ badRequest(msg: string, details: any): boolean; /** * Using API formatting, send an http.ServerResponse indicating there was an Unauthorized request (401) * @param {string} msg Error message to send * @param {Object} details Any additional details for the error (must be serializable) * @return {boolean} */ unauthorized(msg: string, details: any): boolean; /** * Using API formatting, send an http.ServerResponse indicating the requested resource was Not Found (404) * @param {string} msg Error message to send * @param {Object} details Any additional details for the error (must be serializable) * @return {boolean} */ notFound(msg: string, details: any): boolean; /** * Endpoint not implemented * @param {string} msg Error message to send * @param {Object} details Any additional details for the error (must be serializable) * @return {boolean} */ notImplemented(msg: string, details: any): boolean; /** * Using API formatting, send an http.ServerResponse indicating there were Too Many Requests (429) (i.e. the client is being rate limited) * @param {string} msg Error message to send * @param {Object} details Any additional details for the error (must be serializable) * @return {boolean} */ tooManyRequests(msg: string, details: any): boolean; /** * Using API formatting, send an http.ServerResponse indicating there was an Internal Server Error (500) * @param {string} msg Error message to send * @param {Object} details Any additional details for the error (must be serializable) * @return {boolean} */ error(msg: string, details: any): boolean; /** * Using API formatting, generate an error or respond with model / object data. * @param {Error|Object|Array|Nodal.Model|Nodal.ModelArray} data Object to be formatted for API response * @param {optional Array} The interface to use for the data being returned, if not an error. * @return {boolean} */ respond(data: Error | Object | any[] | Model | ModelArray<Model>, arrInterface?: string[]): boolean; } export interface IComparison { [item: string]: any; __order?: string; __offset?: number; __count?: number; } export class Composer<T extends Model> { db: Database; Model: T; private _parent; private _command; /** * Created by Model#query, used for composing SQL queries based on Models * @param {Nodal.Model} Model The model class the composer is querying from * @param {Nodal.Composer} [parent=null] The composer's parent (another composer instance) */ constructor(modelConstructor: typeof Model, parent?: Composer<any>); /** * Given rows with repeated data (due to joining in multiple children), * return only parent models (but include references to their children) * @param {Array} rows Rows from sql result * @param {Boolean} grouped Are these models grouped, if so, different procedure * @return {Nodal.ModelArray} * @private */ private __parseModelsFromRows__(rows, grouped?); /** * Collapses linked list of queries into an array (for .reduce, .map etc) * @return {Array} * @private */ private __collapse__(); /** * Removes last limit command from a collapsed array of composer commands * @param {Array} [composerArray] Array of composer commands * @return {Array} * @private */ private __removeLastLimitCommand__(composerArray); /** * Gets last limit command from a collapsed array of composer commands * @param {Array} [composerArray] Array of composer commands * @return {Array} * @private */ private __getLastLimitCommand__(composerArray); /** * Determines whether this composer query represents a grouped query or not * @return {Boolean} * @private */ private __isGrouped__(); /** * Reduces an array of composer queries to a single query information object * @param {Array} [composerArray] * @return {Object} Looks like {commands: [], joins: []} * @private */ private __reduceToQueryInformation__(composerArray); /** * Reduces an array of commands from query informtion to a SQL query * @param {Array} [commandArray] * @param {Array} [includeColumns=*] Which columns to include, includes all by default * @return {Object} Looks like {sql: [], params: []} * @private */ private __reduceCommandsToQuery__(commandArray, includeColumns?); /** * Retrieve all joined column data for a given join * @param {string} joinName The name of the join relationship * @private */ private __joinedColumns__(joinName); /** * Generate a SQL query and its associated parameters from the current composer instance * @param {Array} [includeColumns=*] Which columns to include, includes all by default * @param {boolean} [disableJoins=false] Disable joins if you just want a subset of data * @return {Object} Has "params" and "sql" properties. * @private */ private __generateQuery__(includeColumns?, disableJoins?); /** * Generate a SQL count query * @param {boolean} [useLimit=false] Generates COUNT using limit command as well * @return {Object} Has "params" and "sql" properties. * @private */ private __generateCountQuery__(useLimit?); /** * Add Joins to a query from queryInfo * @param {Object} query Must be format {sql: '', params: []} * @param {Object} queryInfo Must be format {commands: [], joins: []} * @param {Array} [includeColumns=*] Which columns to include, includes all by default * @return {Object} Has "params" and "sql" properties. * @private */ private __addJoinsToQuery__(query, queryInfo, includeColumns?); /** * When using Composer#where, format all provided comparisons * @param {Object} comparisons Comparisons object. {age__lte: 27}, for example. * @param {Nodal.Model} Model the model to use as the basis for comparison. Default to current model. * @return {Array} * @private */ private __parseComparisons__(comparisons, model?); private __filterHidden__(modelConstructor, comparisonsArray); /** * Add comparisons to SQL WHERE clause. Does not allow filtering if Model.hides() has been called. * @param {Object} comparisons Comparisons object. {age__lte: 27}, for example. * @return {Nodal.Composer} new Composer instance */ safeWhere(...comparisonsArray: IComparison[]): this; /** * Join in a relationship. Filters out hidden fields from comparisons. * @param {string} joinName The name of the joined relationship * @param {array} comparisonsArray comparisons to perform on this join (can be overloaded) */ safeJoin(joinName: string, ...comparisonsArray: IComparison[]): this; /** * Add comparisons to SQL WHERE clause. * @param {Object} comparisons Comparisons object. {age__lte: 27}, for example. * @return {Nodal.Composer} new Composer instance */ where(...comparisonsArray: IComparison[]): this; /** * Order by field belonging to the current Composer instance's model. * @param {string} field Field to order by * @param {string} direction Must be 'ASC' or 'DESC' * @return {Nodal.Composer} new Composer instance */ orderBy(field: string, direction?: 'ASC' | 'DSC' | any): this; /** * Limit to an offset and count * @param {number} offset The offset at which to set the limit. If this is the only argument provided, it will be the count instead. * @param {number} count The number of results to be returned. Can be omitted, and if omitted, first argument is used for count. * @return {Nodal.Composer} new Composer instance */ limit(offset: number | string, count?: number | string): this; /** * Join in a relationship. * @param {string} joinName The name of the joined relationship * @param {array} comparisonsArray comparisons to perform on this join (can be overloaded) */ join(joinName: string, comparisonsArray?: IComparison[] | IComparison, orderBy?: 'ASC' | 'DESC', count?: number, offset?: number): this; /** * Groups by a specific field, or a transformation on a field * @param {String} column The column to group by */ groupBy(column: string): this; /** * Aggregates a field * @param {String} alias The alias for the new aggregate field * @param {Function} transformation The transformation to apply to create the aggregate */ aggregate(alias: string, transformation?: Function): this; /** * Counts the results in the query * @param {function} callback Supplied with an error and the integer value of the count */ count(callback: (err: Error, count: number) => void): void; /** * Execute the query you've been composing. * @param {function({Error}, {Nodal.ModelArray})} callback The method to execute when the query is complete */ end(callback: (err: Error, modelArray: ModelArray<T>) => void): void; /** * Shortcut for .limit(1).end(callback) that only returns a model object or error if not found * @param {Function} callback Callback to execute, provides an error and model parameter */ first(callback: (err: Error, model: Model) => void): void; /** * Execute query as an update query, changed all fields specified. * @param {Object} fields The object containing columns (keys) and associated values you'd like to update * @param {function({Error}, {Nodal.ModelArray})} callback The callback for the update query */ update(fields: IAnyObject, callback: (err: Error, modelArray: ModelArray<T>) => void): void; } export const CLI: any; export class Daemon extends fxn.Daemon { constructor(); error(req: any, res: any, err: any): void; } export class Database { adapter: any; __logColorFuncs: Function[]; private _useLogColor; constructor(); connect(cfg: any): boolean; close(callback: Function): boolean; log(sql: string, params?: any, time?: number): boolean; info(message: string): void; error(message: string): boolean; query(...args: any[]): void; transaction(...args: any[]): void; drop(): void; create(): void; } export class GraphQuery { private ['constructor']; identifier: string; name: string; Model: typeof Model; structure: any; joins: any; /** * Create a GraphQuery object * @param {String} str The query to execute * @param {Number} maxDepth The maximum depth of graph to traverse * @param {Nodal.Model} [Model=null] The Model to base your query around (used for testing) */ constructor(str: string, maxDepth: number, mModel?: typeof Model); /** * Create and execute a GraphQuery object * @param {String} str The query to execute * @param {Number} maxDepth The maximum depth of graph to traverse * @param {Function} callback The function to execute upon completion */ static query(str: string, maxDepth: number, callback: Function): boolean; /** * Parse syntax tree of a GraphQL query */ static parseSyntaxTree(str: string, state?: string, arr?: any[]): any; /** * Fully parse a GraphQL query, get necessary joins to make in SQL */ static parse(str: string, max: number): { structure: any; joins: {}; }; /** * Format a parsed syntax tree in a way that the Composer expects */ static formatTree(tree: any[], max: number, joins: any, parents?: any): any[]; /** * Query the GraphQuery object from the database * @param {Function} callback The function to execute upon completion */ query(callback: Function): this; } export interface IArrayMetadata { total?: number; offset?: number; [other: string]: any; } export class ItemArray<T> extends Array<T> { private _meta; constructor(); static from(arr: Object[]): ItemArray<{}>; setMeta(data: IArrayMetadata): IArrayMetadata; toObject(arrInterface: string[]): Object; } export class Migration { private db; private id; private schema; constructor(db: Database); up(): string[]; down(): string[]; executeUp(callback: (err: Error) => void): void; executeDown(callback: (err: Error) => void, prevId?: string): void; createTable(table: string, arrFieldData: Object[], modelName: string): any; dropTable(table: string): any; renameTable(table: string, newTableName: string, renameModel: string, newModelName: string): any; alterColumn(table: string, column: string, type: DataType, properties: IColumnProperties): any; addColumn(table: string, column: string, type: DataType, properties: IColumnProperties): any; dropColumn(table: string, column: string): any; renameColumn(table: string, column: string, newColumn: string): any; createIndex(table: string, column: string, type: DataType): any; dropIndex(table: string, column: string): any; addForeignKey(table: string, referenceTable: string): any; dropForeignKey(table: string, referenceTable: string): any; } export const mime: any; /** * Model Stuff */ export interface IErrorsObject { _query?: any; [field: string]: string[]; } export interface ICalculation { fields: string[]; calculate: Function; } export interface ICalculations { [calculations: string]: ICalculation; } export class Model { ['constructor']: typeof Model; db: Database | any; schema: { table: string; columns: IColumn[]; }; data: any; externalInterface: string[]; aggregateBy: { id: string; created_at: string; updated_at: string; }; formatters: IAnyObject; _inStorage: boolean; private _isSeeding; private _changed; private _errors; private _joinsList; private _joinsCache; private _data; _calculations: ICalculations; private static _relationshipCache; _validations: IAnyObject; _validationsList: any[]; _calculationsList: string[]; _verificationsList: any; _hides: IAnyObject; _table: string; _columnLookup: { [key: string]: any; }; _columnNames: string[]; _columns: IColumn[]; _relationshipCache: IAnyObject; constructor(modelData: Object, fromStorage?: boolean, fromSeed?: boolean); /** * Indicates whethere or not the model is currently represented in hard storage (db). * @return {boolean} */ inStorage(): boolean; /** * Indicates whethere or not the model is being generated from a seed. * @return {boolean} */ isSeeding(): boolean; /** * Tells us whether a model field has changed since we created it or loaded it from storage. * @param {string} field The model field * @return {boolean} */ hasChanged(field: string): boolean; /** * Provides an array of all changed fields since model was created / loaded from storage * @return {Array} */ changedFields(): string[]; /** * Creates an error object for the model if any validations have failed, returns null otherwise * @return {Error} */ errorObject(): IExtendedError | null; /** * Tells us whether or not the model has errors (failed validations) * @return {boolean} */ hasErrors(): boolean; /** * Gives us an error object with each errored field as a key, and each value * being an array of failure messages from the validators * @return {Object} */ getErrors(): IErrorsObject; /** * Reads new data into the model. * @param {Object} data Data to inject into the model * @return {this} */ read(data: IAnyObject): this; /** * Converts a value to its intended format based on its field. Returns null if field not found. * @param {string} field The field to use for conversion data * @param {any} value The value to convert */ convert(field: string, value: any): any; /** * Grabs the path of the given relationship from the RelationshipGraph * @param {string} name the name of the relationship */ relationship(name: string): RelationshipPath; /** * Sets specified field data for the model. Logs and validates the change. * @param {string} field Field to set * @param {any} value Value for the field */ set(field: string, value: any): any; /** * Set a joined object (Model or ModelArray) * @param {string} field The field (name of the join relationship) * @param {Model|ModelArray} value The joined model or array of models */ setJoined(field: string, value: ModelArray<this> | Model): Model | ModelArray<this>; /** * Calculate field from calculations (assumes it exists) * @param {string} field Name of the calculated field */ calculate(field: string): void; /** * Retrieve field data for the model. * @param {string} field Field for which you'd like to retrieve data. */ get(field: string, ignoreFormat?: boolean): any; /** * Retrieves joined Model or ModelArray * @param {String} joinName the name of the join (list of connectors separated by __) */ joined(joinName: string): Model | ModelArray<this>; /** * Retrieve associated models joined this model from the database. * @param {function({Error} err, {Nodal.Model|Nodal.ModelArray} model_1, ... {Nodal.Model|Nodal.ModelArray} model_n)} * Pass in a function with named parameters corresponding the relationships you'd like to retrieve. * The first parameter is always an error callback. */ include(callback: (err: Error, ...models: (Model | ModelArray<this>)[]) => void): void; /** * Creates a plain object from the Model, with properties matching an optional interface * @param {Array} arrInterface Interface to use for object creation */ toObject(arrInterface?: any[]): any; /** * Get the table name for the model. * @return {string} */ tableName(): string; /** * Determine if the model has a specified field. * @param {string} field * @return {boolean} */ hasField(field: string): boolean; /** * Retrieve the schema field data for the specified field * @param {string} field * @return {Object} */ getFieldData(field: string): any; /** * Retrieve the schema data type for the specified field * @param {string} field * @return {string} */ getDataTypeOf(field: string): { convert: Function; }; /** * Determine whether or not this field is an Array (PostgreSQL supports this) * @param {string} field * @return {boolean} */ isFieldArray(field: string): boolean; /** * Determine whether or not this field is a primary key in our schema * @param {string} field * @return {boolean} */ isFieldPrimaryKey(field: string): boolean; /** * Retrieve the defaultValue for this field from our schema * @param {string} field * @return {any} */ fieldDefaultValue(field: string): any; /** * Retrieve an array of fields for our model * @return {Array} */ fieldList(): string[]; /** * Retrieve our field schema definitions * @return {Array} */ fieldDefinitions(): IColumn[]; /** * Set an error for a specified field (supports multiple errors) * @param {string} key The specified field for which to create the error (or '*' for generic) * @param {string} message The error message * @return {boolean} */ setError(key: string, message: string): boolean; /** * Clears all errors for a specified field * @param {string} key The specified field for which to create the error (or '*' for generic) * @return {boolean} */ clearError(key: string): boolean; __generateSaveQuery__(): { sql: any; params: any; }; /** * Runs all verifications before saving * @param {function} callback Method to execute upon completion. Returns true if OK, false if failed * @private */ __verify__(callback: Function): any; /** * Saves model to database * @param {function} callback Method to execute upon completion, returns error if failed (including validations didn't pass) * @private */ private __save__(callback); /** * Destroys model and cascades all deletes. * @param {function} callback method to run upon completion */ destroyCascade(callback: Function): void; /** * Logic to execute before a model gets destroyed. Intended to be overwritten when inherited. * @param {Function} callback Invoke with first argument as an error if failure. */ beforeDestroy(callback: Function): void; /** * Logic to execute after a model is destroyed. Intended to be overwritten when inherited. * @param {Function} callback Invoke with first argument as an error if failure. */ afterDestroy(callback: Function): void; /** * Destroys model reference in database. * @param {function({Error} err, {Nodal.Model} model)} callback * Method to execute upon completion, returns error if failed */ destroy(callback: Function): void; /** * Logic to execute before a model saves. Intended to be overwritten when inherited. * @param {Function} callback Invoke with first argument as an error if failure. */ beforeSave(callback: Function): void; /** * Logic to execute after a model saves. Intended to be overwritten when inherited. * @param {Function} callback Invoke with first argument as an error if failure. */ afterSave(callback: Function): void; /** * Save a model (execute beforeSave and afterSave) * @param {Function} callback Callback to execute upon completion */ save(callback: Function): void; /** * Runs an update query for this specific model instance * @param {Object} fields Key-value pairs of fields to update * @param {Function} callback Callback to execute upon completion */ update(fields: IAnyObject, callback: Function): void; static find(id: number, callback: (err: IExtendedError, model?: Model) => void): void; static findBy(field: string, value: any, callback: (err: IExtendedError, model?: Model) => void): void; /** * Creates a new model instance using the provided data. * @param {object} data The data to load into the object. * @param {function({Error} err, {Nodal.Model} model)} callback The callback to execute upon completion */ static create(data: IAnyObject, callback: (err: IExtendedError, model?: Model) => void): void; /** * Finds a model with a provided field, value pair. Returns the first found. * @param {string} field Name of the field * @param {object} data Key-value pairs of Model creation data. Will use appropriate value to query for based on "field" parametere. * @param {function({Error} err, {Nodal.Model} model)} callback The callback to execute upon completion */ static findOrCreateBy(field: string, data: IAnyObject, callback: (err: IExtendedError | null, model?: Model) => void): void; /** * Finds and updates a model with a specified id. Return a notFound error if model does not exist. * @param {number} id The id of the model you're looking for * @param {object} data The data to load into the object. * @param {function({Error} err, {Nodal.Model} model)} callback The callback to execute upon completion */ static update(id: number, data: IAnyObject, callback: (err: IExtendedError, model?: Model) => void): void; /** * Finds and destroys a model with a specified id. Return a notFound error if model does not exist. * @param {number} id The id of the model you're looking for * @param {function({Error} err, {Nodal.Model} model)} callback The callback to execute upon completion */ static destroy(id: number, callback: (err: IExtendedError, model?: Model) => void): void; /** * Creates a new Composer (ORM) instance to begin a new query. * @param {optional Nodal.Database} db Deprecated - provide a database to query from. Set the model's db in its constructor file, instead. * @return {Nodal.Composer} */ static query<T extends Model>(db?: Database): Composer<T>; /** * Get the model's table name * @return {string} */ static table(): string; /** * Get the model's column data * @return {Array} */ static columns(): IColumn[]; /** * Get the model's column names (fields) * @return {Array} */ static columnNames(): string[]; /** * Get the model's column lookup data * @return {Object} */ static columnLookup(): IAnyObject; /** * Check if the model has a column name in its schema * @param {string} columnName */ static hasColumn(columnName: string): boolean; /** * Return the column schema data for a given name * @param {string} columnName */ static column(columnName: string): any; /** * Set the database to be used for this model * @param {Nodal.Database} db */ static setDatabase(db: Database): void; /** * Set the schema to be used for this model * @param {Object} schema */ static setSchema(schema: { table: string; columns: IColumn[]; }): void; /** * FIXME */ static relationships(): RelationshipNode; /**` * FIXME */ static relationship(name: string): RelationshipPath; /** * Sets a joins relationship for the Model. Sets joinedBy relationship for parent. * @param {class Nodal.Model} Model The Model class which your current model belongs to * @param {Object} [options={}] * "name": The string name of the parent in the relationship (default to camelCase of Model name) * "via": Which field in current model represents this relationship, defaults to `${name}_id` * "as": What to display the name of the child as when joined to the parent (default to camelCase of child name) * "multiple": Whether the child exists in multiples for the parent (defaults to false) */ static joinsTo(modelClass: typeof Model, options: { name?: string; via?: string; as?: string; multiple?: boolean; }): RelationshipEdge | null; /** * Create a validator. These run synchronously and check every time a field is set / cleared. * @param {string} field The field you'd like to validate * @param {string} message The error message shown if a validation fails. * @param {function({any} value)} fnAction the validation to run - first parameter is the value you're testing. */ static validates(field: string, message: string, fnAction: (value: any) => void): void; /** * Creates a verifier. These run asynchronously, support multiple fields, and check every time you try to save a Model. * @param {string} message The error message shown if a validation fails. * @param {function} fnAction The asynchronous verification method. The last argument passed is always a callback, * and field names are determined by the argument names. */ static verifies(message: string, fnAction: Function): void; /** * Create a calculated field (in JavaScript). Must be synchronous. * @param {string} calcField The name of the calculated field * @param {function} fnCalculate The synchronous method to perform a calculation for. * Pass the names of the (non-computed) fields you'd like to use as parameters. */ static calculates(calcField: string, fnCompute: Function): void; /** * Hides fields from being output in .toObject() (i.e. API responses), even if asked for * @param {String} field */ static hides(field: string): boolean; /** * Tells us if a field is hidden (i.e. from API queries) * @param {String} field */ static isHidden(field: string): any; /** * Prepare model for use * @private */ private __initialize__(); __load__(data: any, fromStorage?: boolean, fromSeed?: boolean): this; /** * Validates provided fieldList (or all fields if not provided) * @private * @param {optional Array} fieldList fields to validate */ private __validate__(field?); /** * Sets specified field data for the model, assuming data is safe and does not log changes * @param {string} field Field to set * @param {any} value Value for the field */ public __safeSet__(field: string, value: any): void; /** * Destroys model reference in database * @param {function} callback Method to execute upon completion, returns error if failed * @private */ private __destroy__(callback); } export class ModelArray<T> extends ItemArray<T> { Model: typeof Model; constructor(modelConstructor: typeof Model); static from<T>(arr: Model[]): ModelArray<T>; toObject(arrInterface?: string[]): any; has(model: Model): boolean; readAll(data: Object): boolean; setAll(field: string, value: string): boolean; destroyAll(callback: Function): void; destroyCascade(callback: Function): void; saveAll(callback: Function): Function | undefined; private __saveAll__(callback); } export interface IModelData { [modelName: string]: any[]; } /** * Factory for creating models * @class */ export class ModelFactory { private Model; /** * Create the ModelFactory with a provided Model to use as a reference. * @param {Nodal.Model} modelConstructor Must pass the constructor for the type of ModelFactory you wish to create. */ constructor(modelConstructor: typeof Model); /** * Loads all model constructors in your ./app/models directory into an array * @return {Array} Array of model Constructors */ static loadModels(): any[]; /** * Creates new factories from a supplied array of Models, loading in data keyed by Model name * @param {Array} Models Array of model constructors you wish to reference * @param {Object} objModelData Keys are model names, values are arrays of model data you wish to create * @param {Function} callback What to execute upon completion */ static createFromModels(Models: (typeof Model)[], objModelData: IModelData, callback: Function): void; /** * Populates a large amount of model data from an Object. * @param {Array} Models Array of Model constructors */ static populate(objModelData: IModelData, callback: Function): void; /** * Creates models from an array of Objects containing the model data * @param {Array} arrModelData Array of objects to create model data from */ create(arrModelData: IModelData[], callback: Function): void; } export interface IOptions { name: string; multiple: boolean; as: string; via: string; } export class RelationshipPath { private ['constructor']; path: (RelationshipEdge | RelationshipNode)[]; constructor(path: (RelationshipEdge | RelationshipNode)[]); toString(): string; joinName(reverse?: boolean): string; add(node: RelationshipNode, edge: RelationshipEdge): RelationshipPath; getModel(): typeof Model; multiple(): boolean; immediateMultiple(): boolean; joins(alias?: string | null, firstTable?: string): IJoin[]; } export class RelationshipNode { Graph: RelationshipGraph; Model: typeof Model; edges: RelationshipEdge[]; constructor(Graph: RelationshipGraph, mModel: typeof Model); toString(): string; joinsTo(mModel: typeof Model, options: IOptions): RelationshipEdge | null; childEdges(): RelationshipEdge[]; cascade(): RelationshipPath[]; findExplicit(pathname: string): RelationshipPath | null; find(name: string): RelationshipPath | null; } export class RelationshipEdge { id: number; parent: RelationshipNode; child: RelationshipNode; options: IOptions; constructor(parent: RelationshipNode, child: RelationshipNode, options: IOptions); toString(): string; hasChild(child: RelationshipNode): boolean; hasParent(parent: RelationshipNode): boolean; opposite(node: RelationshipNode): RelationshipNode | null; } export class RelationshipGraph { nodes: RelationshipNode[]; edges: RelationshipEdge[]; constructor(); of(mModel: typeof Model): RelationshipNode; } export class Router extends fxn.Router { } export class Scheduler extends fxn.Scheduler { } /** * Random types used across multiple classes. */ export interface IAnyObject { [prop: string]: any; } export interface IExtendedError extends Error { notFound?: boolean; details?: Object; } export interface IColumn { name: string; type: DataType; properties: IColumnProperties; } export interface ISchema { table: string; columns: IColumn[]; } export interface IJoin { prevColumn?: string; joinColumn?: string; joinTable: string; prevTable: string; name?: string; key?: string; multiple?: boolean; columns?: string[]; columnsObject?: Object; cachedModel?: Model; joinAlias?: string; multiFilter?: any; prevAlias?: string; orderBy?: any; offset?: number; count?: number; } export type Query = any; export interface IColumnProperties { length?: number | null; nullable?: boolean; primary_key?: 0 | 1 | boolean; auto_increment?: boolean; unique?: 0 | 1 | boolean; array?: boolean; defaultValue?: any; } export interface IArrInterface { [item: string]: [string]; } export type InterfaceType = IArrInterface | string; export type DataType = 'serial' | 'int' | 'currency' | 'float' | 'string' | 'text' | 'datetime' | 'boolean' | 'json'; export const my: { Config?: any; Schema?: any; bootstrapper?: any; }; export const require: NodeRequire;
the_stack
import {jsx, Global} from '@emotion/core' import '@reach/tabs/styles.css' import '@reach/tooltip/styles.css' import * as React from 'react' import ReactDOM from 'react-dom' import {FaTools} from 'react-icons/fa' import {Tooltip} from '@reach/tooltip' import {Tabs, TabList, TabPanels, TabPanel, Tab} from '@reach/tabs' import * as colors from '../styles/colors' const isLsKey = (name: string) => name.startsWith(`__react_workshop_app`) const getKey = (name: string) => `__react_workshop_app_${name}__` function install() { // @ts-expect-error I do not care... const requireDevToolsLocal = require.context( './', false, /dev-tools\.local\.(js|tsx|ts)/, ) const local = requireDevToolsLocal.keys()[0] if (local) { requireDevToolsLocal(local) } function DevTools() { const rootRef = React.useRef<HTMLDivElement>(null) const [hovering, setHovering] = React.useState(false) const [persist, setPersist] = useLocalStorageState( getKey('devtools_persist'), false, ) const [tabIndex, setTabIndex] = useLocalStorageState( getKey('devtools_tab_index'), 0, ) const show = persist || hovering const toggleShow = () => setPersist(v => !v) React.useEffect(() => { function updateHoverState(event: MouseEvent) { setHovering(rootRef.current?.contains(event.target as Node) ?? false) } document.addEventListener('mousemove', updateHoverState) return () => { document.removeEventListener('mousemove', updateHoverState) } }, []) // eslint-disable-next-line consistent-return React.useEffect(() => { if (hovering) { const iframes = Array.from(document.querySelectorAll('iframe')) for (const iframe of iframes) { iframe.style.pointerEvents = 'none' } return () => { for (const iframe of iframes) { iframe.style.pointerEvents = '' } } } }, [hovering]) return ( <div css={{ position: 'fixed', zIndex: 20, bottom: -15, left: 0, right: 0, width: show ? '100%' : 0, transition: 'all 0.3s', label: { margin: 0, color: 'rgb(216, 221, 227)', }, 'input, select': { background: 'rgb(20, 36, 55)', border: '2px solid rgb(28, 46, 68)', borderRadius: 5, color: 'white', fontWeight: 600, padding: '5px', '::placeholder': { color: 'rgba(255,255,255,0.3)', }, ':focus': { outlineColor: colors.indigo, borderColor: colors.indigo, outline: '1px', }, }, button: { cursor: 'pointer', }, 'button:not([data-reach-tab])': { borderRadius: 5, background: colors.indigo, ':hover': { background: colors.indigoDarken10, }, border: 0, color: colors.gray, }, '[data-reach-tab]': { border: 0, ':focus': { outline: 'none', }, }, '[data-reach-tab][data-selected]': { background: 'rgb(11, 21, 33)', borderBottom: '3px solid white', marginBottom: -3, }, }} > <div ref={rootRef} css={[ { background: 'rgb(11, 21, 33)', opacity: '0.6', color: 'white', boxSizing: 'content-box', height: '60px', width: '68px', transition: 'all 0.3s', overflow: 'auto', }, show ? { height: '50vh', width: '100%', opacity: '1', } : null, ]} > <Tooltip label="Toggle Persist DevTools"> <button css={{ display: 'flex', alignItems: 'center', fontSize: '1.2rem', border: 'none', padding: '10px 20px', background: 'none', marginTop: show ? -40 : 0, marginLeft: show ? 20 : 0, position: 'absolute', backgroundColor: 'rgb(11,21,33) !important', overflow: 'hidden', svg: { width: 20, marginRight: 8, color: persist ? 'white' : 'rgba(255,255,255,0.7)', }, '::before': { content: '""', position: 'absolute', height: 4, width: '100%', left: 0, top: 0, background: persist ? colors.yellow : 'transparent', }, }} onClick={toggleShow} > <FaTools /> {show ? 'Workshop DevTools' : null} </button> </Tooltip> {show ? ( <Tabs css={{padding: 20}} index={tabIndex} onChange={i => setTabIndex(i)} > <TabList css={{marginBottom: 20}}> <Tab>Controls</Tab> <Tab>Request Failures</Tab> </TabList> <div css={{ border: '1px solid rgb(28,46,68)', margin: '0px -20px 20px -20px', }} /> <TabPanels css={{height: '100%'}}> <TabPanel> <ControlsPanel /> </TabPanel> <TabPanel> <RequestFailUI /> </TabPanel> </TabPanels> </Tabs> ) : null} </div> {show ? ( <Global styles={{ '#root': { marginBottom: '50vh', }, }} /> ) : null} </div> ) } DevTools.displayName = 'DevTools' // add dev tools UI to the page let devToolsRoot = document.getElementById('dev-tools') if (devToolsRoot) { ReactDOM.unmountComponentAtNode(devToolsRoot) // right } if (!devToolsRoot) { devToolsRoot = document.createElement('div') devToolsRoot.id = 'dev-tools' document.body.appendChild(devToolsRoot) } ReactDOM.render(<DevTools />, devToolsRoot) } function ControlsPanel() { return ( <div css={{ display: 'grid', gridTemplateColumns: '1fr', gridTemplateRows: 'repeat(auto-fill, minmax(40px, 40px) )', gridGap: '0.5rem', marginRight: '1.5rem', }} > <EnableDevTools /> <FailureRate /> <RequestMinTime /> <RequestVarTime /> <ClearLocalStorage /> </div> ) } ControlsPanel.displayName = 'ControlsPanel' function ClearLocalStorage() { function clear() { const keysToRemove: Array<string> = [] for (let i = 0; i < window.localStorage.length; i++) { const key = window.localStorage.key(i) if (typeof key === 'string' && isLsKey(key)) keysToRemove.push(key) } for (const lsKey of keysToRemove) { window.localStorage.removeItem(lsKey) } // refresh window.location.assign(window.location.toString()) } return <button onClick={clear}>Purge Database</button> } ClearLocalStorage.displayName = 'ClearLocalStorage' function FailureRate() { const [failureRate, setFailureRate] = useLocalStorageState( getKey('failure_rate'), 0, ) const handleChange = (event: React.SyntheticEvent<HTMLInputElement>) => setFailureRate(Number(event.currentTarget.value) / 100) return ( <div css={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > <label htmlFor="failureRate">Request Failure Percentage: </label> <input css={{marginLeft: 6}} value={failureRate * 100} type="number" min="0" max="100" step="10" onChange={handleChange} id="failureRate" /> </div> ) } FailureRate.displayName = 'FailureRate' function EnableDevTools() { const [enableDevTools, setEnableDevTools] = useLocalStorageState( getKey('dev-tools'), process.env.NODE_ENV === 'development', ) const handleChange = (event: React.SyntheticEvent<HTMLInputElement>) => setEnableDevTools(event.currentTarget.checked) return ( <div css={{ width: '100%', display: 'flex', alignItems: 'center', }} > <input css={{marginRight: 6}} checked={enableDevTools} type="checkbox" onChange={handleChange} id="enableDevTools" /> <label htmlFor="enableDevTools">Enable DevTools by default</label> </div> ) } EnableDevTools.displayName = 'EnableDevTools' function RequestMinTime() { const [minTime, setMinTime] = useLocalStorageState( getKey('min_request_time'), 400, ) const handleChange = (event: React.SyntheticEvent<HTMLInputElement>) => setMinTime(Number(event.currentTarget.value)) return ( <div css={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > <label htmlFor="minTime">Request min time (ms): </label> <input css={{marginLeft: 6}} value={minTime} type="number" step="100" min="0" max={1000 * 60} onChange={handleChange} id="minTime" /> </div> ) } RequestMinTime.displayName = 'RequestMinTime' function RequestVarTime() { const [varTime, setVarTime] = useLocalStorageState( getKey('variable_request_time'), 400, ) const handleChange = (event: React.SyntheticEvent<HTMLInputElement>) => setVarTime(Number(event.currentTarget.value)) return ( <div css={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > <label htmlFor="varTime">Request variable time (ms): </label> <input css={{marginLeft: 6}} value={varTime} type="number" step="100" min="0" max={1000 * 60} onChange={handleChange} id="varTime" /> </div> ) } RequestVarTime.displayName = 'RequestVarTime' interface RequestFailFormElements extends HTMLFormControlsCollection { requestMethod: HTMLInputElement urlMatch: HTMLInputElement } interface RequestFailFormElement extends HTMLFormElement { readonly elements: RequestFailFormElements } function RequestFailUI() { type FailConfig = { requestMethod: string urlMatch: string } const [failConfig, setFailConfig] = useLocalStorageState<Array<FailConfig>>( getKey('request_fail_config'), [], ) function handleRemoveClick(index: number) { setFailConfig(c => [...c.slice(0, index), ...c.slice(index + 1)]) } function handleSubmit(event: React.SyntheticEvent<RequestFailFormElement>) { event.preventDefault() const {requestMethod, urlMatch} = event.currentTarget.elements setFailConfig(c => [ ...c, {requestMethod: requestMethod.value, urlMatch: urlMatch.value}, ]) requestMethod.value = '' urlMatch.value = '' } return ( <div css={{ display: 'flex', width: '100%', }} > <form onSubmit={handleSubmit} css={{ display: 'grid', gridTemplateRows: 'repeat(auto-fill, minmax(50px, 60px) )', maxWidth: 300, width: '100%', marginRight: '1rem', gridGap: 10, }} > <div css={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > <label htmlFor="requestMethod">Method:</label> <select id="requestMethod" required> <option value="">Select</option> <option value="ALL">ALL</option> <option value="GET">GET</option> <option value="POST">POST</option> <option value="PUT">PUT</option> <option value="DELETE">DELETE</option> </select> </div> <div css={{width: '100%'}}> <label css={{display: 'block'}} htmlFor="urlMatch"> URL Match: </label> <input autoComplete="off" css={{width: '100%', marginTop: 4}} id="urlMatch" required placeholder="/api/list-items/:listItemId" /> </div> <div> <button css={{padding: '6px 16px'}} type="submit"> + Add </button> </div> </form> <ul css={{ listStyle: 'none', margin: 0, padding: 0, width: '100%', paddingBottom: '2rem', }} > {failConfig.map(({requestMethod, urlMatch}, index) => ( <li key={index} css={{ padding: '6px 10px', borderRadius: 5, margin: '5px 0', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: 'rgb(20,36,55)', }} > <div css={{display: 'flex', flexWrap: 'wrap'}}> <strong css={{minWidth: 70}}>{requestMethod}:</strong> <span css={{marginLeft: 10, whiteSpace: 'pre'}}>{urlMatch}</span> </div> <button css={{ opacity: 0.6, ':hover': {opacity: 1}, fontSize: 13, background: 'rgb(11, 20, 33) !important', }} onClick={() => handleRemoveClick(index)} > Remove </button> </li> ))} </ul> </div> ) } RequestFailUI.displayName = 'RequestFailUI' const getLSDebugValue = <TState,>({ key, state, serialize, }: { key: string state: TState serialize: (data: TState) => string }) => `${key}: ${serialize(state)}` type UseLocalStorageOptions<TState = unknown> = { serialize?: (data: TState) => string deserialize?: (str: string) => TState } function useLocalStorageState<TState>( key: string, defaultValue: TState | (() => TState), { serialize = JSON.stringify, deserialize = JSON.parse, }: UseLocalStorageOptions<TState> = {}, ) { const [state, setState] = React.useState(() => { const valueInLocalStorage = window.localStorage.getItem(key) if (valueInLocalStorage) { return deserialize(valueInLocalStorage) } // can't do typeof because: // https://github.com/microsoft/TypeScript/issues/37663#issuecomment-759728342 return defaultValue instanceof Function ? defaultValue() : defaultValue }) React.useDebugValue({key, state, serialize}, getLSDebugValue) const prevKeyRef = React.useRef(key) React.useEffect(() => { const prevKey = prevKeyRef.current if (prevKey !== key) { window.localStorage.removeItem(prevKey) } prevKeyRef.current = key window.localStorage.setItem(key, serialize(state)) }, [key, state, serialize]) return [state, setState] as const } export {install} /* eslint no-unused-expressions: "off", @typescript-eslint/no-unsafe-assignment: "off", @typescript-eslint/no-unsafe-call: "off", @typescript-eslint/no-unsafe-member-access: "off", */
the_stack
* Separate legend and scrollable legend to reduce package size. */ import * as zrUtil from 'zrender/src/core/util'; import * as graphic from '../../util/graphic'; import * as layoutUtil from '../../util/layout'; import LegendView from './LegendView'; import { LegendSelectorButtonOption } from './LegendModel'; import ExtensionAPI from '../../core/ExtensionAPI'; import GlobalModel from '../../model/Global'; import ScrollableLegendModel, {ScrollableLegendOption} from './ScrollableLegendModel'; import Displayable from 'zrender/src/graphic/Displayable'; import Element from 'zrender/src/Element'; import { ZRRectLike } from '../../util/types'; const Group = graphic.Group; const WH = ['width', 'height'] as const; const XY = ['x', 'y'] as const; interface PageInfo { contentPosition: number[] pageCount: number pageIndex: number pagePrevDataIndex: number pageNextDataIndex: number } interface ItemInfo { /** * Start */ s: number /** * End */ e: number /** * Index */ i: number } type LegendGroup = graphic.Group & { __rectSize: number }; type LegendItemElement = Element & { __legendDataIndex: number }; class ScrollableLegendView extends LegendView { static type = 'legend.scroll' as const; type = ScrollableLegendView.type; newlineDisabled = true; private _containerGroup: LegendGroup; private _controllerGroup: graphic.Group; private _currentIndex: number = 0; private _showController: boolean; init() { super.init(); this.group.add(this._containerGroup = new Group() as LegendGroup); this._containerGroup.add(this.getContentGroup()); this.group.add(this._controllerGroup = new Group()); } /** * @override */ resetInner() { super.resetInner(); this._controllerGroup.removeAll(); this._containerGroup.removeClipPath(); this._containerGroup.__rectSize = null; } /** * @override */ renderInner( itemAlign: ScrollableLegendOption['align'], legendModel: ScrollableLegendModel, ecModel: GlobalModel, api: ExtensionAPI, selector: LegendSelectorButtonOption[], orient: ScrollableLegendOption['orient'], selectorPosition: ScrollableLegendOption['selectorPosition'] ) { const self = this; // Render content items. super.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); const controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length, // e.g., '3/12345' should not overlap with the control arrow button. const pageIconSize = legendModel.get('pageIconSize', true); const pageIconSizeArr: number[] = zrUtil.isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize]; createPageButton('pagePrev', 0); const pageTextStyleModel = legendModel.getModel('pageTextStyle'); controllerGroup.add(new graphic.Text({ name: 'pageText', style: { // Placeholder to calculate a proper layout. text: 'xx/xx', fill: pageTextStyleModel.getTextColor(), font: pageTextStyleModel.getFont(), verticalAlign: 'middle', align: 'center' }, silent: true })); createPageButton('pageNext', 1); function createPageButton(name: string, iconIdx: number) { const pageDataIndexName = (name + 'DataIndex') as 'pagePrevDataIndex' | 'pageNextDataIndex'; const icon = graphic.createIcon( legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], { // Buttons will be created in each render, so we do not need // to worry about avoiding using legendModel kept in scope. onclick: zrUtil.bind( self._pageGo, self, pageDataIndexName, legendModel, api ) }, { x: -pageIconSizeArr[0] / 2, y: -pageIconSizeArr[1] / 2, width: pageIconSizeArr[0], height: pageIconSizeArr[1] } ); icon.name = name; controllerGroup.add(icon); } } /** * @override */ layoutInner( legendModel: ScrollableLegendModel, itemAlign: ScrollableLegendOption['align'], maxSize: { width: number, height: number }, isFirstRender: boolean, selector: LegendSelectorButtonOption[], selectorPosition: ScrollableLegendOption['selectorPosition'] ) { const selectorGroup = this.getSelectorGroup(); const orientIdx = legendModel.getOrient().index; const wh = WH[orientIdx]; const xy = XY[orientIdx]; const hw = WH[1 - orientIdx]; const yx = XY[1 - orientIdx]; selector && layoutUtil.box( // Buttons in selectorGroup always layout horizontally 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true) ); const selectorButtonGap = legendModel.get('selectorButtonGap', true); const selectorRect = selectorGroup.getBoundingRect(); const selectorPos = [-selectorRect.x, -selectorRect.y]; const processMaxSize = zrUtil.clone(maxSize); selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap); const mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy ); if (selector) { if (selectorPosition === 'end') { selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap; } else { const offset = selectorRect[wh] + selectorButtonGap; selectorPos[orientIdx] -= offset; mainRect[xy] -= offset; } mainRect[wh] += selectorRect[wh] + selectorButtonGap; selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2; mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]); mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]); selectorGroup.x = selectorPos[0]; selectorGroup.y = selectorPos[1]; selectorGroup.markRedraw(); } return mainRect; } _layoutContentAndController( legendModel: ScrollableLegendModel, isFirstRender: boolean, maxSize: { width: number, height: number }, orientIdx: 0 | 1, wh: 'width' | 'height', hw: 'width' | 'height', yx: 'x' | 'y', xy: 'y' | 'x' ) { const contentGroup = this.getContentGroup(); const containerGroup = this._containerGroup; const controllerGroup = this._controllerGroup; // Place items in contentGroup. layoutUtil.box( legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height ); layoutUtil.box( // Buttons in controller are layout always horizontally. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true) ); const contentRect = contentGroup.getBoundingRect(); const controllerRect = controllerGroup.getBoundingRect(); const showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0] const contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming. // If first rendering, `contentGroup.position` is [0, 0], which // does not make sense and may cause unexepcted animation if adopted. if (!isFirstRender) { contentPos[orientIdx] = contentGroup[xy]; } // Layout container group based on 0. const containerPos = [0, 0]; const controllerPos = [-controllerRect.x, -controllerRect.y]; const pageButtonGap = zrUtil.retrieve2( legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true) ); // Place containerGroup and controllerGroup and contentGroup. if (showController) { const pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom. if (pageButtonPosition === 'end') { controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh]; } // controller is on the left / top. else { containerPos[orientIdx] += controllerRect[wh] + pageButtonGap; } } // Always align controller to content as 'middle'. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2; contentGroup.setPosition(contentPos); containerGroup.setPosition(containerPos); controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`. // mainRect should not be calculated by `this.group.getBoundingRect()` // for sake of the overflow. const mainRect = {x: 0, y: 0} as ZRRectLike; // Consider content may be overflow (should be clipped). mainRect[wh] = showController ? maxSize[wh] : contentRect[wh]; mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]); containerGroup.__rectSize = maxSize[wh]; if (showController) { const clipShape = {x: 0, y: 0} as graphic.Rect['shape']; clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0); clipShape[hw] = mainRect[hw]; containerGroup.setClipPath(new graphic.Rect({shape: clipShape})); // Consider content may be larger than container, container rect // can not be obtained from `containerGroup.getBoundingRect()`. containerGroup.__rectSize = clipShape[wh]; } else { // Do not remove or ignore controller. Keep them set as placeholders. controllerGroup.eachChild(function (child: Displayable) { child.attr({ invisible: true, silent: true }); }); } // Content translate animation. const pageInfo = this._getPageInfo(legendModel); pageInfo.pageIndex != null && graphic.updateProps( contentGroup, { x: pageInfo.contentPosition[0], y: pageInfo.contentPosition[1] }, // When switch from "show controller" to "not show controller", view should be // updated immediately without animation, otherwise causes weird effect. showController ? legendModel : null ); this._updatePageInfoView(legendModel, pageInfo); return mainRect; } _pageGo( to: 'pagePrevDataIndex' | 'pageNextDataIndex', legendModel: ScrollableLegendModel, api: ExtensionAPI ) { const scrollDataIndex = this._getPageInfo(legendModel)[to]; scrollDataIndex != null && api.dispatchAction({ type: 'legendScroll', scrollDataIndex: scrollDataIndex, legendId: legendModel.id }); } _updatePageInfoView( legendModel: ScrollableLegendModel, pageInfo: PageInfo ) { const controllerGroup = this._controllerGroup; zrUtil.each(['pagePrev', 'pageNext'], function (name) { const key = (name + 'DataIndex') as'pagePrevDataIndex' | 'pageNextDataIndex'; const canJump = pageInfo[key] != null; const icon = controllerGroup.childOfName(name) as graphic.Path; if (icon) { icon.setStyle( 'fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true) ); icon.cursor = canJump ? 'pointer' : 'default'; } }); const pageText = controllerGroup.childOfName('pageText') as graphic.Text; const pageFormatter = legendModel.get('pageFormatter'); const pageIndex = pageInfo.pageIndex; const current = pageIndex != null ? pageIndex + 1 : 0; const total = pageInfo.pageCount; pageText && pageFormatter && pageText.setStyle( 'text', zrUtil.isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '') .replace('{total}', total == null ? '' : total + '') : pageFormatter({current: current, total: total}) ); } /** * contentPosition: Array.<number>, null when data item not found. * pageIndex: number, null when data item not found. * pageCount: number, always be a number, can be 0. * pagePrevDataIndex: number, null when no previous page. * pageNextDataIndex: number, null when no next page. * } */ _getPageInfo(legendModel: ScrollableLegendModel): PageInfo { const scrollDataIndex = legendModel.get('scrollDataIndex', true); const contentGroup = this.getContentGroup(); const containerRectSize = this._containerGroup.__rectSize; const orientIdx = legendModel.getOrient().index; const wh = WH[orientIdx]; const xy = XY[orientIdx]; const targetItemIndex = this._findTargetItemIndex(scrollDataIndex); const children = contentGroup.children(); const targetItem = children[targetItemIndex]; const itemCount = children.length; const pCount = !itemCount ? 0 : 1; const result: PageInfo = { contentPosition: [contentGroup.x, contentGroup.y], pageCount: pCount, pageIndex: pCount - 1, pagePrevDataIndex: null, pageNextDataIndex: null }; if (!targetItem) { return result; } const targetItemInfo = getItemInfo(targetItem); result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy: // (1) Always align based on the left/top most item. // (2) It is user-friendly that the last item shown in the // current window is shown at the begining of next window. // Otherwise if half of the last item is cut by the window, // it will have no chance to display entirely. // (3) Consider that item size probably be different, we // have calculate pageIndex by size rather than item index, // and we can not get page index directly by division. // (4) The window is to narrow to contain more than // one item, we should make sure that the page can be fliped. for (let i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i ) { currItemInfo = getItemInfo(children[i]); if ( // Half of the last item is out of the window. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize) // If the current item does not intersect with the window, the new page // can be started at the current item or the last item. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) ) { if (winEndItemInfo.i > winStartItemInfo.i) { winStartItemInfo = winEndItemInfo; } else { // e.g., when page size is smaller than item size. winStartItemInfo = currItemInfo; } if (winStartItemInfo) { if (result.pageNextDataIndex == null) { result.pageNextDataIndex = winStartItemInfo.i; } ++result.pageCount; } } winEndItemInfo = currItemInfo; } for (let i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i ) { currItemInfo = getItemInfo(children[i]); if ( // If the the end item does not intersect with the window started // from the current item, a page can be settled. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) // e.g., when page size is smaller than item size. && winStartItemInfo.i < winEndItemInfo.i ) { winEndItemInfo = winStartItemInfo; if (result.pagePrevDataIndex == null) { result.pagePrevDataIndex = winStartItemInfo.i; } ++result.pageCount; ++result.pageIndex; } winStartItemInfo = currItemInfo; } return result; function getItemInfo(el: Element): ItemInfo { if (el) { const itemRect = el.getBoundingRect(); const start = itemRect[xy] + el[xy]; return { s: start, e: start + itemRect[wh], i: (el as LegendItemElement).__legendDataIndex }; } } function intersect(itemInfo: ItemInfo, winStart: number) { return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize; } } _findTargetItemIndex(targetDataIndex: number) { if (!this._showController) { return 0; } let index; const contentGroup = this.getContentGroup(); let defaultIndex: number; contentGroup.eachChild(function (child, idx) { const legendDataIdx = (child as LegendItemElement).__legendDataIndex; // FIXME // If the given targetDataIndex (from model) is illegal, // we use defaultIndex. But the index on the legend model and // action payload is still illegal. That case will not be // changed until some scenario requires. if (defaultIndex == null && legendDataIdx != null) { defaultIndex = idx; } if (legendDataIdx === targetDataIndex) { index = idx; } }); return index != null ? index : defaultIndex; } } export default ScrollableLegendView;
the_stack
import {Node, Statement} from 'shift-ast'; import {Declaration, Reference, Variable} from 'shift-scope'; import {GlobalState} from './global-state'; import {matches} from './misc/query'; import { AsyncReplacer, Constructor, NodesWithStatements, Replacer, SelectorOrNode, SimpleIdentifier, SimpleIdentifierOwner, } from './misc/types'; import {innerBodyStatements, isNodeWithStatements} from './misc/util'; import {RefactorSession} from './refactor-session'; type Plugin = (instance: RefactorSessionChainable) => any; /** * Plugin interface * * @internal */ export interface Pluggable { /** * @internal */ plugins: Plugin[]; /** * @internal */ with<S extends Constructor<any> & Pluggable, T extends Plugin>(this: S, plugin: T): S & Pluggable; } /** * Refactor query objects can take a string, a single node, or a list of nodes as input */ export type RefactorQueryInput = string | Node | Node[]; /** * Necessary typing for RefactorSessionChainable static methods * * @public */ export interface RefactorSessionChainable extends Pluggable {} /** * The Chainable Refactor interface * * @remarks * * This is not intended to be instantiated directly. Use refactor() to create your instances. * * @public */ export class RefactorSessionChainable { session: RefactorSession; static plugins: Plugin[] = []; constructor(session: RefactorSession) { this.session = session; const classConstructor = this.constructor as typeof RefactorSessionChainable; classConstructor.plugins.forEach(plugin => { Object.assign(this, plugin(this)); }); } /** * @internal */ static with<S extends Constructor<any> & Pluggable, T extends Plugin>(this: S, plugin: T) { const currentPlugins = this.plugins; const BaseWithPlugins: Pluggable = class extends this { static plugins = currentPlugins.concat(plugin); static with = RefactorSessionChainable.with; // static create = RefactorSessionChainable.create; }; return BaseWithPlugins as S & typeof BaseWithPlugins & Constructor<ReturnType<T>>; } /** * @internal */ static create(session: RefactorSession): RefactorQueryAPI { const Klass = this; const chainable = new Klass(session); const prototype = Object.getPrototypeOf(chainable); const $query = function(selector: RefactorQueryInput): RefactorQueryAPI { const subSession = session.subSession(selector); return Klass.create(subSession); }; const hybridObject = Object.assign($query, chainable); Object.setPrototypeOf(hybridObject, prototype); Object.defineProperty(hybridObject, 'length', { get() { return session.length; }, }); return hybridObject; } get root(): Node { return this.session.root; } get length(): number { return this.session.length; } get nodes(): Node[] { return this.session.nodes; } /** * Get selected node at index. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * someFunction('first string', 'second string', 'third string'); * ` * $script = refactor(src); * * const thirdString = $script('LiteralStringExpression').get(2); * * ``` * * @assert * * ```js * assert.equal(thirdString.value, 'third string'); * ``` * */ get(index: number): Node { return this.nodes[index]; } /** * Rename all references to the first selected node to the passed name. * * @remarks * * Uses the selected node as the target, but affects the global state. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * const myVariable = 2; * myVariable++; * const other = myVariable; * function unrelated(myVariable) { return myVariable } * ` * $script = refactor(src); * * $script('VariableDeclarator[binding.name="myVariable"]').rename('newName'); * * ``` * * @assert * * ```js * assert.treesEqual($script, 'const newName = 2;newName++;const other = newName;function unrelated(myVariable) { return myVariable }'); * ``` * */ rename(newName: string) { this.session.rename(this.raw(), newName); return this; } /** * Delete nodes * * @example * * ```js * const { refactor } = require('shift-refactor'); * * $script = refactor('foo();bar();'); * * $script('ExpressionStatement[expression.callee.name="foo"]').delete(); * * ``` * * @assert * * ```js * assert.treesEqual($script, 'bar();'); * ``` * */ delete() { this.session.delete(this.nodes); return this; } /** * Replace selected node with the result of the replacer parameter * * @example * * ```js * const { refactor } = require('shift-refactor'); * const Shift = require('shift-ast'); * * const src = ` * function sum(a,b) { return a + b } * function difference(a,b) {return a - b} * ` * * $script = refactor(src); * * $script('FunctionDeclaration').replace(node => new Shift.VariableDeclarationStatement({ * declaration: new Shift.VariableDeclaration({ * kind: 'const', * declarators: [ * new Shift.VariableDeclarator({ * binding: node.name, * init: new Shift.ArrowExpression({ * isAsync: false, * params: node.params, * body: node.body * }) * }) * ] * }) * })) * * ``` * @assert * * ```js * assert.treesEqual($script, 'const sum = (a,b) => { return a + b }; const difference = (a,b) => { return a - b };') * ``` * * @public */ replace(replacer: Replacer): RefactorSessionChainable { this.session.replace(this.nodes, replacer); return this; } /** * Async version of .replace() that supports asynchronous replacer functions * * @example * * ```js * const { refactor } = require('shift-refactor'); * * $script = refactor('var a = "hello";'); * * async function work() { * await $script('LiteralStringExpression').replaceAsync( * (node) => Promise.resolve(`"goodbye"`) * ) * } * * ``` * @assert * * ```js * work().then(_ => assert.treesEqual($script, 'var a = "goodbye";')); * ``` * * @public */ replaceAsync(replacer: AsyncReplacer) { return this.session.replaceAsync(this.nodes, replacer); } /** * Recursively replaces child nodes until no nodes have been replaced. * * @example * * ```js * const { refactor } = require('shift-refactor'); * const Shift = require('shift-ast'); * * const src = ` * 1 + 2 + 3 * ` * * $script = refactor(src); * * $script.replaceChildren( * 'BinaryExpression[left.type=LiteralNumericExpression][right.type=LiteralNumericExpression]', * (node) => new Shift.LiteralNumericExpression({value: node.left.value + node.right.value}) * ); * ``` * * @assert * * ```js * assert.treesEqual($script, '6;'); * ``` * * @public */ replaceChildren(query: SelectorOrNode, replacer: Replacer): RefactorSessionChainable { this.session.replaceRecursive(query, replacer); return this; } /** * Return the type of the first selected node * * @example * * ```js * const { refactor } = require('shift-refactor'); * const Shift = require('shift-ast'); * * const src = ` * myFunction(); * ` * * $script = refactor(src); * * const type = $script('CallExpression').type(); * ``` * * @assert * * ```js * assert.equal(type, 'CallExpression'); * ``` * * @public */ type(): string { return this.raw().type; } /** * Returns the first selected node. Optionally takes a selector and returns the first node that matches the selector. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * func1(); * func2(); * func3(); * ` * * $script = refactor(src); * * const func1CallExpression = $script('CallExpression').first(); * ``` * * @assert * * ```js * assert.equal(func1CallExpression.raw(), $script.root.statements[0].expression); * ``` * * @public */ first(selector?: string): RefactorSessionChainable { if (selector) { return this.find(node => matches(node, selector)).first(); } return this.$(this.session.first()); } /** * Returns the raw Shift node for the first selected node. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * const a = 2; * ` * * $script = refactor(src); * * const declStatement = $script('VariableDeclarationStatement').raw(); * ``` * * @assert * * ```js * assert(declStatement === $script.root.statements[0]); * ``` * * @public */ raw(): Node { return this.nodes[0]; } /** * Retrieve parent node(s) * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * var a = 1, b = 2; * ` * * $script = refactor(src); * const declarators = $script('VariableDeclarator'); * const declaration = declarators.parents(); * ``` * * @assert * * ```js * assert.equal(declaration.length, 1); * assert.equal(declarators.length, 2); * ``` * * @public */ parents() { return this.$(this.session.findParents(this.nodes)); } /** * Retrieve the names of the first selected node. Returns undefined for nodes without names. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * var first = 1, second = 2; * ` * * $script = refactor(src); * const firstName = $script('BindingIdentifier[name="first"]').nameString(); * ``` * * @assert * * ```js * assert.equal(firstName, 'first'); * ``` * * @public */ nameString(): string { const node = this.raw(); if (!('name' in node)) return ''; const nameNode = node.name; if (!nameNode) return ''; if (typeof nameNode === 'string') return nameNode; switch (nameNode.type) { case 'BindingIdentifier': case 'IdentifierExpression': return nameNode.name; case 'StaticPropertyName': return nameNode.value; case 'ComputedPropertyName': throw new Error('can not return names of computed properties'); } } // TODO appendInto prependInto to auto-insert into body blocks /** * Inserts the result of `replacer` before the selected statement. * * @param replacer - `string` | Shift `Node` | `(node) => string | Node`: Replaces a node with the result of the replacer parameter * * @remarks * * Only works on Statement nodes. * * @example * * ```js * const { refactor } = require('shift-refactor'); * const Shift = require('shift-ast'); * * const src = ` * var message = "Hello"; * console.log(message); * ` * * $script = refactor(src); * * $script('ExpressionStatement[expression.type="CallExpression"]').prepend(new Shift.DebuggerStatement()); * ``` * * @assert * * ```js * assert.treesEqual($script, 'var message = "Hello";debugger;console.log(message)'); * ``` * * @public */ prepend(replacer: Replacer): RefactorSessionChainable { this.session.prepend(this.nodes, replacer); return this; } /** * Inserts the result of `replacer` after the selected statement. * * @param replacer - `string` | Shift `Node` | `(node) => string | Node`: Replaces a node with the result of the replacer parameter * * @remarks * * Only works on Statement nodes. * * @example * * ```js * const { refactor } = require('shift-refactor'); * const Shift = require('shift-ast'); * * const src = ` * var message = "Hello"; * console.log(message); * ` * * $script = refactor(src); * * $script('LiteralStringExpression[value="Hello"]').closest(':statement').append('debugger'); * ``` * * @assert * * ```js * assert.treesEqual($script, 'var message = "Hello";debugger;console.log(message)'); * ``` * * @public */ append(replacer: Replacer): RefactorSessionChainable { this.session.append(this.nodes, replacer); return this; } /** * Sub-query from selected nodes * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * let a = 1; * function myFunction() { * let b = 2, c = 3; * } * ` * * $script = refactor(src); * * const funcDecl = $script('FunctionDeclaration[name.name="myFunction"]'); * const innerIdentifiers = funcDecl.$('BindingIdentifier'); * // innerIdentifiers.nodes: myFunction, b, c (note: does not include a) * * ``` * * @assert * * ```js * assert.equal(innerIdentifiers.length, 3); * ``` * * @public */ $(queryOrNodes: SelectorOrNode) { return RefactorSessionChainable.create(this.session.subSession(queryOrNodes)); } /** * Sub-query from selected nodes * * @remarks * * synonym for .$() * * @public */ query(selector: string | string[]) { return this.$(this.session.query(selector)); } /** * Iterate over selected nodes * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * let a = [1,2,3,4]; * ` * * $script = refactor(src); * * $script('LiteralNumericExpression').forEach(node => node.value *= 2); * ``` * * @assert * * ```js * assert.treesEqual($script, 'let a = [2,4,6,8]'); * ``` * * @public */ forEach(iterator: (node: any, i?: number) => any): RefactorSessionChainable { this.nodes.forEach(iterator); return this; } /** * Transform selected nodes via passed iterator * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * let doc = window.document; * function addListener(event, fn) { * doc.addEventListener(event, fn); * } * ` * * $script = refactor(src); * * const values = $script('BindingIdentifier').map(node => node.name); * ``` * * @assert * * ```js * assert.deepEqual(values, ['doc', 'addListener', 'event', 'fn']); * ``` * * @public */ map(iterator: (node: any, i?: number) => any): any[] { return this.nodes.map(iterator); } /** * Filter selected nodes via passed iterator * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * let doc = window.document; * function addListener(event, fn) { * doc.addEventListener(event, fn); * } * ` * * $script = refactor(src); * * const values = $script('BindingIdentifier').filter(node => node.name === 'doc'); * ``` * * @assert * * ```js * assert.deepEqual(values.nodes, [{type: "BindingIdentifier", name:"doc"}]); * ``` * * @public */ filter(iterator: (node: any, i?: number) => any): RefactorSessionChainable { return this.$(this.nodes.filter(iterator)); } /** * Finds node via the passed iterator iterator * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * const myMessage = "He" + "llo" + " " + "World"; * ` * * $script = refactor(src); * * $script('LiteralStringExpression') * .find(node => node.value === 'World') * .replace('"Reader"'); * ``` * * @assert * * ```js * assert.treesEqual($script, 'const myMessage = "He" + "llo" + " " + "Reader";'); * ``` * * @public */ find(iterator: (node: any, i?: number) => any) { return this.$(this.nodes.find(iterator) || []); } /** * * Finds an expression that closely matches the passed source. * * @remarks * * Used for selecting nodes by source pattern instead of query. The passed source is parsed as a Script and the first statement is expected to be an ExpressionStatement.Matching is done by matching the properties of the parsed statement, ignoring additional properties/nodes in the source tree. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * const a = someFunction(paramOther); * const b = targetFunction(param1, param2); * ` * * $script = refactor(src); * * const targetCallExpression = $script.findMatchingExpression('targetFunction(param1, param2)'); * ``` * * @assert * * ```js * assert.equal(targetCallExpression.length, 1); * ``` * * @public */ findMatchingExpression(sampleSrc: string) { return this.$(this.session.findMatchingExpression(sampleSrc)); } /** * Finds a statement that matches the passed source. * * @remarks * * Used for selecting nodes by source pattern vs query. The passed source is parsed as a Script and the first statement alone is used as the statement to match. Matching is done by matching the properties of the parsed statement, ignoring additional properties/nodes in the source tree. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * function someFunction(a,b) { * var innerVariable = "Lots of stuff in here"; * foo(a); * bar(b); * } * ` * * $script = refactor(src); * * const targetDeclaration = $script.findMatchingStatement('function someFunction(a,b){}'); * ``` * * @assert * * ```js * assert.equal(targetDeclaration.length, 1); * ``` * * @public */ findMatchingStatement(sampleSrc: string) { return this.$(this.session.findMatchingStatement(sampleSrc)); } /** * Finds and selects a single node, throwing an error if zero or more than one is found. * * @remarks * * This is useful for when you want to target a single node but aren't sure how specific your query needs to be to target that node and only that node. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * let outerVariable = 1; * function someFunction(a,b) { * let innerVariable = 2; * } * ` * * $script = refactor(src); * * // This would throw, because there are multiple VariableDeclarators * // $script.findOne('VariableDeclarator'); * * // This won't throw because there is only one within the only FunctionDeclaration. * const innerVariableDecl = $script('FunctionDeclaration').findOne('VariableDeclarator'); * ``` * * @assert * * ```js * assert.equal(innerVariableDecl.length, 1); * assert.throws(() => { * $script.findOne('VariableDeclarator'); * }) * ``` * * @public */ findOne(selectorOrNode: string) { return this.$(this.session.findOne(selectorOrNode)); } /** * Finds the references for the selected Identifier nodes. * * @remarks * * Returns a list of Reference objects for each selected node, not a shift-refactor query object. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * let myVar = 1; * function someFunction(a,b) { * myVar++; * return myVar; * } * ` * * $script = refactor(src); * * const refs = $script('BindingIdentifier[name="myVar"]').references(); * * ``` * * @assert * * ```js * assert.equal(refs.length, 3); * ``` * * @public */ references(): Reference[] { return this.nodes.flatMap(node => this.session.globalSession.findReferences(node as SimpleIdentifier | SimpleIdentifierOwner), ); } /** * Finds the declaration for the selected Identifier nodes. * * @remarks * * Returns a list of Declaration objects for each selected node, not a shift-refactor query object. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * const myVariable = 2, otherVar = 3; * console.log(myVariable, otherVar); * ` * * $script = refactor(src); * * // selects the parameters to console.log() and finds their declarations * const decls = $script('CallExpression[callee.object.name="console"][callee.property="log"] > .arguments').declarations(); * * ``` * * @assert * * ```js * assert.equal(decls.length, 2); * ``` * * @public */ declarations(): Declaration[] { return this.nodes.flatMap(node => this.session.globalSession.findDeclarations(node as SimpleIdentifier | SimpleIdentifierOwner), ); } /** * Finds the closest parent node that matches the passed selector. * * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * function someFunction() { * interestingFunction(); * } * function otherFunction() { * interestingFunction(); * } * ` * * $script = refactor(src); * * // finds all functions that call `interestingFunction` * const fnDecls = $script('CallExpression[callee.name="interestingFunction"]').closest('FunctionDeclaration'); * * ``` * * @assert * * ```js * assert.equal(fnDecls.length, 2); * ``` * * @public */ closest(closestSelector: string) { return this.$(this.session.closest(this.nodes, closestSelector)); } /** * Returns the selects the statements for the selected nodes. Note: it will "uplevel" the inner statements of nodes with a `.body` property. * * Does nothing for nodes that have no statements property. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * console.log(1); * console.log(2); * ` * * $script = refactor(src); * * const rootStatements = $script.statements(); * * ``` * * @assert * * ```js * assert.equal(rootStatements.length, 2); * ``` * * @public */ statements() { const statements: Statement[] = this.nodes .map(innerBodyStatements) .filter(isNodeWithStatements) .flatMap((node: NodesWithStatements) => node.statements); return this.$(statements); } /** * Looks up the Variable from the passed identifier node * * @remarks * * Returns `Variable` objects from shift-scope, that contain all the references and declarations for a program variable. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * const someVariable = 2, other = 3; * someVariable++; * function thisIsAVariabletoo(same, as, these) {} * ` * * $script = refactor(src); * * // Finds all variables declared within a program * const variables = $script('BindingIdentifier').lookupVariable(); * * ``` * * @assert * * ```js * assert.equal(variables.length, 6); * ``` * * @public */ lookupVariable(): Variable[] { return this.nodes.map(node => this.session.globalSession.lookupVariable(node as SimpleIdentifierOwner | SimpleIdentifier), ); } /** * Looks up Variables by name. * * @remarks * * There may be multiple across a program. Variable lookup operates on the global program state. This method ignores selected nodes. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const src = ` * const someVariable = 2, other = 3; * ` * * $script = refactor(src); * * const variables = $script.lookupVariableByName('someVariable'); * ``` * * @assert * * ```js * assert.equal(variables.length, 1); * assert.equal(variables[0].name, 'someVariable'); * ``` * * @public */ lookupVariableByName(name: string): Variable[] { return this.session.globalSession.lookupVariableByName(name); } /** * Generates JavaScript source for the first selected node. * * @example * * * ```js * * const { refactor } = require('shift-refactor'); * const Shift = require('shift-ast'); * * const src = ` * window.addEventListener('load', () => { * lotsOfWork(); * }) * ` * * $script = refactor(src); * * $script("CallExpression[callee.property='addEventListener'] > ArrowExpression") * .replace(new Shift.IdentifierExpression({name: 'myListener'})); * * console.log($script.print()); * * ``` * * @assert * * ```js * assert.treesEqual($script, "window.addEventListener('load', myListener)"); * ``` * * @public */ print() { return this.session.print(); } /** * Generates JavaScript source for the first selected node. * * @example * * * ```js * * const { refactor } = require('shift-refactor'); * * const src = ` * for (var i=1; i < 101; i++){ * if (i % 15 == 0) console.log("FizzBuzz"); * else if (i % 3 == 0) console.log("Fizz"); * else if (i % 5 == 0) console.log("Buzz"); * else console.log(i); * } * ` * * $script = refactor(src); * * const strings = $script("LiteralStringExpression") * * console.log(strings.codegen()); * * ``` * * @assert * * ```js * assert.equal(strings.length,3); * ``` * * @public */ codegen() { return this.nodes.map(node => this.session.print(node)); } /** * `console.log()`s the selected nodes. Useful for inserting into a chain to see what * nodes you are working with. * * @example * * * ```js * * const { refactor } = require('shift-refactor'); * * const src = ` * let a = 1, b = 2; * ` * * $script = refactor(src); * * $script("VariableDeclarator").logOut().delete(); * ``` * * @assert * * ```js * assert.treesEqual($script,''); * ``` * * @public */ logOut() { console.log(this.nodes); return this; } /** * JSON-ifies the current selected nodes. * * @example * * * ```js * * const { refactor } = require('shift-refactor'); * * const src = ` * (function(){ console.log("Hey")}()) * ` * * $script = refactor(src); * * const json = $script.toJSON(); * ``` * * @assert * * ```js * assert.deepEqual(json,JSON.stringify([_parse('(function(){ console.log("Hey")}())')])); * ``` * * @public */ toJSON() { return JSON.stringify(this.nodes); } } /** * Refactor query object type */ export type RefactorQueryAPI = { (selectorOrNode: RefactorQueryInput): RefactorQueryAPI; } & InstanceType<typeof RefactorSessionChainable>; /** * Create a refactor query object. * * @remarks * * This function assumes that it is being passed complete JavaScript source or a *root* AST node (Script or Module) so that it can create and maintain global state. * * @example * * ```js * const { refactor } = require('shift-refactor'); * * const $script = refactor(`/* JavaScript Source *\/`); * ``` * * @assert * * ```js * assert.treesEqual($script, `/* JavaScript Source *\/`); * ``` * * @public */ export function refactor(input: string | Node, ...plugins: Plugin[]): RefactorQueryAPI { const globalSession = new GlobalState(input); const refactorSession = new RefactorSession(globalSession.root, globalSession); if (plugins) return plugins .reduce((chainable, plugin) => chainable.with(plugin), RefactorSessionChainable) .create(refactorSession) as any; return RefactorSessionChainable.create(refactorSession); }
the_stack
import * as chai from 'chai'; import BigNumber from 'bignumber.js'; import * as Web3 from 'web3'; import ethUtil = require('ethereumjs-util'); import { chaiSetup } from './utils/chai_setup'; import { Artifacts } from '../../util/artifacts'; import assertRevert from '../helpers/assertRevert'; import expectThrow from '../helpers/expectThrow'; import eventByName from '../helpers/eventByName'; import latestTime from '../helpers/latestTime'; import increaseTime from '../helpers/increaseTime'; import { advanceBlock } from '../helpers/advanceToBlock'; import * as Bluebird from 'bluebird'; import includes = require('lodash/includes'); import find = require('lodash/find'); import { duration } from '../helpers/increaseTime'; chaiSetup.configure(); const expect = chai.expect; const { LicenseCoreTest, AffiliateProgram } = new Artifacts(artifacts); const LicenseCore = LicenseCoreTest; chai.should(); const web3: Web3 = (global as any).web3; const web3Eth: any = Bluebird.promisifyAll(web3.eth); contract('AffiliateProgram', (accounts: string[]) => { let token: any = null; let affiliate: any = null; const creator = accounts[0]; const user1 = accounts[1]; const user2 = accounts[2]; const user3 = accounts[3]; const user4 = accounts[4]; const user5 = accounts[5]; const affiliate1 = accounts[6]; const affiliate2 = accounts[7]; const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; const firstProduct = { id: 1, price: 1000, initialInventory: 2, supply: 2, interval: 0 }; const secondProduct = { id: 2, price: 2000, initialInventory: 3, supply: 5, interval: duration.weeks(4) }; const thirdProduct = { id: 3, price: 3000, initialInventory: 5, supply: 10, interval: duration.weeks(4) }; const purchase = async (product: any, user: any, opts: any = {}) => { const affiliate = opts.affiliate || ZERO_ADDRESS; const { logs } = await token.purchase(product.id, 1, user, affiliate, { value: product.price, gasPrice: 0 }); const issuedEvent = eventByName(logs, 'LicenseIssued'); return issuedEvent.args.licenseId; }; beforeEach(async () => { token = await LicenseCore.new({ from: creator }); await token.setCEO(creator, { from: creator }); await token.setCFO(creator, { from: creator }); await token.setCOO(creator, { from: creator }); await token.createProduct( firstProduct.id, firstProduct.price, firstProduct.initialInventory, firstProduct.supply, firstProduct.interval, { from: creator } ); await token.createProduct( secondProduct.id, secondProduct.price, secondProduct.initialInventory, secondProduct.supply, secondProduct.interval, { from: creator } ); await token.unpause({ from: creator }); affiliate = await AffiliateProgram.new(token.address, { from: creator }); await token.setAffiliateProgramAddress(affiliate.address, { from: creator }); await affiliate.unpause({ from: creator }); }); describe('in AffiliateProgram', async () => { it('should have a storeAddress', async () => { (await affiliate.storeAddress()).should.be.eq(token.address); }); it('should report that it isAffiliateProgram', async () => { (await affiliate.isAffiliateProgram()).should.be.true(); }); describe('when setting the baselineRate', async () => { describe('when the owner sets a new rate', async () => { let event: any; beforeEach(async () => { (await affiliate.baselineRate()).should.be.bignumber.equal(0); const { logs } = await affiliate.setBaselineRate(1000, { from: creator }); event = eventByName(logs, 'RateChanged'); }); it('the owner should set a new rate', async () => { (await affiliate.baselineRate()).should.be.bignumber.equal(1000); }); it('should emit a RateChanged event', async () => { event.args.rate.should.be.bignumber.equal(0); event.args.amount.should.be.bignumber.equal(1000); }); }); it('the owner should not be able to set it too high', async () => { await assertRevert(affiliate.setBaselineRate(5100, { from: creator })); }); it('a random user should not be able to change the rate', async () => { await assertRevert(affiliate.setBaselineRate(1000, { from: user1 })); }); }); describe('when setting the maximumRate', async () => { describe('when the owner is setting the new rate', async () => { let event: any; beforeEach(async () => { (await affiliate.maximumRate()).should.be.bignumber.equal(5000); const { logs } = await affiliate.setMaximumRate(1000, { from: creator }); event = eventByName(logs, 'RateChanged'); }); it('should allow the owner to set a new rate', async () => { (await affiliate.maximumRate()).should.be.bignumber.equal(1000); }); it('should emit a RateChanged event', async () => { event.args.rate.should.be.bignumber.equal(1); event.args.amount.should.be.bignumber.equal(1000); }); }); it('should not allow the owner to set a new rate too high', async () => { await assertRevert(affiliate.setMaximumRate(5100, { from: creator })); }); it('should not allow a rando to change the maximumRate', async () => { await assertRevert(affiliate.setMaximumRate(1000, { from: user1 })); }); }); describe('when whitelisting affiliates', async () => { describe('when the owner is whitelisting', async () => { let event: any; beforeEach(async () => { (await affiliate.whitelistRates( affiliate1 )).should.be.bignumber.equal(0); let { logs } = await affiliate.whitelist(affiliate1, 2500, { from: creator }); event = eventByName(logs, 'Whitelisted'); }); it('should allow the owner to whitelist affiliates', async () => { (await affiliate.whitelistRates( affiliate1 )).should.be.bignumber.equal(2500); }); it('should emit a Whitelisted event', async () => { event.args.affiliate.should.be.equal(affiliate1); event.args.amount.should.be.bignumber.equal(2500); }); }); it('should not allow the owner to whitelist with too high of a rate', async () => { await assertRevert( affiliate.whitelist(affiliate1, 5100, { from: creator }) ); }); it('should not allow a rando to whitelist', async () => { await assertRevert( affiliate.whitelist(affiliate1, 1000, { from: user1 }) ); }); }); describe('when using rateFor', async () => { describe('when affiliates are whitelisted', async () => { it('should return the correct rate for affiliates', async () => { (await affiliate.rateFor( affiliate1, 0, 0, 0 )).should.be.bignumber.equal(0); await affiliate.whitelist(affiliate1, 2500, { from: creator }); (await affiliate.rateFor( affiliate1, 0, 0, 0 )).should.be.bignumber.equal(2500); }); describe('if the maximumRate is lower than the whitelisted rate', async () => { beforeEach(async () => { await affiliate.whitelist(affiliate1, 2500, { from: creator }); await affiliate.setMaximumRate(1000, { from: creator }); }); it('should return the maximumRate', async () => { (await affiliate.rateFor( affiliate1, 0, 0, 0 )).should.be.bignumber.equal(1000); }); }); describe('when an affiliate is blacklisted', async () => { beforeEach(async () => { await affiliate.whitelist(affiliate1, 1, { from: creator }); }); it('should return zero for that affiliate', async () => { (await affiliate.rateFor( affiliate1, 0, 0, 0 )).should.be.bignumber.equal(0); }); }); }); }); describe('when calculating cuts for an affiliate', async () => { const priceTests = [ { price: web3.toWei(1, 'ether'), rate: 1000, actual: web3.toWei(0.1, 'ether') }, { price: web3.toWei(0.5, 'ether'), rate: 2500, actual: web3.toWei(0.125, 'ether') }, { price: 1000, rate: 2, actual: 0 }, { price: 1234, rate: 123, actual: 15 }, { price: 1234, rate: 129, actual: 15 } ]; priceTests.forEach(test => { it(`should calculate the correct cut for price ${ test.price } at rate ${test.rate / 100}%`, async () => { await affiliate.whitelist(affiliate1, test.rate, { from: creator }); const givenCut = await affiliate.cutFor( affiliate1, 0, 0, test.price, { from: creator } ); givenCut.should.be.bignumber.equal(new BigNumber(test.actual)); }); }); }); describe('when making deposits for affiliates', async () => { const purchaseId = 1; const valueAmount = 12345; describe('in a valid way', async () => { let logs: any; beforeEach(async () => { const result = await affiliate.credit(affiliate1, purchaseId, { from: creator, value: valueAmount }); logs = result.logs; }); it('should add to the balance of that affiliate', async () => { (await affiliate.balances(affiliate1)).should.be.bignumber.equal( valueAmount ); await affiliate.credit(affiliate1, purchaseId, { from: creator, value: valueAmount }); (await affiliate.balances(affiliate1)).should.be.bignumber.equal( valueAmount * 2 ); }); it('should record the lastDeposit for that affiliate', async () => { const block = await web3Eth.getBlockAsync('latest'); const lastDepositTime = await affiliate.lastDepositTimes(affiliate1); lastDepositTime.should.be.bignumber.equal(block.timestamp); }); it('should record the lastDeposit for the contract overall', async () => { const block = await web3Eth.getBlockAsync('latest'); const lastDepositTime = await affiliate.lastDepositTime(); lastDepositTime.should.be.bignumber.equal(block.timestamp); }); it('emit an AffiliateCredit', async () => { let event = eventByName(logs, 'AffiliateCredit'); event.args.affiliate.should.be.equal(affiliate1); event.args.productId.should.be.bignumber.equal(purchaseId); event.args.amount.should.be.bignumber.equal(valueAmount); }); }); it('should not allow deposits when paused', async () => { await affiliate.pause({ from: creator }); await assertRevert( affiliate.credit(affiliate1, purchaseId, { from: creator, value: valueAmount }) ); }); it('should not allow deposits from a rando', async () => { await assertRevert( affiliate.credit(affiliate1, purchaseId, { from: user1, value: valueAmount }) ); }); it('should not allow deposits without a value', async () => { await assertRevert( affiliate.credit(affiliate1, purchaseId, { from: creator, value: 0 }) ); }); it('should not allow deposits to an affiliate with a zero address', async () => { await assertRevert( affiliate.credit(ZERO_ADDRESS, purchaseId, { from: creator, value: valueAmount }) ); }); }); describe('when withdrawing', async () => { describe('and the affiliate has a balance', async () => { const valueAf1 = 10000; const valueAf2 = 30000; const purchaseId1 = 1; const purchaseId2 = 2; let affiliateContractBalance: any; let originalAccountBalance1: any; let originalAccountBalance2: any; beforeEach(async () => { await affiliate.credit(affiliate1, purchaseId1, { from: creator, value: valueAf1 }); await affiliate.credit(affiliate2, purchaseId2, { from: creator, value: valueAf2 }); // the affiliate balances are credited (await affiliate.balances(affiliate1)).should.be.bignumber.equal( valueAf1 ); (await affiliate.balances(affiliate2)).should.be.bignumber.equal( valueAf2 ); // and the contract actually holds the ETH balance affiliateContractBalance = await web3Eth.getBalanceAsync( affiliate.address ); affiliateContractBalance.should.be.bignumber.equal( valueAf1 + valueAf2 ); originalAccountBalance1 = await web3Eth.getBalanceAsync(affiliate1); originalAccountBalance2 = await web3Eth.getBalanceAsync(affiliate2); }); describe('and the affiliate withdraws', async () => { beforeEach(async () => { await affiliate.withdraw({ from: affiliate1, gasPrice: 0 }); }); it('should clear the balance', async () => { (await affiliate.balances(affiliate1)).should.be.bignumber.equal(0); }); it('should give the affiliate ETH', async () => { const newBalance = await web3Eth.getBalanceAsync(affiliate1); newBalance.should.be.bignumber.equal( originalAccountBalance1.plus(valueAf1) ); }); it('should deduct the amount from the affiliate contract balance', async () => { const newAffiliateContractBalance = await web3Eth.getBalanceAsync( affiliate.address ); newAffiliateContractBalance.should.be.bignumber.equal( affiliateContractBalance.minus(valueAf1) ); }); it('should not affect another account', async () => { (await affiliate.balances(affiliate2)).should.be.bignumber.equal( valueAf2 ); (await web3Eth.getBalanceAsync( affiliate2 )).should.be.bignumber.equal(originalAccountBalance2); }); it('should not allow a withdraw when there is a zero balance', async () => { await assertRevert( affiliate.withdraw({ from: affiliate1 }) ); }); }); describe('and it is paused', async () => { beforeEach(async () => { await affiliate.pause({ from: creator }); }); it('should not work', async () => { await assertRevert( affiliate.withdraw({ from: affiliate1 }) ); }); }); describe('when the owner is withdrawing', async () => { it('should not be allowed before the expiry time', async () => { await assertRevert( affiliate.withdrawFrom(affiliate1, creator, { from: creator }) ); }); describe('and the expiry time has passed', async () => { beforeEach(async () => { await increaseTime(60 * 60 * 24 * 31); }); describe('and the creator withdraws', async () => { let creatorBalance: any; beforeEach(async () => { creatorBalance = await web3Eth.getBalanceAsync(creator); await affiliate.withdrawFrom(affiliate1, creator, { from: creator, gasPrice: 0 }); }); it('should clear the balance', async () => { (await affiliate.balances( affiliate1 )).should.be.bignumber.equal(0); }); it('should give the creator ETH', async () => { const newBalance = await web3Eth.getBalanceAsync(creator); newBalance.should.be.bignumber.equal( creatorBalance.plus(valueAf1) ); }); it('should deduct the amount from the affiliate contract balance', async () => { const newAffiliateContractBalance = await web3Eth.getBalanceAsync( affiliate.address ); newAffiliateContractBalance.should.be.bignumber.equal( affiliateContractBalance.minus(valueAf1) ); }); }); }); }); describe('when a rando is withdrawing', async () => { it('should not work to withdraw', async () => { await assertRevert(affiliate.withdraw({ from: user1 })); }); it('should not work to withdrawFrom', async () => { await assertRevert( affiliate.withdrawFrom(affiliate1, user1, { from: user1 }) ); }); }); }); }); }); describe('when shutting down', async () => { describe('and it is before the expiry time', async () => { it('should not allow the creator to retire', async () => { await assertRevert(affiliate.retire(creator, { from: creator })); }); it('should not allow the a rando to retire', async () => { await assertRevert(affiliate.retire(user1, { from: user1 })); }); }); describe('and it is after the expiry time', async () => { beforeEach(async () => { await increaseTime(60 * 60 * 24 * 31); }); it('should allow the creator to retire', async () => { const creatorBalance = await web3Eth.getBalanceAsync(creator); const affiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); await affiliate.pause({ from: creator, gasPrice: 0 }); await affiliate.retire(creator, { from: creator, gasPrice: 0 }); const newCreatorBalance = await web3Eth.getBalanceAsync(creator); newCreatorBalance.should.be.bignumber.equal( creatorBalance.plus(affiliateBalance) ); await assertRevert(affiliate.unpause({ from: creator })); }); it('should not allow the a rando to retire', async () => { await assertRevert(affiliate.retire(user1, { from: user1 })); }); }); }); const productsOwnedBy = async (ownerAddress: string) => { const tokenIds = await token.tokensOf(ownerAddress); let tokenProductIds = []; for (let i = 0; i < tokenIds.length; i++) { tokenProductIds.push(await token.licenseProductId(tokenIds[i])); } return tokenProductIds; }; const assertOwns = async (ownerAddress: string, productId: number) => { const products = await productsOwnedBy(ownerAddress); const matchingId = find(products, id => id.equals(productId)); (matchingId || false).should.be.bignumber.equal(productId); }; const assertDoesNotOwn = async (ownerAddress: string, productId: number) => { const products = await productsOwnedBy(ownerAddress); const matchingId = find(products, id => id.equals(productId)); (matchingId || false).should.be.false(); }; describe('when making a sale', async () => { const assertPurchaseWorks = async () => { const originalLicenseBalance = await web3Eth.getBalanceAsync( token.address ); await assertDoesNotOwn(user3, secondProduct.id); await token.purchase(secondProduct.id, 1, user3, affiliate1, { from: user3, value: secondProduct.price, gasPrice: 0 }); const newLicenseBalance = await web3Eth.getBalanceAsync(token.address); newLicenseBalance.should.be.bignumber.equal( originalLicenseBalance.add(secondProduct.price) ); await assertOwns(user3, secondProduct.id); }; describe('and the affiliate program is inoperational because', async () => { describe('and the affiliate program was retired', async () => { beforeEach(async () => { await increaseTime(60 * 60 * 24 * 31); await affiliate.pause({ from: creator, gasPrice: 0 }); await affiliate.retire(creator, { from: creator }); }); it('should work just fine', assertPurchaseWorks); }); describe('and the affiliate program is paused', async () => { beforeEach(async () => { await affiliate.pause({ from: creator, gasPrice: 0 }); }); it('should work just fine', assertPurchaseWorks); }); }); describe('and the affiliate program is operational', async () => { beforeEach(async () => { await token.setPrice( secondProduct.id, web3.toWei(new BigNumber(1), 'ether'), { from: creator } ); secondProduct.price = web3.toWei(new BigNumber(1), 'ether').toNumber(); }); describe('and the product is free', async () => { beforeEach(async () => { await token.setPrice(secondProduct.id, 0, { from: creator }); secondProduct.price = 0; }); it('should work just fine', async () => { await assertDoesNotOwn(user3, secondProduct.id); // make a purchase await token.purchase(secondProduct.id, 1, user3, affiliate1, { from: user3, value: secondProduct.price, gasPrice: 0 }); // check the new balances await assertOwns(user3, secondProduct.id); }); }); describe('and the affiliate is missing', async () => { it('should work just fine', async () => { await assertDoesNotOwn(user3, secondProduct.id); // make a purchase await token.purchase(secondProduct.id, 1, user3, ZERO_ADDRESS, { from: user3, value: secondProduct.price, gasPrice: 0 }); // check the new balances await assertOwns(user3, secondProduct.id); }); }); describe('and the affiliate is unknown', async () => { let expectedComission: any; beforeEach(async () => { await affiliate.setBaselineRate(100, { from: creator }); expectedComission = web3.toWei(new BigNumber(0.01), 'ether'); }); it('should give the affiliate his credit', async () => { // check original balances const originalLicenseBalance = await web3Eth.getBalanceAsync( token.address ); const originalAffiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); await assertDoesNotOwn(user3, secondProduct.id); // make a purchase await token.purchase(secondProduct.id, 1, user3, affiliate1, { from: user3, value: secondProduct.price, gasPrice: 0 }); // check the new balances await assertOwns(user3, secondProduct.id); const newLicenseBalance = await web3Eth.getBalanceAsync( token.address ); newLicenseBalance.should.be.bignumber.equal( originalLicenseBalance .add(secondProduct.price) .sub(expectedComission) ); const newAffiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); newAffiliateBalance.should.be.bignumber.equal( originalAffiliateBalance.add(expectedComission) ); }); }); describe('and the affiliate is whitelisted', async () => { let expectedComission: any; beforeEach(async () => { await affiliate.whitelist(affiliate1, 2000, { from: creator }); expectedComission = web3.toWei(new BigNumber(0.2), 'ether'); }); it('should give the affiliate her credit', async () => { // check original balances const originalLicenseBalance = await web3Eth.getBalanceAsync( token.address ); const originalAffiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); await assertDoesNotOwn(user3, secondProduct.id); // make a purchase await token.purchase(secondProduct.id, 1, user3, affiliate1, { from: user3, value: secondProduct.price, gasPrice: 0 }); // check the new balances await assertOwns(user3, secondProduct.id); const newLicenseBalance = await web3Eth.getBalanceAsync( token.address ); newLicenseBalance.should.be.bignumber.equal( originalLicenseBalance .add(secondProduct.price) .sub(expectedComission) ); const newAffiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); newAffiliateBalance.should.be.bignumber.equal( originalAffiliateBalance.add(expectedComission) ); }); }); }); describe('and the affiliate is operational on renew', async () => { describe('and the product is free', async () => { let tokenId: any; beforeEach(async () => { tokenId = await purchase(secondProduct, user1, { affiliate: affiliate1 }); await token.setPrice(secondProduct.id, 0, { from: creator }); secondProduct.price = 0; }); it('should work just fine', async () => { await token.renew(tokenId, 1, { from: user3 }); }); }); describe('and the affiliate might receive a credit', async () => { let tokenId: any; let expectedComission: any; beforeEach(async () => { await token.setPrice( secondProduct.id, web3.toWei(new BigNumber(1), 'ether'), { from: creator } ); secondProduct.price = web3 .toWei(new BigNumber(1), 'ether') .toNumber(); await affiliate.setBaselineRate(100, { from: creator }); expectedComission = web3.toWei(new BigNumber(0.01), 'ether'); tokenId = await purchase(secondProduct, user1, { affiliate: affiliate1 }); }); describe("and it's within the renewal timeframe", async () => { it('should give the affiliate his credit', async () => { // check original balances const originalLicenseBalance = await web3Eth.getBalanceAsync( token.address ); const originalAffiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); await assertOwns(user1, secondProduct.id); // make a renewal await token.renew(tokenId, 1, { from: user3, value: secondProduct.price, gasPrice: 0 }); const newLicenseBalance = await web3Eth.getBalanceAsync( token.address ); newLicenseBalance.should.be.bignumber.equal( originalLicenseBalance .add(secondProduct.price) .sub(expectedComission) ); const newAffiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); newAffiliateBalance.should.be.bignumber.equal( originalAffiliateBalance.add(expectedComission) ); }); }); describe('and the token was sold a long time ago', async () => { beforeEach(async () => { await token.setRenewalsCreditAffiliatesFor(duration.days(1), { from: creator }); let renewalsTimeframe = await token.renewalsCreditAffiliatesFor(); renewalsTimeframe.should.be.bignumber.equal(duration.days(1)); await increaseTime(duration.days(2)); }); it('should not pay an affiliate', async () => { const originalLicenseBalance = await web3Eth.getBalanceAsync( token.address ); const originalAffiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); await assertOwns(user1, secondProduct.id); // make a renewal await token.renew(tokenId, 1, { from: user3, value: secondProduct.price, gasPrice: 0 }); const newLicenseBalance = await web3Eth.getBalanceAsync( token.address ); newLicenseBalance.should.be.bignumber.equal( originalLicenseBalance.add(secondProduct.price) ); const newAffiliateBalance = await web3Eth.getBalanceAsync( affiliate.address ); newAffiliateBalance.should.be.bignumber.equal( originalAffiliateBalance ); }); }); }); }); }); });
the_stack
import * as React from "react"; import styles from "./TranslationBar.module.scss"; import { ITranslationBarProps } from "./ITranslationBarProps"; import { ITranslationBarState } from "./ITranslationBarState"; import { ActionButton } from "office-ui-fabric-react/lib/Button"; import { ILanguage } from "../../models/ILanguage"; import { IContextualMenuItem } from "office-ui-fabric-react/lib/ContextualMenu"; import { Layer } from "office-ui-fabric-react/lib/Layer"; import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar"; import { Overlay } from "office-ui-fabric-react/lib/Overlay"; import { IDetectedLanguage } from "../../models/IDetectedLanguage"; import { sp } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; import "@pnp/sp/items"; import { ColumnControl, ClientsideText, IClientsidePage } from "@pnp/sp/clientside-pages"; import { ITranslationResult } from "../../models/ITranslationResult"; export class TranslationBar extends React.Component<ITranslationBarProps, ITranslationBarState> { constructor(props: ITranslationBarProps) { super(props); this.state = { availableLanguages: [], selectedLanguage: undefined, pageItem: undefined, isLoading: true, isTranslated: false, isTranslating: false, globalError: undefined }; } public async componentDidMount() { this._initTranslationBar(); } public async componentDidUpdate(nextProps: ITranslationBarProps) { if (nextProps.currentPageId !== this.props.currentPageId) { // Set original state this.setState({ availableLanguages: [], selectedLanguage: undefined, pageItem: undefined, isLoading: true, isTranslated: false, isTranslating: false, globalError: undefined }, () => this._initTranslationBar()); } } public render(): JSX.Element { const { availableLanguages, globalError, selectedLanguage, isLoading } = this.state; if (isLoading) { return ( <div className={styles.translationBar}> <div className={styles.loadingButton}>Loading ...</div> </div> ); } if (globalError) { return ( <div className={styles.translationBar}> <MessageBar messageBarType={MessageBarType.error}> {globalError} </MessageBar> </div> ); } if (!selectedLanguage) { return ( <div className={styles.translationBar}> <MessageBar messageBarType={MessageBarType.info}> {"Could not determine the language of the page. It is either not supported by the API or it is not enabled by your adminitrator."} </MessageBar> </div> ); } let currentMenuItems = [...availableLanguages]; if (currentMenuItems.length <= 0) { currentMenuItems = [ { key: "noTranslationsPlaceholder", name: "No available languages found", disabled: true } ]; } return ( <div className={styles.translationBar}> <ActionButton className={styles.actionButton} text={this.state.selectedLanguage.label} iconProps={{ iconName: "Globe" }} menuProps={{ shouldFocusOnMount: true, items: currentMenuItems }} /> {this.state.isTranslated && ( <ActionButton className={styles.actionButton} text={"Reload original"} onClick={() => this._onReloadOriginal()} /> )} {this.state.isTranslated && ( <MessageBar messageBarType={MessageBarType.warning}> <span> Please be aware that the content on this page is translated by the Microsoft Translator Text API to provide a basic understanding of the content. It is a literal translation and certain words may not translate accurately.... </span> </MessageBar> )} {this.state.isTranslating && ( <Layer> <Overlay isDarkThemed={true} /> </Layer> )} </div> ); } private _initTranslationBar = async (): Promise<void> => { try { const pageItem = await this._getPageItem(); const textToDetect = pageItem["Description"] ? pageItem["Description"] : pageItem["Title"]; const detectedLanguage = await this._detectLanguage(textToDetect); const availableLanguages = await this._getAvailableLanguages(detectedLanguage); let selectedLanguage: ILanguage = undefined; if (availableLanguages.some((l: IContextualMenuItem) => l.key === detectedLanguage.language)) { const selectedLanguageMenuItem = availableLanguages.filter((l: IContextualMenuItem) => l.key === detectedLanguage.language)[0]; selectedLanguage = { label: selectedLanguageMenuItem.name, code: selectedLanguageMenuItem.key }; } this.setState({ availableLanguages, selectedLanguage, pageItem, isLoading: false, isTranslated: false, isTranslating: false, globalError: undefined }); } catch (error) { console.dir(error); this.setState({ isLoading: false, isTranslated: false, isTranslating: false, globalError: (error as Error).message }); } } private _getPageItem = async (): Promise<any> => { const page = await sp.web.lists .getById(this.props.currentListId) .items .getById(this.props.currentPageId) .select("Title", "FileLeafRef", "FileRef", "Description").get(); return page; } private _detectLanguage = async (text: string): Promise<IDetectedLanguage> => { return await this.props.translationService.detectLanguage(text); } private _getAvailableLanguages = async (detectedLanguage: IDetectedLanguage): Promise<IContextualMenuItem[]> => { return (await this.props.translationService.getAvailableLanguages(this.props.supportedLanguages)) .map((language: ILanguage) => { return { key: language.code, name: language.label, onClick: () => this._onTranslate(language), iconProps: language.code === detectedLanguage.language ? { iconName: "CheckMark" } : undefined }; }); } private _updateSelectedLanguage = (selectedLanguage: ILanguage): void => { const availableLanguages: IContextualMenuItem[] = [...this.state.availableLanguages].map((item: IContextualMenuItem) => { return { ...item, iconProps: item.key === selectedLanguage.code ? { iconName: "CheckMark" } : undefined }; }); this.setState({ availableLanguages, selectedLanguage }); } private _onTranslate = (language: ILanguage): void => { this.setState({ isTranslating: true }); const relativePageUrl: string = `${this.props.currentWebUrl}/SitePages/${this.state.pageItem["FileLeafRef"]}`; sp.web.loadClientsidePage(relativePageUrl).then( async (clientSidePage: IClientsidePage) => { try { // Translate title await this._translatePageTitle(clientSidePage.title, language.code); // Get all text controls var textControls: ColumnControl<any>[] = []; clientSidePage.findControl((c) => { if (c instanceof ClientsideText) { textControls.push(c); } return false; }); for (const control of textControls) { await this._translateTextControl(control as ClientsideText, language.code); } this.setState({ isTranslating: false, isTranslated: true }); this._updateSelectedLanguage(language); } catch (error) { console.dir(error); this.setState({ isTranslating: false, globalError: (error as Error).message }); } }).catch((error: Error) => { console.dir(error); this.setState({ isTranslating: false, globalError: error.message }); }); } private _translatePageTitle = async (title: string, languageCode): Promise<void> => { const translationResult: ITranslationResult = await this.props.translationService.translate(title, languageCode, false); // get the title element const pageTitle: Element = document.querySelector("div[data-automation-id='pageHeader'] div[role='heading']"); if (pageTitle) { pageTitle.textContent = translationResult.translations[0].text; } } private _translateTextControl = async (textControl: ClientsideText, languageCode: string): Promise<void> => { // Get the element const element = document.querySelector(`[data-sp-feature-instance-id='${textControl.id}']`); // Translate element if found if (element && element.firstChild) { await this._translateHtmlElement(element.firstChild as Element, languageCode); } else { console.error(`Text control with id: '${textControl.id}' not found!`); } } private _translateHtmlElement = async (element: Element, languageCode: string): Promise<void> => { // If inner HTML >= 5000 the API call will fail // translate each HMTL child node if (element.innerHTML.length > 4999) { const childElements = [].slice.call(element.children); if (childElements.length > 0) { for (const childElement of childElements) { await this._translateHtmlElement(childElement, languageCode); } } else { // Fallback: translate each sentence individually if the // the length of one html tag is longer then 4999 characters const breakSentenceResult = await this.props.translationService.breakSentence(element.textContent); let startIndex, endIndex = 0; const fullTextToTranslate = element.textContent; for (const sentenceLenght of breakSentenceResult.sentLen) { endIndex += sentenceLenght; const sentenceToTranslate = fullTextToTranslate.substring(startIndex, endIndex); const translationResult = await this.props.translationService.translate(sentenceToTranslate, languageCode, false); element.textContent = element.textContent.replace( sentenceToTranslate, translationResult.translations[0].text ); startIndex = endIndex; } } } else { const translationResult = await this.props.translationService.translate(element.innerHTML, languageCode, true); element.innerHTML = translationResult.translations[0].text; } } private _onReloadOriginal = () => { window.location.reload(); } }
the_stack
export enum ClassState { // The class has yet to be loaded. NOT_LOADED, // The class's definition has been downloaded and parsed. LOADED, // This class and its super classes' definitions have been downloaded and // parsed. RESOLVED, // This class, its super classes', and its interfaces have been downloaded, // parsed, and statically initialized. INITIALIZED } /** * A thread can be in one of these states at any given point in time. * * NOTE: When altering ThreadStatus, remember to update the following things. * * - Thread.validTransitions: Describes each valid thread transition. * - sun.misc.VM.getThreadStateValues: Maps ThreadStatus values to Thread.State * values. * - Assertion statements in Thread regarding its status. */ export enum ThreadStatus { // A thread that has not yet started is in this state. NEW, // A thread that is able to be run. The thread may actually be running. // Query the ThreadPool to determine if this is the case. RUNNABLE, // A thread that is blocked waiting for a monitor lock is in this state. BLOCKED, // A thread that is blocked waiting for a monitor lock that was previously // interrupted from waiting on a monitor is in this state. // Why? Well, the thread has *already* been interrupted once, but cannot // process the interruption until it regains the lock. UNINTERRUPTABLY_BLOCKED, // A thread that is waiting indefinitely for another thread to perform a // particular action is in this state. WAITING, // A thread that is waiting for another thread to perform an action for up to // a specified waiting time is in this state. TIMED_WAITING, // A thread that is waiting for an asynchronous browser operation to complete. ASYNC_WAITING, // A thread that is parked. PARKED, // A thread that has exited is in this state. TERMINATED } /** * Java-visible thread state values. */ export enum JVMTIThreadState { ALIVE = 0x0001, TERMINATED = 0x0002, RUNNABLE = 0x0004, BLOCKED_ON_MONITOR_ENTER = 0x0400, WAITING_INDEFINITELY = 0x0010, WAITING_WITH_TIMEOUT = 0x0020 } /** * Three-state boolean. */ export enum TriState { TRUE, FALSE, INDETERMINATE } /** * The current status of the JVM. */ export enum JVMStatus { // The JVM is booting up. BOOTING, // The JVM is booted, and waiting for a class to run. BOOTED, // The JVM is running. RUNNING, // The JVM has completed running, and is performing termination steps. TERMINATING, // The JVM is completely finished executing. TERMINATED } /** * Indicates the type of a stack frame. */ export enum StackFrameType { /** * A JVM internal stack frame. These should be completely invisible to the * JVM program. */ INTERNAL, /** * A bytecode method's stack frame. These have an actual stack. */ BYTECODE, /** * A native method's stack frame. These typically consist of just a JavaScript * function and a method association. */ NATIVE } /** * Various constant values. Enum'd so they are inlined by the TypeScript * compiler. */ export enum Constants { INT_MAX = Math.pow(2, 31) - 1, INT_MIN = -INT_MAX - 1, FLOAT_POS_INFINITY = Math.pow(2, 128), FLOAT_NEG_INFINITY = -1 * FLOAT_POS_INFINITY, FLOAT_POS_INFINITY_AS_INT = 0x7F800000, FLOAT_NEG_INFINITY_AS_INT = -8388608, // We use the JavaScript NaN as our NaN value, and convert it to // a NaN value in the SNaN range when an int equivalent is requested. FLOAT_NaN_AS_INT = 0x7fc00000 } /** * Integer indicating the type of a constant pool item. * @url https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4-140 */ export enum ConstantPoolItemType { CLASS = 7, FIELDREF = 9, METHODREF = 10, INTERFACE_METHODREF = 11, STRING = 8, INTEGER = 3, FLOAT = 4, LONG = 5, DOUBLE = 6, NAME_AND_TYPE = 12, UTF8 = 1, METHOD_HANDLE = 15, METHOD_TYPE = 16, INVOKE_DYNAMIC = 18 } /** * Integer indicating the type of a StackMapTable entry. * @see https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.4 */ export enum StackMapTableEntryType { SAME_FRAME, SAME_LOCALS_1_STACK_ITEM_FRAME, SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED, CHOP_FRAME, SAME_FRAME_EXTENDED, APPEND_FRAME, FULL_FRAME } /** * Integer indicating the reference type of a MethodHandle item in the constant * pool. * @see https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4.8 */ export enum MethodHandleReferenceKind { GETFIELD = 1, GETSTATIC = 2, PUTFIELD = 3, PUTSTATIC = 4, INVOKEVIRTUAL = 5, INVOKESTATIC = 6, INVOKESPECIAL = 7, NEWINVOKESPECIAL = 8, INVOKEINTERFACE = 9 } /** * JVM op codes. The enum value corresponds to that opcode's value. */ export enum OpCode { AALOAD = 0x32, AASTORE = 0x53, ACONST_NULL = 0x01, ALOAD = 0x19, ALOAD_0 = 0x2a, ALOAD_1 = 0x2b, ALOAD_2 = 0x2c, ALOAD_3 = 0x2d, ANEWARRAY = 0xbd, ARETURN = 0xb0, ARRAYLENGTH = 0xbe, ASTORE = 0x3a, ASTORE_0 = 0x4b, ASTORE_1 = 0x4c, ASTORE_2 = 0x4d, ASTORE_3 = 0x4e, ATHROW = 0xbf, BALOAD = 0x33, BASTORE = 0x54, BIPUSH = 0x10, BREAKPOINT = 0xca, CALOAD = 0x34, CASTORE = 0x55, CHECKCAST = 0xc0, D2F = 0x90, D2I = 0x8e, D2L = 0x8f, DADD = 0x63, DALOAD = 0x31, DASTORE = 0x52, DCMPG = 0x98, DCMPL = 0x97, DCONST_0 = 0x0e, DCONST_1 = 0x0f, DDIV = 0x6f, DLOAD = 0x18, DLOAD_0 = 0x26, DLOAD_1 = 0x27, DLOAD_2 = 0x28, DLOAD_3 = 0x29, DMUL = 0x6b, DNEG = 0x77, DREM = 0x73, DRETURN = 0xaf, DSTORE = 0x39, DSTORE_0 = 0x47, DSTORE_1 = 0x48, DSTORE_2 = 0x49, DSTORE_3 = 0x4a, DSUB = 0x67, DUP = 0x59, DUP_X1 = 0x5a, DUP_X2 = 0x5b, DUP2 = 0x5c, DUP2_X1 = 0x5d, DUP2_X2 = 0x5e, F2D = 0x8d, F2I = 0x8b, F2L = 0x8c, FADD = 0x62, FALOAD = 0x30, FASTORE = 0x51, FCMPG = 0x96, FCMPL = 0x95, FCONST_0 = 0x0b, FCONST_1 = 0x0c, FCONST_2 = 0x0d, FDIV = 0x6e, FLOAD = 0x17, FLOAD_0 = 0x22, FLOAD_1 = 0x23, FLOAD_2 = 0x24, FLOAD_3 = 0x25, FMUL = 0x6a, FNEG = 0x76, FREM = 0x72, FRETURN = 0xae, FSTORE = 0x38, FSTORE_0 = 0x43, FSTORE_1 = 0x44, FSTORE_2 = 0x45, FSTORE_3 = 0x46, FSUB = 0x66, GETFIELD = 0xb4, GETSTATIC = 0xb2, GOTO = 0xa7, GOTO_W = 0xc8, I2B = 0x91, I2C = 0x92, I2D = 0x87, I2F = 0x86, I2L = 0x85, I2S = 0x93, IADD = 0x60, IALOAD = 0x2e, IAND = 0x7e, IASTORE = 0x4f, ICONST_M1 = 0x2, ICONST_0 = 3, ICONST_1 = 4, ICONST_2 = 5, ICONST_3 = 6, ICONST_4 = 7, ICONST_5 = 8, IDIV = 0x6c, IF_ACMPEQ = 0xa5, IF_ACMPNE = 0xa6, IF_ICMPEQ = 0x9f, IF_ICMPGE = 0xa2, IF_ICMPGT = 0xa3, IF_ICMPLE = 0xa4, IF_ICMPLT = 0xa1, IF_ICMPNE = 0xa0, IFEQ = 0x99, IFGE = 0x9c, IFGT = 0x9d, IFLE = 0x9e, IFLT = 0x9b, IFNE = 0x9a, IFNONNULL = 0xc7, IFNULL = 0xc6, IINC = 0x84, ILOAD = 0x15, ILOAD_0 = 0x1a, ILOAD_1 = 0x1b, ILOAD_2 = 0x1c, ILOAD_3 = 0x1d, // IMPDEP1 = 0xfe, // IMPDEP2 = 0xff, IMUL = 0x68, INEG = 0x74, INSTANCEOF = 0xc1, INVOKEDYNAMIC = 0xba, INVOKEINTERFACE = 0xb9, INVOKESPECIAL = 0xb7, INVOKESTATIC = 0xb8, INVOKEVIRTUAL = 0xb6, IOR = 0x80, IREM = 0x70, IRETURN = 0xac, ISHL = 0x78, ISHR = 0x7a, ISTORE = 0x36, ISTORE_0 = 0x3b, ISTORE_1 = 0x3c, ISTORE_2 = 0x3d, ISTORE_3 = 0x3e, ISUB = 0x64, IUSHR = 0x7c, IXOR = 0x82, JSR = 0xa8, JSR_W = 0xc9, L2D = 0x8a, L2F = 0x89, L2I = 0x88, LADD = 0x61, LALOAD = 0x2f, LAND = 0x7f, LASTORE = 0x50, LCMP = 0x94, LCONST_0 = 0x09, LCONST_1 = 0x0a, LDC = 0x12, LDC_W = 0x13, LDC2_W = 0x14, LDIV = 0x6d, LLOAD = 0x16, LLOAD_0 = 0x1e, LLOAD_1 = 0x1f, LLOAD_2 = 0x20, LLOAD_3 = 0x21, LMUL = 0x69, LNEG = 0x75, LOOKUPSWITCH = 0xab, LOR = 0x81, LREM = 0x71, LRETURN = 0xad, LSHL = 0x79, LSHR = 0x7b, LSTORE = 0x37, LSTORE_0 = 0x3f, LSTORE_1 = 0x40, LSTORE_2 = 0x41, LSTORE_3 = 0x42, LSUB = 0x65, LUSHR = 0x7d, LXOR = 0x83, MONITORENTER = 0xc2, MONITOREXIT = 0xc3, MULTIANEWARRAY = 0xc5, NEW = 0xbb, NEWARRAY = 0xbc, NOP = 0x00, POP = 0x57, POP2 = 0x58, PUTFIELD = 0xb5, PUTSTATIC = 0xb3, RET = 0xa9, RETURN = 0xb1, SALOAD = 0x35, SASTORE = 0x56, SIPUSH = 0x11, SWAP = 0x5f, TABLESWITCH = 0xaa, WIDE = 0xc4, // Special Doppio 'fast' opcodes GETSTATIC_FAST32 = 0xd0, GETSTATIC_FAST64 = 0xd1, NEW_FAST = 0xd2, ANEWARRAY_FAST = 0xd5, CHECKCAST_FAST = 0xd6, INSTANCEOF_FAST = 0xd7, MULTIANEWARRAY_FAST = 0xd8, PUTSTATIC_FAST32 = 0xd9, PUTSTATIC_FAST64 = 0xda, GETFIELD_FAST32 = 0xdb, GETFIELD_FAST64 = 0xdc, PUTFIELD_FAST32 = 0xdd, PUTFIELD_FAST64 = 0xde, INVOKENONVIRTUAL_FAST = 0xdf, INVOKESTATIC_FAST = 0xf0, INVOKEVIRTUAL_FAST = 0xf1, INVOKEINTERFACE_FAST = 0xf2, INVOKEHANDLE = 0xf3, INVOKEBASIC = 0xf4, LINKTOSPECIAL = 0xf5, LINKTOVIRTUAL = 0xf7, INVOKEDYNAMIC_FAST = 0xf8 } export enum OpcodeLayoutType { OPCODE_ONLY, CONSTANT_POOL_UINT8, CONSTANT_POOL, CONSTANT_POOL_AND_UINT8_VALUE, UINT8_VALUE, UINT8_AND_INT8_VALUE, INT8_VALUE, INT16_VALUE, INT32_VALUE, // LOOKUPSWITCH, // TABLESWITCH, ARRAY_TYPE, WIDE } // Contains the opcode layout types for each valid opcode. // To conserve code space, it's assumed all opcodes not in the table // are OPCODE_ONLY. var olt: OpcodeLayoutType[] = new Array(0xff); (() => { for (var i = 0; i < 0xff; i++) { olt[i] = OpcodeLayoutType.OPCODE_ONLY; } })(); function assignOpcodeLayout(layoutType: OpcodeLayoutType, opcodes: OpCode[]): void { opcodes.forEach((opcode) => { olt[opcode] = layoutType; }); } assignOpcodeLayout(OpcodeLayoutType.UINT8_VALUE, [OpCode.ALOAD, OpCode.ASTORE, OpCode.DLOAD, OpCode.DSTORE, OpCode.FLOAD, OpCode.FSTORE, OpCode.ILOAD, OpCode.ISTORE, OpCode.LLOAD, OpCode.LSTORE, OpCode.RET]); assignOpcodeLayout(OpcodeLayoutType.CONSTANT_POOL_UINT8, [OpCode.LDC]); assignOpcodeLayout(OpcodeLayoutType.CONSTANT_POOL, [OpCode.LDC_W, OpCode.LDC2_W, OpCode.ANEWARRAY, OpCode.CHECKCAST, OpCode.GETFIELD, OpCode.GETSTATIC, OpCode.INSTANCEOF, OpCode.INVOKEDYNAMIC, OpCode.INVOKESPECIAL, OpCode.INVOKESTATIC, OpCode.INVOKEVIRTUAL, OpCode.NEW, OpCode.PUTFIELD, OpCode.PUTSTATIC, OpCode.MULTIANEWARRAY_FAST, OpCode.INVOKENONVIRTUAL_FAST, OpCode.INVOKESTATIC_FAST, OpCode.CHECKCAST_FAST, OpCode.NEW_FAST, OpCode.ANEWARRAY_FAST, OpCode.INSTANCEOF_FAST, OpCode.GETSTATIC_FAST32, OpCode.GETSTATIC_FAST64, OpCode.PUTSTATIC_FAST32, OpCode.PUTSTATIC_FAST64, OpCode.PUTFIELD_FAST32, OpCode.PUTFIELD_FAST64, OpCode.GETFIELD_FAST32, OpCode.GETFIELD_FAST64, OpCode.INVOKEVIRTUAL_FAST ]); assignOpcodeLayout(OpcodeLayoutType.CONSTANT_POOL_AND_UINT8_VALUE, [OpCode.INVOKEINTERFACE, OpCode.INVOKEINTERFACE_FAST, OpCode.MULTIANEWARRAY]); assignOpcodeLayout(OpcodeLayoutType.INT8_VALUE, [OpCode.BIPUSH]); assignOpcodeLayout(OpcodeLayoutType.INT16_VALUE, [OpCode.SIPUSH, OpCode.GOTO, OpCode.IFGT, OpCode.IFEQ, OpCode.IFGE, OpCode.IFLE, OpCode.IFLT, OpCode.IFNE, OpCode.IFNULL, OpCode.IFNONNULL, OpCode.IF_ICMPLE, OpCode.IF_ACMPEQ, OpCode.IF_ACMPNE, OpCode.IF_ICMPEQ, OpCode.IF_ICMPGE, OpCode.IF_ICMPGT, OpCode.IF_ICMPLT, OpCode.IF_ICMPNE, OpCode.JSR]); assignOpcodeLayout(OpcodeLayoutType.INT32_VALUE, [OpCode.GOTO_W, OpCode.JSR_W]); assignOpcodeLayout(OpcodeLayoutType.UINT8_AND_INT8_VALUE, [OpCode.IINC]); assignOpcodeLayout(OpcodeLayoutType.ARRAY_TYPE, [OpCode.NEWARRAY]); export var OpcodeLayouts = olt;
the_stack
module android.graphics.drawable { import Canvas = android.graphics.Canvas; import Rect = android.graphics.Rect; import TypedValue = android.util.TypedValue; import Log = android.util.Log; import Resources = android.content.res.Resources; import Gravity = android.view.Gravity; import Runnable = java.lang.Runnable; import Float = java.lang.Float; import Drawable = android.graphics.drawable.Drawable; import TypedArray = android.content.res.TypedArray; /** * A Drawable that changes the size of another Drawable based on its current * level value. You can control how much the child Drawable changes in width * and height based on the level, as well as a gravity to control where it is * placed in its overall container. Most often used to implement things like * progress bars. * * <p>It can be defined in an XML file with the <code>&lt;scale></code> element. For more * information, see the guide to <a * href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.</p> * * @attr ref android.R.styleable#ScaleDrawable_scaleWidth * @attr ref android.R.styleable#ScaleDrawable_scaleHeight * @attr ref android.R.styleable#ScaleDrawable_scaleGravity * @attr ref android.R.styleable#ScaleDrawable_drawable */ export class ScaleDrawable extends Drawable implements Drawable.Callback { private mScaleState:ScaleDrawable.ScaleState; private mMutated:boolean; private mTmpRect:Rect = new Rect(); constructor(drawable:Drawable, gravity:number, scaleWidth:number, scaleHeight:number); constructor(state?:ScaleDrawable.ScaleState); constructor(...args) { super(); if (args.length <= 1) { this.mScaleState = new ScaleDrawable.ScaleState(args[0], this); return; } let drawable:Drawable = args[0]; let gravity:number = args[1]; let scaleWidth:number = args[2]; let scaleHeight:number = args[3]; this.mScaleState = new ScaleDrawable.ScaleState(null, this); this.mScaleState.mDrawable = drawable; this.mScaleState.mGravity = gravity; this.mScaleState.mScaleWidth = scaleWidth; this.mScaleState.mScaleHeight = scaleHeight; if (drawable != null) { drawable.setCallback(this); } } /** * Returns the drawable scaled by this ScaleDrawable. */ getDrawable():Drawable { return this.mScaleState.mDrawable; } //private static getPercent(a:TypedArray, name:number):number { // let s:string = a.getString(name); // if (s != null) { // if (s.endsWith("%")) { // let f:string = s.substring(0, s.length() - 1); // return Float.parseFloat(f) / 100.0; // } // } // return -1; //} inflate(r:Resources, parser:HTMLElement):void { super.inflate(r, parser); let a:TypedArray = r.obtainAttributes(parser); let sw:number = a.getFloat("android:scaleWidth", 1); let sh:number = a.getFloat("android:scaleHeight", 1); let gStr:string = a.getString("android:scaleGravity"); let g = Gravity.parseGravity(gStr, Gravity.LEFT); let min:boolean = a.getBoolean("android:useIntrinsicSizeAsMinimum", false); let dr:Drawable = a.getDrawable("android:drawable"); a.recycle(); if (!dr && parser.children[0] instanceof HTMLElement) { dr = Drawable.createFromXml(r, <HTMLElement>parser.children[0]); } if (dr == null) { throw Error(`new IllegalArgumentException("No drawable specified for <scale>")`); } this.mScaleState.mDrawable = dr; this.mScaleState.mScaleWidth = sw; this.mScaleState.mScaleHeight = sh; this.mScaleState.mGravity = g; this.mScaleState.mUseIntrinsicSizeAsMin = min; if (dr != null) { dr.setCallback(this); } } // overrides from Drawable.Callback drawableSizeChange(who:android.graphics.drawable.Drawable):void { const callback = this.getCallback(); if (callback != null && callback.drawableSizeChange) { callback.drawableSizeChange(this); } } invalidateDrawable(who:Drawable):void { if (this.getCallback() != null) { this.getCallback().invalidateDrawable(this); } } scheduleDrawable(who:Drawable, what:Runnable, when:number):void { if (this.getCallback() != null) { this.getCallback().scheduleDrawable(this, what, when); } } unscheduleDrawable(who:Drawable, what:Runnable):void { if (this.getCallback() != null) { this.getCallback().unscheduleDrawable(this, what); } } // overrides from Drawable draw(canvas:Canvas):void { if (this.mScaleState.mDrawable.getLevel() != 0) this.mScaleState.mDrawable.draw(canvas); } //getChangingConfigurations():number { // return super.getChangingConfigurations() | this.mScaleState.mChangingConfigurations | this.mScaleState.mDrawable.getChangingConfigurations(); //} getPadding(padding:Rect):boolean { // XXX need to adjust padding! return this.mScaleState.mDrawable.getPadding(padding); } setVisible(visible:boolean, restart:boolean):boolean { this.mScaleState.mDrawable.setVisible(visible, restart); return super.setVisible(visible, restart); } setAlpha(alpha:number):void { this.mScaleState.mDrawable.setAlpha(alpha); } getAlpha():number { return this.mScaleState.mDrawable.getAlpha(); } //setColorFilter(cf:ColorFilter):void { // this.mScaleState.mDrawable.setColorFilter(cf); //} getOpacity():number { return this.mScaleState.mDrawable.getOpacity(); } isStateful():boolean { return this.mScaleState.mDrawable.isStateful(); } protected onStateChange(state:number[]):boolean { let changed:boolean = this.mScaleState.mDrawable.setState(state); this.onBoundsChange(this.getBounds()); return changed; } protected onLevelChange(level:number):boolean { this.mScaleState.mDrawable.setLevel(level); this.onBoundsChange(this.getBounds()); this.invalidateSelf(); return true; } protected onBoundsChange(bounds:Rect):void { const r:Rect = this.mTmpRect; const min:boolean = this.mScaleState.mUseIntrinsicSizeAsMin; let level:number = this.getLevel(); let w:number = bounds.width(); if (this.mScaleState.mScaleWidth > 0) { const iw:number = min ? this.mScaleState.mDrawable.getIntrinsicWidth() : 0; w -= Math.floor(((w - iw) * (10000 - level) * this.mScaleState.mScaleWidth / 10000)); } let h:number = bounds.height(); if (this.mScaleState.mScaleHeight > 0) { const ih:number = min ? this.mScaleState.mDrawable.getIntrinsicHeight() : 0; h -= Math.floor(((h - ih) * (10000 - level) * this.mScaleState.mScaleHeight / 10000)); } //const layoutDirection:number = this.getLayoutDirection(); Gravity.apply(this.mScaleState.mGravity, w, h, bounds, r);//, layoutDirection); if (w > 0 && h > 0) { this.mScaleState.mDrawable.setBounds(r.left, r.top, r.right, r.bottom); } } getIntrinsicWidth():number { return this.mScaleState.mDrawable.getIntrinsicWidth(); } getIntrinsicHeight():number { return this.mScaleState.mDrawable.getIntrinsicHeight(); } getConstantState():Drawable.ConstantState { if (this.mScaleState.canConstantState()) { //this.mScaleState.mChangingConfigurations = this.getChangingConfigurations(); return this.mScaleState; } return null; } mutate():Drawable { if (!this.mMutated && super.mutate() == this) { this.mScaleState.mDrawable.mutate(); this.mMutated = true; } return this; } } export module ScaleDrawable { export class ScaleState implements Drawable.ConstantState { mDrawable:Drawable; //mChangingConfigurations:number = 0; mScaleWidth:number = 0; mScaleHeight:number = 0; mGravity:number = 0; mUseIntrinsicSizeAsMin:boolean; private mCheckedConstantState:boolean; private mCanConstantState:boolean; constructor(orig:ScaleState, owner:ScaleDrawable) { if (orig != null) { this.mDrawable = orig.mDrawable.getConstantState().newDrawable(); this.mDrawable.setCallback(owner); //this.mDrawable.setLayoutDirection(orig.mDrawable.getLayoutDirection()); this.mScaleWidth = orig.mScaleWidth; this.mScaleHeight = orig.mScaleHeight; this.mGravity = orig.mGravity; this.mUseIntrinsicSizeAsMin = orig.mUseIntrinsicSizeAsMin; this.mCheckedConstantState = this.mCanConstantState = true; } } newDrawable():Drawable { return new ScaleDrawable(this); } //getChangingConfigurations():number { // return this.mChangingConfigurations; //} canConstantState():boolean { if (!this.mCheckedConstantState) { this.mCanConstantState = this.mDrawable.getConstantState() != null; this.mCheckedConstantState = true; } return this.mCanConstantState; } } } }
the_stack
import { transduce } from "./core"; import { lazyTransduce } from "./iterables"; import { count, every, find, first, forEach, isEmpty, joinToString, max, min, some, sum, toArray, toAverage, toMap, toMapGroupBy, toObject, toObjectGroupBy, toSet, } from "./reducers"; import { dedupe, drop, dropWhile, filter, flatMap, flatten, interpose, map, mapIndexed, partitionAll, partitionBy, remove, take, takeNth, takeWhile, } from "./transducers"; import { Comparator, CompletingTransformer, QuittingReducer, Transducer, } from "./types"; export interface TransformChain<T> { // tslint:disable: member-ordering compose<U>(transducer: Transducer<T, U>): TransformChain<U>; dedupe(): TransformChain<T>; drop(n: number): TransformChain<T>; dropWhile(pred: (item: T) => boolean): TransformChain<T>; filter<U extends T>(pred: (item: T) => item is U): TransformChain<U>; filter(pred: (item: T) => boolean): TransformChain<T>; flatMap<U>(f: (item: T) => Iterable<U>): TransformChain<U>; flatten: T extends Iterable<infer U> ? () => TransformChain<U> : void; interpose(separator: T): TransformChain<T>; map<U>(f: (item: T) => U): TransformChain<U>; mapIndexed<U>(f: (item: T, index: number) => U): TransformChain<U>; partitionAll(n: number): TransformChain<T[]>; partitionBy(pred: (item: T) => any): TransformChain<T[]>; remove<U extends T>( pred: (item: T) => item is U, ): TransformChain<Exclude<T, U>>; remove(pred: (item: T) => boolean): TransformChain<T>; removeAbsent(): TransformChain<NonNullable<T>>; take(n: number): TransformChain<T>; takeNth(n: number): TransformChain<T>; takeWhile<U extends T>(pred: (item: T) => item is U): TransformChain<U>; takeWhile(pred: (item: T) => boolean): TransformChain<T>; reduce<TResult>( reducer: QuittingReducer<TResult, T>, initialValue: TResult, ): TResult; reduce<TResult, TCompleteResult>( transformer: CompletingTransformer<TResult, TCompleteResult, T>, ): TCompleteResult; average: T extends number ? () => number | null : void; count(): number; every(pred: (item: T) => boolean): boolean; find<U extends T>(pred: (item: T) => item is U): U | null; find(pred: (item: T) => boolean): T | null; first(): T | null; forEach(f: (item: T) => void): void; isEmpty(): boolean; joinToString(separator: string): string; max: T extends number ? (comparator?: Comparator<number>) => number | null : (comparator: Comparator<T>) => T | null; min: T extends number ? (comparator?: Comparator<number>) => number | null : (comparator: Comparator<T>) => T | null; some(pred: (item: T) => boolean): boolean; sum: T extends number ? () => number : void; toArray(): T[]; toMap<K, V>(getKey: (item: T) => K, getValue: (item: T) => V): Map<K, V>; toMapGroupBy<K>(getKey: (item: T) => K): Map<K, T[]>; toMapGroupBy<K, V>( getKey: (item: T) => K, transformer: CompletingTransformer<any, V, T>, ): Map<K, V>; toObject<K extends keyof any, V>( getKey: (item: T) => K, getValue: (item: T) => V, ): Record<K, V>; toObjectGroupBy<K extends keyof any>( getKey: (item: T) => K, ): Record<K, T[]>; toObjectGroupBy<K extends keyof any, V>( getKey: (item: T) => K, transformer: CompletingTransformer<any, V, T>, ): Record<K, V>; toSet(): Set<T>; toIterator(): IterableIterator<T>; // tslint:enable: member-ordering } export interface TransducerBuilder<TBase, T> { // tslint:disable: member-ordering compose<U>(transducer: Transducer<T, U>): TransducerBuilder<TBase, U>; dedupe(): TransducerBuilder<TBase, T>; drop(n: number): TransducerBuilder<TBase, T>; dropWhile(pred: (item: T) => boolean): TransducerBuilder<TBase, T>; filter<U extends T>( pred: (item: T) => item is U, ): TransducerBuilder<TBase, U>; filter(pred: (item: T) => boolean): TransducerBuilder<TBase, T>; flatMap<U>(f: (item: T) => Iterable<U>): TransducerBuilder<TBase, U>; flatten: T extends Iterable<infer U> ? () => TransducerBuilder<TBase, U> : void; interpose(separator: T): TransducerBuilder<TBase, T>; map<U>(f: (item: T) => U): TransducerBuilder<TBase, U>; mapIndexed<U>( f: (item: T, index: number) => U, ): TransducerBuilder<TBase, U>; partitionAll(n: number): TransducerBuilder<TBase, T[]>; partitionBy(pred: (item: T) => boolean): TransducerBuilder<TBase, T[]>; remove<U extends T>( pred: (item: T) => item is U, ): TransducerBuilder<TBase, Exclude<T, U>>; remove(pred: (item: T) => boolean): TransducerBuilder<TBase, T>; removeAbsent(): TransducerBuilder<TBase, NonNullable<T>>; take(n: number): TransducerBuilder<TBase, T>; takeNth(n: number): TransducerBuilder<TBase, T>; takeWhile<U extends T>( pred: (item: T) => item is U, ): TransducerBuilder<TBase, U>; takeWhile(pred: (item: T) => boolean): TransducerBuilder<TBase, T>; build(): Transducer<TBase, T>; // tslint:disable: member-ordering } export function chainFrom<T>(collection: Iterable<T>): TransformChain<T> { return new TransducerChain(collection) as any; } export function transducerBuilder<T>(): TransducerBuilder<T, T> { return new TransducerChain<T, T>([]) as any; } type CombinedBuilder<TBase, T> = TransformChain<T> & TransducerBuilder<TBase, T>; class TransducerChain<TBase, T> implements CombinedBuilder<TBase, T> { private readonly transducers: Array<Transducer<any, any>> = []; constructor(private readonly collection: Iterable<TBase>) {} public compose<U>(transducer: Transducer<T, U>): CombinedBuilder<TBase, U> { this.transducers.push(transducer); return this as any; } public build(): Transducer<TBase, T> { return (x: any) => { let result = x; for (let i = this.transducers.length - 1; i >= 0; i--) { result = this.transducers[i](result); } return result; }; } // ----- Composing transducers ----- public dedupe(): CombinedBuilder<TBase, T> { return this.compose(dedupe()); } public drop(n: number): CombinedBuilder<TBase, T> { return this.compose(drop(n)); } public dropWhile(pred: (item: T) => boolean): CombinedBuilder<TBase, T> { return this.compose(dropWhile(pred)); } public filter(pred: (item: T) => boolean): CombinedBuilder<TBase, T> { return this.compose(filter(pred)); } public flatMap<U>(f: (item: T) => Iterable<U>): CombinedBuilder<TBase, U> { return this.compose(flatMap(f)); } // @ts-ignore public flatten(): CombinedBuilder<TBase, any> { return this.compose(flatten() as any); } public interpose(separator: T): CombinedBuilder<TBase, T> { return this.compose(interpose(separator)); } public map<U>(f: (item: T) => U): CombinedBuilder<TBase, U> { return this.compose(map(f)); } public mapIndexed<U>( f: (item: T, index: number) => U, ): CombinedBuilder<TBase, U> { return this.compose(mapIndexed(f)); } public partitionAll(n: number): CombinedBuilder<TBase, T[]> { return this.compose(partitionAll(n)); } public partitionBy(f: (item: T) => any): CombinedBuilder<TBase, T[]> { return this.compose(partitionBy(f)); } public remove<U extends T>( pred: (item: T) => item is U, ): CombinedBuilder<TBase, Exclude<T, U>>; public remove(pred: (item: T) => boolean): CombinedBuilder<TBase, T>; public remove(pred: (item: T) => boolean): CombinedBuilder<TBase, T> { return this.compose(remove(pred)); } public removeAbsent(): CombinedBuilder<TBase, NonNullable<T>> { return this.remove(item => item == null) as CombinedBuilder< TBase, NonNullable<T> >; } public take(n: number): CombinedBuilder<TBase, T> { return this.compose(take(n)); } public takeNth(n: number): CombinedBuilder<TBase, T> { return this.compose(takeNth(n)); } public takeWhile(pred: (item: T) => boolean): CombinedBuilder<TBase, T> { return this.compose(takeWhile(pred)); } // ----- Reductions ----- public reduce<TResult>( reducer: QuittingReducer<TResult, T>, initialValue: TResult, ): TResult; public reduce<TResult, TCompleteResult>( reducer: CompletingTransformer<TResult, TCompleteResult, T>, ): TCompleteResult; public reduce<TResult, TCompleteResult>( reducer: | QuittingReducer<TResult, T> | CompletingTransformer<TResult, TCompleteResult, T>, initialValue?: TResult, ): TCompleteResult { if (typeof reducer === "function") { // Type coercion because in this branch, TResult and TCompleteResult are // the same, but the checker doesn't know that. return transduce( this.collection, this.build(), reducer, initialValue!, ) as any; } else { return transduce(this.collection, this.build(), reducer); } } // @ts-ignore public average(): number | null { return this.reduce(toAverage() as any); } public count(): number { return this.reduce(count()); } public every(pred: (item: T) => boolean): boolean { return this.reduce(every(pred)); } public find(pred: (item: T) => boolean): T | null { return this.reduce(find(pred)); } public first(): T | null { return this.reduce(first()); } public forEach(f: (item: T) => void): void { this.reduce(forEach(f)); } public isEmpty(): boolean { return this.reduce(isEmpty()); } public joinToString(separator: string): string { return this.reduce(joinToString(separator)); } // @ts-ignore public max(comparator: Comparator<T>): T | null { return this.reduce(max(comparator)); } // @ts-ignore public min(comparator: Comparator<T>): T | null { return this.reduce(min(comparator)); } public some(pred: (item: T) => boolean): boolean { return this.reduce(some(pred)); } // @ts-ignore public sum(): number { return this.reduce(sum() as any); } public toArray(): T[] { return this.reduce(toArray()); } public toMap<K, V>( getKey: (item: T) => K, getValue: (item: T) => V, ): Map<K, V> { return this.reduce(toMap(getKey, getValue)); } public toMapGroupBy<K>(getKey: (item: T) => K): Map<K, T[]>; public toMapGroupBy<K, V>( getKey: (item: T) => K, transformer: CompletingTransformer<any, V, T>, ): Map<K, V>; public toMapGroupBy<K>( getKey: (item: T) => K, transformer?: CompletingTransformer<any, any, T>, ): Map<K, any> { return this.reduce(toMapGroupBy(getKey, transformer as any)); } public toObject<K extends keyof any, V>( getKey: (item: T) => K, getValue: (item: T) => V, ): Record<K, V> { return this.reduce(toObject(getKey, getValue)); } public toObjectGroupBy<K extends keyof any>( getKey: (item: T) => K, ): Record<K, T[]>; public toObjectGroupBy<K extends keyof any, V>( getKey: (item: T) => K, transformer: CompletingTransformer<any, V, T>, ): Record<K, V>; public toObjectGroupBy<K extends keyof any>( getKey: (item: T) => K, transformer?: CompletingTransformer<any, any, T>, ): Record<K, any> { return this.reduce(toObjectGroupBy(getKey, transformer as any)); } public toSet(): Set<T> { return this.reduce(toSet()); } public toIterator(): IterableIterator<T> { return lazyTransduce(this.collection, this.build()); } }
the_stack
import React, { useState, useMemo, useCallback } from 'react'; import { UUIFunctionComponent, UUIFunctionComponentProps } from '../../core'; import { Popover, PopoverPlacement } from '../Popover'; import { ListBox as UUIListBox, ListBoxItem } from '../ListBox'; import { TextField as UUITextField } from '../Input'; import { pick, clone } from 'lodash-es'; import { Icons } from '../../icons/Icons'; import { usePendingValue } from '../../hooks/usePendingValue'; import { LoadingSpinner } from '../Loading/LoadingSpinner'; import ReactHelper from '../../utils/ReactHelper'; import { KeyCode } from '../../utils/keyboardHelper'; import { createComponentPropTypes, PropTypes, ExtraPropTypes } from '../../utils/createPropTypes'; export interface CascaderOption { value: string; /** * for input text display. */ label: string; /** * for custom render view. * if content and label are both provided, priority display content in option view. */ content?: React.ReactNode; /** * Whether the option of cascader is non-interactive. * @default false */ disabled?: boolean; children?: CascaderOption[]; } export interface CascaderFeatureProps { /** * Option items of Cascader. */ options: CascaderOption[]; /** * Placeholder text when there is no value. * @default none */ placeholder?: string; /** * The value to display in the input field. */ value: string[] | null; /** * Event handler invoked when input value is changed. */ onChange: (value: string[] | null) => void; /** * Indicate which type to trigger expand item list. * @default click */ expandTriggerType?: 'click' | 'hover'; /** * only invoke onChange when the final level option item select. * @default true */ changeOnFinalSelect?: boolean; /** * enable inputting text to search options. * @default false */ searchable?: boolean; searchPlaceholder?: string; /** * The custom search function, it invoked per option iteration. */ onSearch?: (option: CascaderOption, q: string) => boolean; /** * dropdown placement */ dropdownPlacement?: PopoverPlacement; /** * Whether the control is loading. * @default false */ loading?: boolean; /** * Whether the content of Cascader should be rendered inside a `Portal` where appending inside `portalContainer`(if it provided) or `document.body`. * @default false */ usePortal?: boolean; /** * The container element into which the overlay renders its contents, when `usePortal` is `true`. * This prop is ignored if `usePortal` is `false`. * @default document.body */ portalContainer?: HTMLElement; } export const CascaderOptionPropTypes = ExtraPropTypes.recursiveShape({ value: PropTypes.string.isRequired, label: PropTypes.string.isRequired, content: PropTypes.node, disabled: PropTypes.bool, }, 'children') export const CascaderPropTypes = createComponentPropTypes<CascaderFeatureProps>({ options: PropTypes.arrayOf(CascaderOptionPropTypes).isRequired, placeholder: PropTypes.string, value: ExtraPropTypes.nullable(PropTypes.arrayOf(PropTypes.string).isRequired), onChange: PropTypes.func.isRequired, expandTriggerType: PropTypes.oneOf(['click', 'hover']), changeOnFinalSelect: PropTypes.bool, searchable: PropTypes.bool, searchPlaceholder: PropTypes.string, onSearch: PropTypes.func, dropdownPlacement: PropTypes.oneOf([ "auto", "auto-start", "auto-end", "top", "bottom", "right", "left", "top-start", "top-end", "bottom-start", "bottom-end", "right-start", "right-end", "left-start", "left-end" ]), loading: PropTypes.bool, usePortal: PropTypes.bool, portalContainer: PropTypes.element, }) export const Cascader = UUIFunctionComponent({ name: 'Cascader', nodes: { Root: 'div', Activator: 'div', Placeholder: 'div', Result: 'div', DisplayValue: 'span', DisplayValueSeparator: 'span', Dropdown: Popover, DropdownIcon: Icons.ChevronDown, ActionBox: 'div', LevelList: 'div', OptionList: UUIListBox, Option: 'div', OptionLabel: 'div', OptionIcon: Icons.ChevronRight, SearchInput: UUITextField, SearchIcon: Icons.Search, SearchList: UUIListBox, SearchMatched: 'span', LoadingSpinner: LoadingSpinner, }, propTypes: CascaderPropTypes, }, (props: CascaderFeatureProps, { nodes, NodeDataProps }) => { /** * Component Nodes Spread */ const { Activator, Result, Placeholder, DisplayValue, DisplayValueSeparator, Root, Dropdown, DropdownIcon, LevelList, LoadingSpinner, SearchList, SearchIcon, OptionList, Option, OptionLabel, OptionIcon, ActionBox, SearchInput, } = nodes /** * Default props value */ const finalProps = { placeholder: props.placeholder || 'select options...', searchPlaceholder: props.searchPlaceholder || 'Search options...', expandTriggerType: props.expandTriggerType || 'click', searchable: props.searchable === undefined ? false : props.searchable, changeOnFinalSelect: props.changeOnFinalSelect === undefined ? true : props.changeOnFinalSelect, dropdownPlacement: props.dropdownPlacement === undefined ? 'bottom-start' : props.dropdownPlacement } /** * Component Inner States */ const [innerValue, setInnerValue, resetInnerValue] = usePendingValue(props.value, props.onChange) const [popoverActive, setPopoverActive] = useState(false) const [searchInputValue, setSearchInputValue] = useState('') /** * Generate tree hierarchy data of cascade options for rendering. */ type Levels = (CascaderOption & { selectedOption: Omit<CascaderOption, 'children'>[]; selected: boolean; })[][] const levels = useMemo(() => { const dfs = (data: Levels, index: number, selectedOption: CascaderOption[], options: CascaderOption[]) => { const getNewSelectedOption = (option: CascaderOption) => [...selectedOption, pick(option, 'value', 'label')] const getSelected = (option: CascaderOption) => innerValue ? option.value === innerValue[index] : false data.push(options.map((i) => ({ ...i, selectedOption: getNewSelectedOption(i), selected: getSelected(i) }))) if (innerValue && innerValue[index]) { const value = innerValue[index] const option = options.find((option) => option.value === value) if (option && option.children) { dfs(data, index+1, getNewSelectedOption(option), option.children) } } } const data: Levels = [] dfs(data, 0, [], props.options) return data }, [props.options, innerValue]) const renderValueResult = useCallback((options: CascaderOption[]) => { return ( <Result> {ReactHelper.join( options.map((option) => { return ( <DisplayValue key={option.value}>{option.content || option.label}</DisplayValue> ) }), <DisplayValueSeparator>/</DisplayValueSeparator> )} </Result> ) }, [DisplayValue, DisplayValueSeparator, Result]) const valueResult = useMemo(() => { if (!props.value || props.value.length === 0) return null const selectedOptions = findSelectedOptions(props.value, props.options) return renderValueResult(selectedOptions) }, [props.options, props.value, renderValueResult]) const displayResult = useMemo(() => { return props.value && props.value.length > 0 ? valueResult : <Placeholder>{finalProps.placeholder}</Placeholder> }, [Placeholder, finalProps.placeholder, props.value, valueResult]) /** * manage option ListBox data */ const optionListDataOfLevels = useMemo(() => { return levels.map((level, levelIndex) => { const items: ListBoxItem[] = level.map((option) => { return { id: option.value, content: ( <Option onMouseEnter={() => { if (finalProps.expandTriggerType !== 'hover') return if (option.disabled) return if (!option.children) return const newValue = [ ...(innerValue || []).slice(0, levelIndex), option.value, ] setInnerValue(newValue) }} > <OptionLabel>{option.content || option.label}</OptionLabel> <OptionIcon {...NodeDataProps({ 'hidden': !option.children, })} svgrProps={{ strokeWidth: 1 }} /> </Option> ), disabled: option.disabled, } }) const option = level.find((option) => option.selected) const selectedIds = option ? [option.value] : [] const handleOnSelect = (selectedIds: string[]) => { if (selectedIds && selectedIds.length === 0) return const selectedOption = findOneInAllOptions(selectedIds[0], props.options) if (!selectedOption) return const newValue = (innerValue || []).slice(0, levelIndex) if (selectedIds && selectedIds[0]) { newValue.push(selectedIds[0]) } const isLastLevel = !selectedOption.children const changeOnFinalSelect = finalProps.changeOnFinalSelect if (isLastLevel) { setInnerValue(newValue, true) setPopoverActive(false) } else { setInnerValue(newValue, !changeOnFinalSelect) } } return { items, selectedIds, handleOnSelect } }) }, [levels, Option, OptionLabel, OptionIcon, NodeDataProps, finalProps.expandTriggerType, finalProps.changeOnFinalSelect, innerValue, setInnerValue, props.options]) const searchListData = useMemo(() => { if (!searchInputValue) return null const matchedOptionsGroup = searchInOptions(searchInputValue, props.options, props.onSearch) const items = matchedOptionsGroup.map((options) => { const matchedSearchOptionId = JSON.stringify(options.map((i) => i.value)) return { id: matchedSearchOptionId, content: ( <Option>{renderValueResult(options)}</Option> ), } }) const selectedIds: string[] = [] const handleOnSelect = (selectedIds: string[]) => { if (selectedIds && selectedIds.length === 0) return const matchedSearchOptionId = selectedIds[0] const newValue = JSON.parse(matchedSearchOptionId) setInnerValue(newValue, true) setPopoverActive(false) } return { items, selectedIds, handleOnSelect } }, [Option, props.onSearch, props.options, renderValueResult, searchInputValue, setInnerValue]) return ( <Root {...NodeDataProps({ 'active': !!popoverActive, 'loading': !!props.loading, 'searchable': !!finalProps.searchable, })} role="select" tabIndex={0} onKeyDown={(event) => { switch (event.keyCode) { case KeyCode.Enter: case KeyCode.SpaceBar: if (!popoverActive) { setPopoverActive(true) } break case KeyCode.Escape: setPopoverActive(false) break default: // do nothing } }} > <Dropdown usePortal={props.usePortal} portalContainer={props.portalContainer} active={popoverActive} placement={finalProps.dropdownPlacement} onClickAway={() => { setPopoverActive(false) resetInnerValue() setSearchInputValue('') }} activator={ <Activator onClick={() => { setPopoverActive((value) => !value) }} > {displayResult} {props.loading && ( <LoadingSpinner width={16} height={16} /> )} <DropdownIcon width={20} height={20} svgrProps={{ strokeWidth: 1 }} /> </Activator> } > <ActionBox> {props.searchable && ( <SearchInput value={searchInputValue} onChange={(value) => { setSearchInputValue(value) }} placeholder={finalProps.searchPlaceholder} customize={{ Root: { extendChildrenBefore: ( <SearchIcon /> ) } }} /> )} {searchListData ? ( <SearchList items={searchListData.items} selectedIds={searchListData.selectedIds} onSelected={searchListData.handleOnSelect} /> ) : ( <LevelList> {optionListDataOfLevels.map((data, levelIndex) => { return ( <OptionList key={levelIndex} items={data.items} selectedIds={data.selectedIds} onSelected={data.handleOnSelect} /> ) })} </LevelList> )} </ActionBox> </Dropdown> </Root> ) }) export type CascaderProps = UUIFunctionComponentProps<typeof Cascader> function findOneInAllOptions(value: string | null, options: CascaderOption[]): CascaderOption | null { if (value === null) return null const dfs = (options?: CascaderOption[]): CascaderOption | null => { if (!options) return null for (const option of options) { if (option.value === value) return option const result = dfs(option.children) if (result) return result } return null } return dfs(options) } function findSelectedOptions(value: string[] | null, options: CascaderOption[]) { if (!value || value.length === 0) return [] const dfs = (data: CascaderOption[], index: number, options: CascaderOption[]) => { if (!value[index]) return const option = options.find((option) => option.value === value[index]) if (!option) return data.push(option) if (option.children) { dfs(data, index+1, option.children) } } const data: CascaderOption[] = [] dfs(data, 0, options) return data } function searchInOptions(q: string, options: CascaderOption[], predicate?: CascaderFeatureProps['onSearch']) { const current: CascaderOption[] = [] const flatOptions: CascaderOption[][] = [] const initialOption: CascaderOption = { label: '', value: '', children: options } const backtracking = (current: CascaderOption[], flatOptions: CascaderOption[][], option: CascaderOption) => { if (!option.children) { const searched = current.some((i) => !!(i as any)['matched']) if (searched) flatOptions.push(clone(current.map((i) => { delete (i as any)['matched'] return i }))) return } for (const child of option.children) { (child as any)['matched'] = (() => { return predicate ? predicate(child, q) : child.label.includes(q) })() current.push(child) backtracking(current, flatOptions, child) current.pop() } } backtracking(current, flatOptions, initialOption) return flatOptions }
the_stack
import {EventAggregator, Subscription} from 'aurelia-event-aggregator'; import {bindable, bindingMode, computedFrom, inject, observable} from 'aurelia-framework'; import {Router} from 'aurelia-router'; import {ValidateEvent, ValidationController} from 'aurelia-validation'; import { IConnection, IExtensionElement, IFormElement, IModdleElement, IShape, } from '@process-engine/bpmn-elements_contracts'; import {DataModels} from '@process-engine/management_api_contracts'; import {IDiagram} from '@process-engine/solutionexplorer.contracts'; import * as JSON5 from 'json5'; import { DeployResult, IElementRegistry, ISolutionEntry, IUserInputValidationRule, NotificationType, } from '../../../contracts/index'; import environment from '../../../environment'; import {NotificationService} from '../../../services/notification-service/notification.service'; import {BpmnIo} from '../bpmn-io/bpmn-io'; import {DeployDiagramService} from '../../../services/deploy-diagram-service/deploy-diagram.service'; import {SaveDiagramService} from '../../../services/save-diagram-service/save-diagram.service'; import {exposeFunctionForTesting} from '../../../services/expose-functionality-module/expose-functionality.module'; import {DiagramDetailService} from './service/diagram-detail.service'; import {isRunningInElectron} from '../../../services/is-running-in-electron-module/is-running-in-electron.module'; @inject( 'DiagramDetailService', 'NotificationService', EventAggregator, Router, ValidationController, DeployDiagramService, SaveDiagramService, ) export class DiagramDetail { @bindable() public activeDiagram: IDiagram; @bindable() public activeSolutionEntry: ISolutionEntry; @observable({changeHandler: 'correlationChanged'}) public customCorrelationId: string; @observable({changeHandler: 'diagramHasChangedChanged'}) public diagramHasChanged: boolean; @bindable({defaultBindingMode: bindingMode.oneWay}) public xml: string; @bindable() public initialToken: string; public bpmnio: BpmnIo; public showSaveForStartModal: boolean = false; public showStartEventModal: boolean = false; public showStartWithOptionsModal: boolean = false; public processesStartEvents: Array<DataModels.Events.Event> = []; public selectedStartEventId: string; public hasValidationError: boolean = false; public diagramIsInvalid: boolean = false; public showRemoteSolutionOnDeployModal: boolean = false; public remoteSolutions: Array<ISolutionEntry> = []; @observable public selectedRemoteSolution: ISolutionEntry; public showDiagramExistingModal: boolean = false; private diagramDetailService: DiagramDetailService; private notificationService: NotificationService; private eventAggregator: EventAggregator; private subscriptions: Array<Subscription>; private router: Router; private validationController: ValidationController; private ipcRenderer: any; private correlationIdValidationRegExpList: IUserInputValidationRule = { alphanumeric: /^[a-z0-9]/i, specialCharacters: /^[._ -]/i, german: /^[äöüß]/i, }; private clickedOnCustomStart: boolean = false; private deployDiagramService: DeployDiagramService; private saveDiagramService: SaveDiagramService; constructor( diagramDetailService: DiagramDetailService, notificationService: NotificationService, eventAggregator: EventAggregator, router: Router, validationController: ValidationController, deployDiagramService: DeployDiagramService, saveDiagramService: SaveDiagramService, ) { this.diagramDetailService = diagramDetailService; this.notificationService = notificationService; this.eventAggregator = eventAggregator; this.router = router; this.validationController = validationController; this.deployDiagramService = deployDiagramService; this.saveDiagramService = saveDiagramService; exposeFunctionForTesting('saveDiagramAs', (path: string): void => { this.saveDiagramAs(path); }); } public determineActivationStrategy(): string { return 'replace'; } public async getXML(): Promise<string> { return this.bpmnio.getXML(); } public attached(): void { this.diagramHasChanged = false; this.selectedRemoteSolution = this.getPreviouslySelectedRemoteSolution(); if (isRunningInElectron()) { this.ipcRenderer = (window as any).nodeRequire('electron').ipcRenderer; this.ipcRenderer.on('menubar__start_save_diagram_as', this.electronOnSaveDiagramAs); this.ipcRenderer.on('menubar__start_save_diagram', this.electronOnSaveDiagram); } this.subscriptions = [ this.validationController.subscribe((event: ValidateEvent) => { this.handleFormValidateEvents(event); }), this.eventAggregator.subscribe(environment.events.diagramDetail.saveDiagram, async () => { try { await this.saveDiagram(); } catch (error) { if (error.message === 'No path was selected.') { return; } throw error; } this.eventAggregator.publish(environment.events.diagramDetail.saveDiagramDone); }), this.eventAggregator.subscribe(environment.events.diagramDetail.uploadProcess, () => { this.deployDiagram(); }), this.eventAggregator.subscribe(environment.events.differsFromOriginal, (savingNeeded: boolean) => { this.diagramHasChanged = savingNeeded; }), this.eventAggregator.subscribe(environment.events.navBar.validationError, () => { this.diagramIsInvalid = true; }), this.eventAggregator.subscribe(environment.events.navBar.noValidationError, () => { this.diagramIsInvalid = false; }), this.eventAggregator.subscribe(environment.events.diagramDetail.startProcess, () => { this.showStartDialog(); }), this.eventAggregator.subscribe(environment.events.diagramDetail.startProcessWithOptions, async () => { this.clickedOnCustomStart = true; await this.showSelectStartEventDialog(); }), this.eventAggregator.subscribe(environment.events.diagramDetail.saveDiagramAs, () => { this.electronOnSaveDiagramAs(); }), this.eventAggregator.subscribe(environment.events.diagramChangedOutsideTheStudio, (diagramUri: string) => { const changedDiagramIsActiveDiagram: boolean = diagramUri === this.activeDiagramUri; if (changedDiagramIsActiveDiagram) { this.eventAggregator.publish(environment.events.differsFromOriginal, true); } }), ]; } public selectedRemoteSolutionChanged(): void { const selectedRemoteSolutionAsString: string = JSON.stringify(this.selectedRemoteSolution); localStorage.setItem('selectedRemoteSolution', selectedRemoteSolutionAsString); } public correlationChanged(newValue: string): void { const inputAsCharArray: Array<string> = newValue.split(''); const correlationIdPassesIdCheck: boolean = !inputAsCharArray.some((letter: string) => { return Object.values(this.correlationIdValidationRegExpList).forEach((regEx: RegExp, index: number) => { const letterIsInvalid: boolean = letter.match(this.correlationIdValidationRegExpList[index]) !== null; if (letterIsInvalid) { return false; } return true; }); }); const correlationIdDoesNotStartWithWhitespace: boolean = !newValue.match(/^\s/); const correlationIdDoesNotEndWithWhitespace: boolean = !newValue.match(/\s+$/); if ( correlationIdDoesNotStartWithWhitespace && correlationIdPassesIdCheck && correlationIdDoesNotEndWithWhitespace ) { this.hasValidationError = false; } else { this.hasValidationError = true; } } public detached(): void { if (isRunningInElectron()) { this.ipcRenderer.removeListener('menubar__start_save_diagram', this.electronOnSaveDiagram); this.ipcRenderer.removeListener('menubar__start_save_diagram_as', this.electronOnSaveDiagramAs); } for (const subscription of this.subscriptions) { subscription.dispose(); } } @computedFrom('activeDiagram.uri') public get activeDiagramUri(): string { return this.activeDiagram.uri; } public async setOptionsAndStart(): Promise<void> { if (this.hasValidationError) { return; } if (this.diagramHasChanged) { await this.saveDiagram(); } const parsedInitialToken: any = this.getInitialTokenValues(this.initialToken); await this.startProcess(parsedInitialToken); } public async startProcess(parsedInitialToken?: any): Promise<void> { if (this.selectedStartEventId === null) { return; } this.dropInvalidFormData(); this.getTokenFromStartEventAnnotation(); const defaultToken: any = this.getInitialTokenValues(this.initialToken); const startToken = defaultToken === '' ? undefined : defaultToken; const startRequestPayload: DataModels.ProcessModels.ProcessStartRequestPayload = { inputValues: parsedInitialToken || startToken, correlationId: this.customCorrelationId, }; try { const useDefaultStartCallbackType: undefined = undefined; const response: DataModels.ProcessModels.ProcessStartResponsePayload = await this.diagramDetailService.startProcessInstance( this.activeSolutionEntry.identity, this.activeDiagram.id, startRequestPayload, useDefaultStartCallbackType, this.selectedStartEventId, ); const {correlationId, processInstanceId} = response; this.router.navigateToRoute('live-execution-tracker', { diagramName: this.activeDiagram.id, solutionUri: this.activeSolutionEntry.uri, correlationId: correlationId, processInstanceId: processInstanceId, }); } catch (error) { this.notificationService.showNotification(NotificationType.ERROR, error.message); } this.clickedOnCustomStart = false; } public async saveChangesBeforeStart(): Promise<void> { this.showSaveForStartModal = false; await this.saveDiagram(); await this.showSelectStartEventDialog(); } public async saveDiagram(): Promise<void> { if (this.diagramIsInvalid) { return; } const xml: string = await this.bpmnio.getXML(); await this.bpmnio.saveDiagramState(this.activeDiagramUri); await this.saveDiagramService.saveDiagram(this.activeSolutionEntry, this.activeDiagram, xml); this.bpmnio.saveCurrentXML(); this.diagramHasChanged = false; } public async saveDiagramAs(path?: string): Promise<void> { if (this.diagramIsInvalid) { return; } const xml: string = await this.getXMLOrDisplayError(); if (!xml) { return; } await this.saveDiagramService.saveDiagramAs(this.activeSolutionEntry, this.activeDiagram, xml, path); this.bpmnio.saveStateForNewUri = true; this.bpmnio.saveCurrentXML(); this.diagramHasChanged = false; } /** * Opens a modal dialog to ask the user, which StartEvent he want's to * use to start the process. * * If there is only one StartEvent this method will select this StartEvent by * default. */ public async showSelectStartEventDialog(): Promise<void> { await this.updateProcessStartEvents(); const onlyOneStarteventAvailable: boolean = this.processesStartEvents.length === 1; if (onlyOneStarteventAvailable) { this.selectedStartEventId = this.processesStartEvents[0].id; this.continueStarting(); return; } this.showStartEventModal = true; this.showSaveForStartModal = false; } public continueStarting(): void { const functionCallDoesNotComeFromCustomModal: boolean = this.clickedOnCustomStart === false; if (functionCallDoesNotComeFromCustomModal) { this.startProcess(); this.clickedOnCustomStart = false; } else { this.showCustomStartModal(); } this.showStartEventModal = false; } public cancelDialog(): void { this.showSaveForStartModal = false; this.showStartEventModal = false; this.showStartWithOptionsModal = false; this.showRemoteSolutionOnDeployModal = false; this.clickedOnCustomStart = false; } public showCustomStartModal(): void { this.getTokenFromStartEventAnnotation(); this.showStartWithOptionsModal = true; } private getPreviouslySelectedRemoteSolution(): ISolutionEntry { const selectedRemoteSolutionFromLocalStorage: string = localStorage.getItem('selectedRemoteSolution'); if (selectedRemoteSolutionFromLocalStorage === null) { return undefined; } return JSON.parse(selectedRemoteSolutionFromLocalStorage); } private getInitialTokenValues(token: any): any { try { // If successful, the token is an object return JSON5.parse(token); } catch (error) { // If an error occurs, the token is something else. return token; } } private async getXMLOrDisplayError(): Promise<string> { try { return await this.bpmnio.getXML(); } catch (error) { this.notificationService.showNotification(NotificationType.ERROR, `Unable to get the XML: ${error}.`); return undefined; } } private getTokenFromStartEventAnnotation(): void { const elementRegistry: IElementRegistry = this.bpmnio.modeler.get('elementRegistry'); const noStartEventId: boolean = this.selectedStartEventId === undefined; let startEvent: IShape; if (noStartEventId) { startEvent = elementRegistry.filter((element: IShape) => { return element.type === 'bpmn:StartEvent'; })[0]; } else { startEvent = elementRegistry.get(this.selectedStartEventId); } const startEventAssociations: Array<IConnection> = startEvent.outgoing.filter((connection: IConnection) => { const connectionIsAssociation: boolean = connection.type === 'bpmn:Association'; return connectionIsAssociation; }); const associationWithStartToken: IConnection = startEventAssociations.find((connection: IConnection) => { const associationText: string = connection.target.businessObject.text; const associationTextIsEmpty: boolean = associationText === undefined || associationText === null; if (associationTextIsEmpty) { return undefined; } const token: string = associationText.trim(); return token.startsWith('StartToken:'); }); const associationWithStartTokenIsExisting: boolean = associationWithStartToken !== undefined; if (associationWithStartTokenIsExisting) { const untrimmedInitialToken: string = associationWithStartToken.target.businessObject.text; const untrimmedInitialTokenIsUndefined: boolean = untrimmedInitialToken === undefined; if (untrimmedInitialTokenIsUndefined) { this.initialToken = ''; return; } this.initialToken = untrimmedInitialToken.replace('StartToken:', '').trim(); return; } this.initialToken = ''; } private async updateProcessStartEvents(): Promise<void> { const startEventResponse: DataModels.Events.EventList = await this.diagramDetailService.getStartEventsForProcessModel( this.activeSolutionEntry.identity, this.activeDiagram.id, ); this.processesStartEvents = startEventResponse.events; } private async deployDiagram(): Promise<void> { const xml: string | undefined = this.diagramHasChanged ? await this.bpmnio.getXML() : undefined; const deployResult: DeployResult = await this.deployDiagramService.deployDiagram( this.activeSolutionEntry, this.activeDiagram, xml, ); if (deployResult === undefined) { return; } this.router.navigateToRoute('design', { diagramName: deployResult.diagram.name, solutionUri: deployResult.solution.uri, }); } /** * Opens a modal, if the diagram has unsaved changes and ask the user, * if he wants to save his changes. This is necessary to * execute the process. * * If there are no unsaved changes, no modal will be displayed. */ private async showStartDialog(): Promise<void> { if (this.diagramHasChanged) { this.showSaveForStartModal = true; } else { await this.showSelectStartEventDialog(); } } private electronOnSaveDiagramAs = async (_?: Event): Promise<void> => { await this.saveDiagramAs(); }; private electronOnSaveDiagram = async (_?: Event): Promise<void> => { this.eventAggregator.publish(environment.events.diagramDetail.saveDiagram); }; private handleFormValidateEvents(event: ValidateEvent): void { const eventIsValidateEvent: boolean = event.type !== 'validate'; if (eventIsValidateEvent) { return; } for (const result of event.results) { const resultIsNotValid: boolean = result.valid === false; if (resultIsNotValid) { this.eventAggregator.publish(environment.events.navBar.validationError); this.diagramIsInvalid = true; return; } } this.eventAggregator.publish(environment.events.navBar.noValidationError); this.diagramIsInvalid = false; } /** * In the current implementation this method only checks for UserTasks that have * empty or otherwise not allowed FormData in them. * * If that is the case the method will continue by deleting unused/not allowed * FormData to make sure the diagrams XML is further supported by Camunda. * * TODO: Look further into this if this method is not better placed at the FormsSection * in the Property Panel, also split this into two methods and name them right. */ private dropInvalidFormData(): void { const registry: IElementRegistry = this.bpmnio.modeler.get('elementRegistry'); registry.forEach((element: IShape) => { const elementIsUserTask: boolean = element.type === 'bpmn:UserTask'; if (elementIsUserTask) { const businessObj: IModdleElement = element.businessObject; const businessObjHasExtensionElements: boolean = businessObj.extensionElements !== undefined; if (businessObjHasExtensionElements) { const extensions: IExtensionElement = businessObj.extensionElements; extensions.values = extensions.values.filter((value: IFormElement) => { const typeIsNotCamundaFormData: boolean = value.$type !== 'camunda:FormData'; const elementContainsFields: boolean = value.fields !== undefined && value.fields.length > 0; const keepThisValue: boolean = typeIsNotCamundaFormData || elementContainsFields; return keepThisValue; }); const noExtensionValuesSet: boolean = extensions.values.length === 0; if (noExtensionValuesSet) { delete businessObj.extensionElements; } } } }); } }
the_stack
import * as Clutter from 'clutter'; import * as Gio from 'gio'; import * as GLib from 'glib'; import * as GObject from 'gobject'; import * as Shell from 'shell'; import { MsWindow } from 'src/layout/msWorkspace/msWindow'; import { MsManager } from 'src/manager/msManager'; import { assert, assertNotNull } from 'src/utils/assert'; import { Allocate, SetAllocation } from 'src/utils/compatibility'; import { diffLists } from 'src/utils/diff_list'; import { registerGObjectClass } from 'src/utils/gjs'; import { IdleDebounce } from 'src/utils/idle_debounce'; import { getSettings } from 'src/utils/settings'; import { ShellVersionMatch } from 'src/utils/shellVersionMatch'; import { MatButton } from 'src/widget/material/button'; import { MsApplicationLauncher } from 'src/widget/msApplicationLauncher'; import { ReorderableList } from 'src/widget/reorderableList'; import * as St from 'st'; import { layout, main as Main, popupMenu as PopupMenu } from 'ui'; import { MsWorkspace, Tileable } from '../msWorkspace'; const DND = imports.ui.dnd; import Monitor = layout.Monitor; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); const isTileableItem = (obj: any): obj is TileableItem => { return obj instanceof TileableItem; }; const isIconTaskBarItem = (obj: any): obj is IconTaskBarItem => { return obj instanceof IconTaskBarItem; }; const isTileableItemOrIconTaskBarItem = ( obj: any ): obj is TileableItem | IconTaskBarItem => { return isTileableItem(obj) || isIconTaskBarItem(obj); }; @registerGObjectClass export class TaskBar extends St.Widget { private _delegate: this; taskActiveIndicator: TaskActiveIndicator; taskButtonContainer: ReorderableList; msWorkspace: MsWorkspace; msWorkspaceSignals: number[]; tracker: Shell.WindowTracker; windowFocused: null; menuManager: PopupMenu.PopupMenuManager; constructor( msWorkspace: MsWorkspace, panelMenuManager: PopupMenu.PopupMenuManager ) { super({ name: 'taskBar', x_expand: true, reactive: true, }); this._delegate = this; this.taskActiveIndicator = new TaskActiveIndicator({ style_class: 'task-active-indicator', }); this.add_child(this.taskActiveIndicator); this.taskButtonContainer = new ReorderableList(false, [TaskBarItem]); this.taskButtonContainer.connect('actor-moved', (_, item, index) => { this.msWorkspace.setTileableAtIndex(item.tileable, index); this.msWorkspace.focusTileable(item.tileable); }); this.taskButtonContainer.connect( 'foreign-actor-inserted', (_, actor, index) => { if (actor.tileable instanceof MsWindow) { Me.msWorkspaceManager.setWindowToMsWorkspace( actor.tileable, this.msWorkspace ); this.msWorkspace.setTileableAtIndex(actor.tileable, index); this.msWorkspace.focusTileable(actor.tileable); Me.msWorkspaceManager.stateChanged(); } } ); this.taskButtonContainer.connect( 'drag-start', (_, actor, foreignActor) => { this.taskActiveIndicator.hide(); } ); this.taskButtonContainer.connect( 'drag-end', (_, actor, foreignActor) => { this.taskActiveIndicator.show(); } ); this.add_child(this.taskButtonContainer); this.msWorkspace = msWorkspace; this.connect('destroy', this._onDestroy.bind(this)); this.msWorkspaceSignals = [ msWorkspace.connect( 'tileableList-changed', (_, newTileableList) => { this.onTileableListChange(newTileableList); } ), msWorkspace.connect( 'tileable-focus-changed', (_, tileable, oldTileable) => { this.onFocusChanged(tileable, oldTileable); } ), ]; this.connect('scroll-event', (_, event) => { switch (event.get_scroll_direction()) { case Clutter.ScrollDirection.UP: this.msWorkspace.focusPreviousTileable(); break; case Clutter.ScrollDirection.DOWN: this.msWorkspace.focusNextTileable(); break; } }); this.tracker = Shell.WindowTracker.get_default(); this.windowFocused = null; this.menuManager = panelMenuManager; this.onTileableListChange(this.msWorkspace.tileableList); if (this.items[this.msWorkspace.focusedIndex]) { this.items[this.msWorkspace.focusedIndex].setActive(true); } } get items(): (TileableItem | IconTaskBarItem)[] { return this.taskButtonContainer .get_children() .filter(isTileableItemOrIconTaskBarItem); } /** * Update the current list of taskBarItem with the least of widget manipulation possible */ onTileableListChange(newTileableList: Tileable[]) { const { added: tileableToAdd, removed: tileableToRemove } = diffLists( this.items.map((item) => item.tileable), newTileableList ); for (const tileable of tileableToRemove) { const item = assertNotNull(this.getTaskBarItemOfTileable(tileable)); item.destroy(); } for (const tileable of tileableToAdd) { const item = this.createNewItemForTileable(tileable); this.taskButtonContainer.insert_child_at_index( item, newTileableList.indexOf(tileable) ); } // Ensure tileable position in case of reorder newTileableList.forEach((tileable, index) => { this.items[index].setTileable(tileable); }); } onFocusChanged( tileableFocused: Tileable, oldTileableFocused: Tileable | null ) { if (tileableFocused === oldTileableFocused) { return; } const previousItem = oldTileableFocused !== null ? this.getTaskBarItemOfTileable(oldTileableFocused) : null; const nextItem = this.getTaskBarItemOfTileable(tileableFocused); if (previousItem) { if (previousItem.has_style_class_name('active')) { previousItem.setActive(false); } } if (!nextItem) return; //if you change the class before animate the indicator there is an issue for retrieving the item.x nextItem.setActive(true); } /** Returns the item for the app which is currently active. * This can only return null in case all apps and the application launcher are removed from a workspace, but the application launcher will in practice always be there. */ getActiveItem(): TileableItem | IconTaskBarItem | null { if (this.items.length > 0) { return this.items[this.msWorkspace.focusedIndex]; } else { return null; } } createNewItemForTileable(tileable: Tileable) { let item: TileableItem | IconTaskBarItem; if (tileable instanceof MsWindow) { item = new TileableItem(tileable); this.menuManager.addMenu(assertNotNull(item.menu)); item.connect('middle-clicked', (_) => { if (item.tileable instanceof MsWindow) item.tileable.kill(); }); item.connect('close-clicked', (_) => { if (item.tileable instanceof MsWindow) item.tileable.kill(); }); } else { item = new IconTaskBarItem( tileable, Gio.icon_new_for_string( `${Me.path}/assets/icons/plus-symbolic.svg` ) ); } item.connect('left-clicked', (_) => { this.msWorkspace.focusTileable(item.tileable); }); return item; } getTaskBarItemOfTileable(tileable: Tileable) { return this.items.find((item) => { return item.tileable === tileable; }); } override vfunc_allocate( box: Clutter.ActorBox, flags?: Clutter.AllocationFlags ) { SetAllocation(this, box, flags); const themeNode = this.get_theme_node(); const contentBox = themeNode.get_content_box(box); Allocate(this.taskButtonContainer, contentBox, flags); const activeItem = this.getActiveItem(); if (activeItem) { this.taskActiveIndicator.show(); const taskActiveIndicatorBox = new Clutter.ActorBox({ x1: activeItem.x, x2: activeItem.x + activeItem.width, y1: contentBox.get_height() - this.taskActiveIndicator.height, y2: contentBox.get_height(), }); Allocate(this.taskActiveIndicator, taskActiveIndicatorBox, flags); } else { this.taskActiveIndicator.hide(); } } _onDestroy() { this.msWorkspaceSignals.forEach((signal) => this.msWorkspace.disconnect(signal) ); } } @registerGObjectClass export class TaskActiveIndicator extends St.Widget { static metaInfo: GObject.MetaInfo = { GTypeName: 'TaskActiveIndicator', }; constructor(...args: any[]) { super(...args); } prepareAnimation(newAllocation: Clutter.ActorBox) { this.translation_x = this.translation_x + this.x - newAllocation.x1; this.scale_x = (this.width * this.scale_x) / newAllocation.get_width(); } animate() { this.ease({ translation_x: 0, scale_x: 1, duration: 250, mode: Clutter.AnimationMode.EASE_OUT_QUAD, }); } vfunc_allocate(...args: [Clutter.ActorBox]) { if (this.width && this.mapped) { this.prepareAnimation(args[0]); GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => { this.animate(); return GLib.SOURCE_REMOVE; }); } super.vfunc_allocate(...args); } } @registerGObjectClass export class TaskBarItem extends MatButton { static metaInfo: GObject.MetaInfo = { GTypeName: 'TaskBarItem', Signals: { 'drag-dropped': {}, 'drag-over': { param_types: [GObject.TYPE_BOOLEAN], }, 'left-clicked': {}, 'middle-clicked': {}, }, }; private _delegate: this; draggable: boolean; contentActor: St.Widget; monitor: Monitor; menu: PopupMenu.PopupMenu | undefined; tileable: Tileable | undefined; constructor(contentActor: St.Widget, draggable: boolean) { super({ style_class: 'task-bar-item ', }); this.y_expand = true; this._delegate = this; this.draggable = draggable; this.contentActor = contentActor; this.monitor = assertNotNull(Main.layoutManager.primaryMonitor); this.set_child(this.contentActor); this.connect('primary-action', () => { this.emit('left-clicked'); }); this.connect('secondary-action', () => { if (this.menu !== undefined) { this.menu.toggle(); } }); this.connect('clicked', (actor, button) => { if (button === Clutter.BUTTON_MIDDLE) { this.emit('middle-clicked'); } }); } override vfunc_parent_set() { const actor = this.get_parent() || this; if (actor.is_mapped()) { this.monitor = assertNotNull( Main.layoutManager.findMonitorForActor(actor) ); } } override vfunc_get_preferred_height(_forWidth: number): [number, number] { const height = Me.msThemeManager.getPanelSize(this.monitor.index); return [height, height]; } setActive(active: boolean) { if (!active && this.has_style_class_name('active')) { this.remove_style_class_name('active'); } if (active && !this.has_style_class_name('active')) { this.add_style_class_name('active'); } } } @registerGObjectClass export class TileableItem extends TaskBarItem { static metaInfo: GObject.MetaInfo = { GTypeName: 'TileableItem', Signals: { 'close-clicked': {}, }, }; container: St.BoxLayout; // Safety: We definitely initialize this because we call setTileable from the constructor tileable!: Tileable; // Safety: We definitely initialize this because we call setTileable from the constructor app!: Shell.App | null; startIconContainer: St.Bin; endIconContainer: St.Bin; makePersistentAction: PopupMenu.PopupBaseMenuItem; unmakePersistentAction: PopupMenu.PopupBaseMenuItem; closeButton: St.Button; persistentIcon: St.Icon; title: St.Label; signalManager: MsManager; titleSignalKiller: (() => void) | undefined; closeIcon: St.Icon; icon: St.Widget | undefined; lastHeight: number | undefined; buildIconIdle: IdleDebounce<[number]>; constructor(tileable: MsWindow) { const container = new St.BoxLayout({ style_class: 'task-bar-item-content', }); super(container, true); this.container = container; this.buildIconIdle = new IdleDebounce(this.buildIcon.bind(this)); if (ShellVersionMatch('3.34')) { this.startIconContainer = new St.Bin({ y_align: 1, }); } else { this.startIconContainer = new St.Bin({ y_align: Clutter.ActorAlign.CENTER, }); } if (ShellVersionMatch('3.34')) { this.endIconContainer = new St.Bin({ y_align: 1, }); } else { this.endIconContainer = new St.Bin({ y_align: Clutter.ActorAlign.CENTER, }); } this.menu = new PopupMenu.PopupMenu(this, 0.5, St.Side.TOP); this.menu.actor.add_style_class_name('horizontal-panel-menu'); /* this.menu.addMenuItem( new PopupMenu.PopupSeparatorMenuItem(_('Open Windows')) ); */ this.makePersistentAction = this.menu.addAction( 'Make this fully persistent', () => { if (this.tileable instanceof MsWindow) { this.tileable.persistent = true; } this.endIconContainer.set_child(this.persistentIcon); this.makePersistentAction.hide(); this.unmakePersistentAction.show(); }, Gio.icon_new_for_string(`${Me.path}/assets/icons/pin-symbolic.svg`) ); this.unmakePersistentAction = this.menu.addAction( 'Unmake this fully persistent', () => { if (this.tileable instanceof MsWindow) { this.tileable.persistent = false; } this.endIconContainer.set_child(this.closeButton); this.makePersistentAction.show(); this.unmakePersistentAction.hide(); }, Gio.icon_new_for_string( `${Me.path}/assets/icons/pin-off-symbolic.svg` ) ); this.menu.addAction( 'Close', () => { this.emit('close-clicked'); }, Gio.icon_new_for_string( `${Me.path}/assets/icons/close-symbolic.svg` ) ); /* let item = new PopupMenu.PopupBaseMenuItem({ activate: true }); item.add_child( new St.Label({ text: 'Make window persistent', }) ); this.menu.box.add_child(item); */ Main.layoutManager.uiGroup.add_actor(this.menu.actor); this.menu.actor.hide(); // TITLE this.title = new St.Label({ style_class: 'task-bar-item-title', y_align: Clutter.ActorAlign.CENTER, }); Me.tooltipManager.add(this.title, { relativeActor: this }); this.signalManager = new MsManager(); this.style = getSettings('theme').get_string('taskbar-item-style'); this.signalManager.observe( getSettings('theme'), 'changed::taskbar-item-style', () => { this.style = getSettings('theme').get_string('taskbar-item-style'); this.updateTitle(); this.setStyle(); } ); this.connect('destroy', this._onDestroy.bind(this)); // CLOSE BUTTON this.closeIcon = new St.Icon({ style_class: 'task-small-icon', gicon: Gio.icon_new_for_string( `${Me.path}/assets/icons/close-symbolic.svg` ), }); this.closeButton = new St.Button({ style_class: 'task-close-button', child: this.closeIcon, }); this.closeButton.connect('clicked', () => { this.emit('close-clicked'); }); this.persistentIcon = new St.Icon({ style_class: 'task-small-icon', gicon: Gio.icon_new_for_string( `${Me.path}/assets/icons/pin-symbolic.svg` ), }); // LAYOUT CONTAINER this.container.add_child(this.startIconContainer); this.container.add_child(this.title); this.container.add_child(this.endIconContainer); this.setTileable(tileable); } setTileable(tileable: Tileable) { if (tileable === this.tileable) return; if (this.titleSignalKiller) this.titleSignalKiller(); this.tileable = tileable; this.app = tileable instanceof MsWindow ? tileable.app : null; if (this.icon) { this.buildIcon(assertNotNull(this.lastHeight)); } this.titleSignalKiller = this.signalManager.observe( this.tileable, 'title-changed', () => this.updateTitle() ); if (this.tileable instanceof MsWindow && this.tileable._persistent) { this.makePersistentAction.hide(); this.unmakePersistentAction.show(); this.endIconContainer.set_child(this.persistentIcon); } else { this.unmakePersistentAction.hide(); this.makePersistentAction.show(); this.endIconContainer.set_child(this.closeButton); } this.setStyle(); } setStyle() { this.updateTitle(); if (this.style == 'icon') { this.title.hide(); } else { this.title.show(); } } buildIcon(height: number) { if (this.icon) this.icon.destroy(); assert(this.app !== null, 'cannot build an icon without an app'); this.lastHeight = height; const icon = this.app.create_icon_texture(height / 2); assert(icon instanceof St.Widget, 'expected icon to be a widget'); this.icon = icon; this.icon.style_class = 'app-icon'; this.icon.set_size(height / 2, height / 2); this.startIconContainer.set_child(this.icon); const smallIconSize = Math.max(Math.round(height / 3), 18); this.persistentIcon.set_icon_size(smallIconSize); this.closeIcon.set_icon_size(smallIconSize); this.queue_relayout(); } setActive(active: boolean) { super.setActive(active); this.updateTitle(); } // Update the title and crop it if it's too long updateTitle() { assert(this.tileable !== undefined, 'item has no tileable'); if ( this.tileable instanceof MsApplicationLauncher || this.app === null ) { this.title.text = ''; } else { if (this.style == 'full') { if (this.tileable.title.includes(this.app.get_name())) { this.title.text = this.tileable.title; } else { const escapedAppName = GLib.markup_escape_text( this.app.get_name(), -1 ); const escapedTitle = GLib.markup_escape_text( this.tileable.title, -1 ); (this.title.get_clutter_text() as Clutter.Text).set_markup( `${escapedTitle}<span alpha="${ this.has_style_class_name('active') ? '40%' : '20%' }"> - ${escapedAppName}</span>` ); } } else if (this.style == 'name') { this.title.text = this.app.get_name(); } } } override vfunc_allocate(...args: [Clutter.ActorBox]) { const box = args[0]; const height = box.get_height(); if (!this.icon || this.lastHeight != height) { this.buildIconIdle.schedule(height); } super.vfunc_allocate(...args); } _onDestroy() { this.buildIconIdle.cancel(); this.signalManager.destroy(); if (this.menu !== undefined) this.menu.destroy(); } } @registerGObjectClass export class IconTaskBarItem extends TaskBarItem { container: St.Bin; tileable: Tileable; icon: St.Icon; buildIconIdle: IdleDebounce<[number]>; constructor(tileable: Tileable, gicon: Gio.IconPrototype) { const container = new St.Bin({ style_class: 'task-bar-icon-container', }); super(container, false); this.container = container; this.buildIconIdle = new IdleDebounce((height) => { this.icon.set_icon_size(height); }); this.icon = new St.Icon({ gicon, style_class: 'app-icon', icon_size: Me.msThemeManager.getPanelSizeNotScaled() / 2, }); this.container.set_child(this.icon); this.tileable = tileable; this.connect('destroy', this._onDestroy.bind(this)); } setTileable(tileable: Tileable) { if (tileable === this.tileable) return; this.tileable = tileable; } override vfunc_get_preferred_width(_forHeight: number): [number, number] { return [_forHeight, _forHeight]; } override vfunc_allocate(...args: [Clutter.ActorBox]) { const box = args[0]; const height = box.get_height() / 2; if (this.icon && this.icon.get_icon_size() != height) { this.buildIconIdle.schedule(height); } super.vfunc_allocate(...args); } _onDestroy() { this.buildIconIdle.cancel(); } }
the_stack
import * as child_process from 'child_process'; import * as vscode from 'vscode'; import * as chai from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as sinon from 'sinon'; import { TestUtil } from '../../TestUtil'; import * as path from 'path'; import { YeomanUtil } from '../../../extension/util/YeomanUtil'; import { SettingConfigurations } from '../../../extension/configurations'; import { FabricRuntimeState } from '../../../extension/fabric/FabricRuntimeState'; import { LocalMicroEnvironment } from '../../../extension/fabric/environments/LocalMicroEnvironment'; import { OutputAdapter, LogType, FabricEnvironmentRegistry, FabricRuntimeUtil, FabricEnvironmentRegistryEntry, EnvironmentType } from 'ibm-blockchain-platform-common'; import * as stream from 'stream'; import { VSCodeBlockchainDockerOutputAdapter } from '../../../extension/logging/VSCodeBlockchainDockerOutputAdapter'; import { TimerUtil } from '../../../extension/util/TimerUtil'; import { UserInputUtil } from '../../../extension/commands/UserInputUtil'; const should: Chai.Should = chai.should(); chai.use(chaiAsPromised); // tslint:disable no-unused-expression describe('LocalMicroEnvironment', () => { const originalPlatform: string = process.platform; const originalSpawn: any = child_process.spawn; const environmentPath: string = path.join(__dirname, '..', '..', 'test', 'tmp', 'environments', FabricRuntimeUtil.LOCAL_FABRIC); let environment: LocalMicroEnvironment; let sandbox: sinon.SinonSandbox; let stopLogsStub: sinon.SinonStub; // tslint:disable max-classes-per-file // tslint:disable no-console class TestFabricOutputAdapter implements OutputAdapter { public log(value: string): void { console.log(value); } public error(value: string): void { console.error(value); } } function mockSuccessCommand(): any { if (originalPlatform === 'win32') { return originalSpawn('cmd', ['/c', 'echo stdout&& echo stderr>&2&& exit 0']); } else { return originalSpawn('/bin/sh', ['-c', 'echo stdout && echo stderr >&2 && true']); } } function mockFailureCommand(): any { if (originalPlatform === 'win32') { return originalSpawn('cmd', ['/c', 'echo stdout&& echo stderr>&2&& exit 1']); } else { return originalSpawn('/bin/sh', ['-c', 'echo stdout && echo stderr >&2 && false']); } } before(async () => { await TestUtil.setupTests(sandbox); // await TestUtil.setupLocalFabric(); }); beforeEach(async () => { sandbox = sinon.createSandbox(); await TestUtil.startLocalFabric(); environment = new LocalMicroEnvironment(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1, UserInputUtil.V2_0); environment['path'] = environmentPath; const localSetting: any = {}; localSetting[FabricRuntimeUtil.LOCAL_FABRIC] = 8080; await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, localSetting, vscode.ConfigurationTarget.Global); await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_ENABLE_CUSTOM_LOCAL_ENVIRONMENT_START_IMAGE, false, vscode.ConfigurationTarget.Global); await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_CUSTOM_LOCAL_ENVIRONMENT_START_IMAGE_VALUE, 'ibmcom/ibp-microfab:latest', vscode.ConfigurationTarget.Global); stopLogsStub = sandbox.stub(LocalMicroEnvironment.prototype, 'stopLogs').returns(undefined); }); afterEach(async () => { sandbox.restore(); }); describe('#create', () => { it('should create a new network for the first time', async () => { const localSetting: any = {}; await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, localSetting, vscode.ConfigurationTarget.Global); const addSpy: sinon.SinonSpy = sandbox.spy(FabricEnvironmentRegistry.instance(), 'add'); const deleteSpy: sinon.SinonSpy = sandbox.spy(FabricEnvironmentRegistry.instance(), 'delete'); const runStub: sinon.SinonStub = sandbox.stub(YeomanUtil, 'run').resolves(); await environment.create(); environment.port.should.equal(8080); deleteSpy.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, true); addSpy.should.have.been.calledOnceWithExactly({ name: FabricRuntimeUtil.LOCAL_FABRIC, managedRuntime: true, environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, environmentDirectory: environment.getPath(), numberOfOrgs: 1, url: environment.getURL(), fabricCapabilities: UserInputUtil.V2_0 } as FabricEnvironmentRegistryEntry); runStub.should.have.been.calledOnceWithExactly('fabric:network', { destination: environment.getPath(), dockerName: FabricRuntimeUtil.LOCAL_FABRIC.replace(/[^A-Za-z0-9]/g, ''), name: FabricRuntimeUtil.LOCAL_FABRIC, numOrganizations: 1, port: 8080, fabricCapabilities: UserInputUtil.V2_0 }); }); it('should create a new network using the ports in the settings', async () => { const addSpy: sinon.SinonSpy = sandbox.spy(FabricEnvironmentRegistry.instance(), 'add'); const deleteSpy: sinon.SinonSpy = sandbox.spy(FabricEnvironmentRegistry.instance(), 'delete'); const runStub: sinon.SinonStub = sandbox.stub(YeomanUtil, 'run').resolves(); await environment.create(); deleteSpy.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, true); addSpy.should.have.been.calledOnceWithExactly({ name: FabricRuntimeUtil.LOCAL_FABRIC, managedRuntime: true, environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, environmentDirectory: environment.getPath(), numberOfOrgs: 1, url: environment.getURL(), fabricCapabilities: UserInputUtil.V2_0 } as FabricEnvironmentRegistryEntry); runStub.should.have.been.calledOnceWithExactly('fabric:network', { destination: environment.getPath(), dockerName: FabricRuntimeUtil.LOCAL_FABRIC.replace(/[^A-Za-z0-9]/g, ''), name: FabricRuntimeUtil.LOCAL_FABRIC, numOrganizations: 1, port: 8080, fabricCapabilities: UserInputUtil.V2_0 }); }); it('should create a new network using ports which have been updated in the settings', async () => { const localSetting: any = {}; localSetting[FabricRuntimeUtil.LOCAL_FABRIC] = 9080; await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, localSetting, vscode.ConfigurationTarget.Global); const addSpy: sinon.SinonSpy = sandbox.spy(FabricEnvironmentRegistry.instance(), 'add'); const deleteSpy: sinon.SinonSpy = sandbox.spy(FabricEnvironmentRegistry.instance(), 'delete'); const runStub: sinon.SinonStub = sandbox.stub(YeomanUtil, 'run').resolves(); environment = new LocalMicroEnvironment(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1, undefined); await environment.create(); environment.port.should.equal(9080); deleteSpy.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, true); addSpy.should.have.been.calledOnceWithExactly({ name: FabricRuntimeUtil.LOCAL_FABRIC, managedRuntime: true, environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, environmentDirectory: environment.getPath(), numberOfOrgs: 1, url: environment.getURL(), fabricCapabilities: UserInputUtil.V2_0 } as FabricEnvironmentRegistryEntry); runStub.should.have.been.calledOnceWithExactly('fabric:network', { destination: environment.getPath(), dockerName: FabricRuntimeUtil.LOCAL_FABRIC.replace(/[^A-Za-z0-9]/g, ''), name: FabricRuntimeUtil.LOCAL_FABRIC, numOrganizations: 1, port: 9080, fabricCapabilities: UserInputUtil.V2_0 }); }); it('should assume network has V2 capabilities if not set', async () => { const localSetting: any = {}; await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, localSetting, vscode.ConfigurationTarget.Global); const addSpy: sinon.SinonSpy = sandbox.spy(FabricEnvironmentRegistry.instance(), 'add'); const deleteSpy: sinon.SinonSpy = sandbox.spy(FabricEnvironmentRegistry.instance(), 'delete'); const runStub: sinon.SinonStub = sandbox.stub(YeomanUtil, 'run').resolves(); await environment.create(); environment.port.should.equal(8080); deleteSpy.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, true); addSpy.should.have.been.calledOnceWithExactly({ name: FabricRuntimeUtil.LOCAL_FABRIC, managedRuntime: true, environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, environmentDirectory: environment.getPath(), numberOfOrgs: 1, url: environment.getURL(), fabricCapabilities: UserInputUtil.V2_0 } as FabricEnvironmentRegistryEntry); runStub.should.have.been.calledOnceWithExactly('fabric:network', { destination: environment.getPath(), dockerName: FabricRuntimeUtil.LOCAL_FABRIC.replace(/[^A-Za-z0-9]/g, ''), name: FabricRuntimeUtil.LOCAL_FABRIC, numOrganizations: 1, port: 8080, fabricCapabilities: UserInputUtil.V2_0 }); }); }); ['start', 'stop', 'teardown', 'kill_chaincode'].forEach((verb: string) => { describe(`#${verb}`, () => { let createStub: sinon.SinonStub; let isRunningStub: sinon.SinonStub; let setStateSpy: sinon.SinonSpy; let getConfigurationStub: sinon.SinonStub; let getSettingsStub: sinon.SinonStub; let isCreatedStub: sinon.SinonStub; beforeEach(() => { createStub = sandbox.stub(environment, 'create'); isCreatedStub = sandbox.stub(environment, 'isCreated'); isCreatedStub.resolves(true); isRunningStub = sandbox.stub(environment, 'isRunning').resolves(false); setStateSpy = sandbox.spy(LocalMicroEnvironment.prototype, 'setState'); getSettingsStub = sandbox.stub(); getConfigurationStub = sandbox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: getSettingsStub, update: sandbox.stub().callThrough() }); }); it(`should execute the ${verb}.sh script and handle success (Linux/MacOS)`, async () => { sandbox.stub(process, 'platform').value('linux'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); if (verb !== 'kill_chaincode') { spawnStub.withArgs('/bin/sh', [`${verb}.sh`], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); } else { spawnStub.withArgs('/bin/sh', [`${verb}.sh`, 'mySmartContract', '0.0.1'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); } if (verb !== 'kill_chaincode') { await environment[verb](); } else { await environment['killChaincode'](['mySmartContract', '0.0.1']); } spawnStub.should.have.been.calledOnce; spawnStub.getCall(0).args[2].env.CORE_CHAINCODE_MODE.should.equal('dev'); if (verb !== 'start' && verb !== 'kill_chaincode') { stopLogsStub.should.have.been.called; } if (verb === 'kill_chaincode') { spawnStub.should.have.been.calledWith('/bin/sh', [`${verb}.sh`, 'mySmartContract', '0.0.1'], sinon.match.any); } else { spawnStub.should.have.been.calledWith('/bin/sh', [`${verb}.sh`], sinon.match.any); } }); it(`should execute the ${verb}.sh script and handle an error (Linux/MacOS)`, async () => { sandbox.stub(process, 'platform').value('linux'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); if (verb !== 'kill_chaincode') { spawnStub.withArgs('/bin/sh', [`${verb}.sh`], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); } else { spawnStub.withArgs('/bin/sh', [`${verb}.sh`, 'mySmartContract', '0.0.1'], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); } if (verb !== 'kill_chaincode') { await environment[verb]().should.be.rejectedWith(`Failed to execute command "/bin/sh" with arguments "${verb}.sh" return code 1`); } else { await environment['killChaincode'](['mySmartContract', '0.0.1']).should.be.rejectedWith(`Failed to execute command "/bin/sh" with arguments "${verb}.sh, mySmartContract, 0.0.1" return code 1`); } spawnStub.should.have.been.calledOnce; if (verb !== 'kill_chaincode') { spawnStub.should.have.been.calledWith('/bin/sh', [`${verb}.sh`], sinon.match.any); } else { spawnStub.should.have.been.calledWith('/bin/sh', [`${verb}.sh`, 'mySmartContract', '0.0.1'], sinon.match.any); } if (verb !== 'start' && verb !== 'kill_chaincode') { stopLogsStub.should.have.been.called; } }); it(`should execute the ${verb}.sh script using a custom output adapter (Linux/MacOS)`, async () => { sandbox.stub(process, 'platform').value('linux'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); if (verb !== 'kill_chaincode') { spawnStub.withArgs('/bin/sh', [`${verb}.sh`], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); } else { spawnStub.withArgs('/bin/sh', [`${verb}.sh`, 'mySmartContract', '0.0.1'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); } const outputAdapter: sinon.SinonStubbedInstance<TestFabricOutputAdapter> = sandbox.createStubInstance(TestFabricOutputAdapter); if (verb !== 'kill_chaincode') { await environment[verb](outputAdapter); } else { await environment['killChaincode'](['mySmartContract', '0.0.1'], outputAdapter); } outputAdapter.log.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'stdout'); outputAdapter.log.getCall(1).should.have.been.calledWith(LogType.INFO, undefined, 'stderr'); if (verb !== 'start' && verb !== 'kill_chaincode') { stopLogsStub.should.have.been.called; } }); if (verb !== 'kill_chaincode') { it(`should publish busy events and set state before and after handling success (Linux/MacOS)`, async () => { sandbox.stub(process, 'platform').value('linux'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', [`${verb}.sh`], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); environment.on('busy', eventStub); if (verb === 'start') { isRunningStub.resolves(true); } else { isRunningStub.resolves(false); } await environment[verb](); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); if (verb === 'start') { environment.getState().should.equal(FabricRuntimeState.STARTED); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.STARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STARTED); } else if (verb === 'stop' || verb === 'teardown') { environment.getState().should.equal(FabricRuntimeState.STOPPED); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.STOPPING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STOPPED); stopLogsStub.should.have.been.called; } }); it(`should publish busy events and set state before and after handling an error (Linux/MacOS)`, async () => { sandbox.stub(process, 'platform').value('linux'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', [`${verb}.sh`], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); if (verb === 'start') { isRunningStub.resolves(false); } else { isRunningStub.resolves(true); } environment.on('busy', eventStub); await environment[verb]().should.be.rejectedWith(`Failed to execute command "/bin/sh" with arguments "${verb}.sh" return code 1`); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); if (verb === 'start') { environment.getState().should.equal(FabricRuntimeState.STOPPED); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.STARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STOPPED); } else if (verb === 'stop' || verb === 'teardown') { environment.getState().should.equal(FabricRuntimeState.STARTED); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.STOPPING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STARTED); stopLogsStub.should.have.been.called; } }); } it(`should execute the ${verb}.cmd script and handle success (Windows)`, async () => { sandbox.stub(process, 'platform').value('win32'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); if (verb !== 'kill_chaincode') { spawnStub.withArgs('cmd', ['/c', `${verb}.cmd`], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); } else { spawnStub.withArgs('cmd', ['/c', `${verb}.cmd`, 'mySmartContract', '0.0.1'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); } if (verb !== 'kill_chaincode') { await environment[verb](); } else { await environment['killChaincode'](['mySmartContract', '0.0.1']); } spawnStub.should.have.been.calledOnce; if (verb !== 'kill_chaincode') { spawnStub.should.have.been.calledWith('cmd', ['/c', `${verb}.cmd`], sinon.match.any); } else { spawnStub.should.have.been.calledWith('cmd', ['/c', `${verb}.cmd`, 'mySmartContract', '0.0.1'], sinon.match.any); } spawnStub.getCall(0).args[2].env.CORE_CHAINCODE_MODE.should.equal('dev'); if (verb !== 'generate' && verb !== 'start' && verb !== 'kill_chaincode') { stopLogsStub.should.have.been.called; } }); it(`should execute the ${verb}.cmd script and handle an error (Windows)`, async () => { sandbox.stub(process, 'platform').value('win32'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); if (verb !== 'kill_chaincode') { spawnStub.withArgs('cmd', ['/c', `${verb}.cmd`], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); } else { spawnStub.withArgs('cmd', ['/c', `${verb}.cmd`, 'mySmartContract', '0.0.1'], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); } if (verb !== 'kill_chaincode') { await environment[verb]().should.be.rejectedWith(`Failed to execute command "cmd" with arguments "/c, ${verb}.cmd" return code 1`); } else { await environment['killChaincode'](['mySmartContract', '0.0.1']).should.be.rejectedWith(`Failed to execute command "cmd" with arguments "/c, ${verb}.cmd, mySmartContract, 0.0.1" return code 1`); } spawnStub.should.have.been.calledOnce; if (verb !== 'kill_chaincode') { spawnStub.should.have.been.calledWith('cmd', ['/c', `${verb}.cmd`], sinon.match.any); } else { spawnStub.should.have.been.calledWith('cmd', ['/c', `${verb}.cmd`, 'mySmartContract', '0.0.1'], sinon.match.any); } if (verb !== 'start' && verb !== 'kill_chaincode') { stopLogsStub.should.have.been.called; } }); it(`should execute the ${verb}.cmd script using a custom output adapter (Windows)`, async () => { sandbox.stub(process, 'platform').value('win32'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); if (verb !== 'kill_chaincode') { spawnStub.withArgs('cmd', ['/c', `${verb}.cmd`], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); } else { spawnStub.withArgs('cmd', ['/c', `${verb}.cmd`, 'mySmartContract', '0.0.1'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); } const outputAdapter: sinon.SinonStubbedInstance<TestFabricOutputAdapter> = sandbox.createStubInstance(TestFabricOutputAdapter); if (verb !== 'kill_chaincode') { await environment[verb](outputAdapter); } else { await environment['killChaincode'](['mySmartContract', '0.0.1'], outputAdapter); } outputAdapter.log.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'stdout'); outputAdapter.log.getCall(1).should.have.been.calledWith(LogType.INFO, undefined, 'stderr'); if (verb !== 'start' && verb !== 'kill_chaincode') { stopLogsStub.should.have.been.called; } }); if (verb !== 'kill_chaincode') { it(`should publish busy events and set state before and after handling success (Windows)`, async () => { if (verb === 'kill_chaincode') { // don't need to do test for kill chaincode return; } sandbox.stub(process, 'platform').value('win32'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', `${verb}.cmd`], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); if (verb === 'start') { isRunningStub.resolves(true); } else { isRunningStub.resolves(false); } environment.on('busy', eventStub); await environment[verb](); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); if (verb === 'start') { environment.getState().should.equal(FabricRuntimeState.STARTED); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.STARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STARTED); } else if (verb === 'stop' || verb === 'teardown') { environment.getState().should.equal(FabricRuntimeState.STOPPED); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.STOPPING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STOPPED); stopLogsStub.should.have.been.called; } }); it(`should publish busy events and set state before and after handling an error (Windows)`, async () => { sandbox.stub(process, 'platform').value('win32'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', `${verb}.cmd`], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); environment.on('busy', eventStub); if (verb === 'start') { isRunningStub.resolves(false); } else { isRunningStub.resolves(true); } await environment[verb]().should.be.rejectedWith(`Failed to execute command "cmd" with arguments "/c, ${verb}.cmd" return code 1`); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); if (verb === 'start') { environment.getState().should.equal(FabricRuntimeState.STOPPED); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.STARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STOPPED); } else if (verb === 'stop' || verb === 'teardown') { environment.getState().should.equal(FabricRuntimeState.STARTED); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.STOPPING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STARTED); stopLogsStub.should.have.been.called; } }); } if (verb === 'teardown') { it('should recreate the runtime after tearing it down', async () => { sandbox.stub(child_process, 'spawn').callsFake(() => { return mockSuccessCommand(); }); await environment.teardown(); createStub.should.have.been.calledOnce; }); } if (verb === 'start') { it('should create the runtime if not created', async () => { sandbox.stub(child_process, 'spawn').callsFake(() => { return mockSuccessCommand(); }); isCreatedStub.resolves(false); await environment[verb](); createStub.should.have.been.calledOnce; }); } }); }); describe('#start', () => { it('should use custom image to start local environments', async () => { await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_ENABLE_CUSTOM_LOCAL_ENVIRONMENT_START_IMAGE, true, vscode.ConfigurationTarget.Global); await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_CUSTOM_LOCAL_ENVIRONMENT_START_IMAGE_VALUE, 'ibmcom/ibp-microfab:latest', vscode.ConfigurationTarget.Global); const createStub: sinon.SinonStub = sandbox.stub(environment, 'create'); sandbox.stub(child_process, 'spawn').callsFake(() => { return mockSuccessCommand(); }); const executeSpy: sinon.SinonSpy = sandbox.spy(LocalMicroEnvironment.prototype, 'execute'); await environment.start(); executeSpy.should.have.been.calledWithExactly('start', ['ibmcom/ibp-microfab:latest'], sinon.match.any); createStub.should.not.have.been.called; }); }); describe('#delete', () => { it('shouldnt recreate the runtime after deleting it', async () => { const createStub: sinon.SinonStub = sandbox.stub(environment, 'create'); sandbox.stub(child_process, 'spawn').callsFake(() => { return mockSuccessCommand(); }); await environment.delete(); createStub.should.not.have.been.called; }); }); describe('#isCreated', () => { it('should return true if the runtime directory exists', async () => { await environment.isCreated().should.eventually.be.true; }); it('should return false if the runtime directory does not exist', async () => { await FabricEnvironmentRegistry.instance().clear(); await environment.isCreated().should.eventually.be.false; }); }); describe('#updateUserSettings', () => { it('should update the user settings if the runtime exists', async () => { const updateStub: sinon.SinonStub = sandbox.stub(); const getConfigurationStub: sinon.SinonStub = sandbox.stub(vscode.workspace, 'getConfiguration'); const setting: any = {}; setting[FabricRuntimeUtil.LOCAL_FABRIC] = 10080; getConfigurationStub.returns({ get: sandbox.stub().returns(setting), update: updateStub }); await environment.updateUserSettings(FabricRuntimeUtil.LOCAL_FABRIC); setting[FabricRuntimeUtil.LOCAL_FABRIC] = environment.port; updateStub.should.have.been.calledWith(SettingConfigurations.FABRIC_RUNTIME, setting); }); it(`should update the user settings if the runtime doesn't exist`, async () => { const updateStub: sinon.SinonStub = sandbox.stub(); const getConfigurationStub: sinon.SinonStub = sandbox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: sandbox.stub().resolves({}), update: updateStub }); await environment.updateUserSettings(FabricRuntimeUtil.LOCAL_FABRIC); updateStub.should.have.been.calledWith(SettingConfigurations.FABRIC_RUNTIME, { '1 Org Local Fabric': 8080 }); }); }); describe('#isRunning', () => { it('should return false if not created (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); sandbox.stub(environment, 'isCreated').resolves(false); await environment.isRunning().should.eventually.be.false; }); it('should return false if not created (Windows)', async () => { sandbox.stub(process, 'platform').value('win32'); sandbox.stub(environment, 'isCreated').resolves(false); await environment.isRunning().should.eventually.be.false; }); it('should execute the is_generated.sh script and return true if successful (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', ['is_running.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); await environment.isRunning().should.eventually.be.true; spawnStub.should.have.been.calledOnce; spawnStub.should.have.been.calledWith('/bin/sh', ['is_running.sh'], sinon.match.any); }); it('should execute the is_generated.sh script and return false if unsuccessful (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', ['is_running.sh'], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); await environment.isRunning().should.eventually.be.false; spawnStub.should.have.been.calledOnce; spawnStub.should.have.been.calledWith('/bin/sh', ['is_running.sh'], sinon.match.any); }); it('should execute the is_generated.sh script and return true if successful (Windows)', async () => { sandbox.stub(process, 'platform').value('win32'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', 'is_running.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); await environment.isRunning().should.eventually.be.true; spawnStub.should.have.been.calledOnce; spawnStub.should.have.been.calledWith('cmd', ['/c', 'is_running.cmd'], sinon.match.any); }); it('should execute the is_generated.sh script and return false if unsuccessful (Windows)', async () => { sandbox.stub(process, 'platform').value('win32'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', 'is_running.cmd'], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); await environment.isRunning().should.eventually.be.false; spawnStub.should.have.been.calledOnce; spawnStub.should.have.been.calledWith('cmd', ['/c', 'is_running.cmd'], sinon.match.any); }); it('should return the same promise if a request is already running (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', ['is_running.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); const promise1: any = environment.isRunning(); const promise2: any = environment.isRunning(); (promise1 === promise2).should.be.true; await promise1.should.eventually.be.true; spawnStub.should.have.been.calledOnce; spawnStub.should.have.been.calledWith('/bin/sh', ['is_running.sh'], sinon.match.any); }); it('should return the same promise if a request is already running (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('win32'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', 'is_running.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); const promise1: any = environment.isRunning(); const promise2: any = environment.isRunning(); (promise1 === promise2).should.be.true; await promise1.should.eventually.be.true; spawnStub.should.have.been.calledOnce; spawnStub.should.have.been.calledWith('cmd', ['/c', 'is_running.cmd'], sinon.match.any); }); }); describe('#startLogs', () => { it('should start the logs', async () => { const fakeStream: stream.Readable = new stream.Readable(); fakeStream._read = (_size: any): any => { // }; const logHoseStub: sinon.SinonStub = sandbox.stub(environment, 'getLoghose'); logHoseStub.returns(fakeStream); const adapter: VSCodeBlockchainDockerOutputAdapter = VSCodeBlockchainDockerOutputAdapter.instance(FabricRuntimeUtil.LOCAL_FABRIC); const outputAdapter: sinon.SinonSpy = sandbox.spy(adapter, 'log'); environment.startLogs(adapter); fakeStream.emit('data', { name: 'jake', line: 'simon dodges his unit tests' }); outputAdapter.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `jake|simon dodges his unit tests`); // let formattedName: string = environment.getName().replace(/\s+/g, ''); // formattedName += '_network'; // const opts: any = logHoseStub.args[0][0]; // const networkObject: any = {NetworkSettings: {Networks: {}}}; // networkObject.NetworkSettings.Networks[formattedName] = { // some: 'stuff' // }; // opts.attachFilter('someid', networkObject).should.be.true; }); }); describe('#stopLogs', () => { it('should stop the logs if loghose is active', () => { stopLogsStub.restore(); const fakeStream: stream.Readable = new stream.Readable(); fakeStream._read = (_size: any): any => { // }; environment['lh'] = fakeStream; const destroyStub: sinon.SinonStub = sandbox.stub(fakeStream, 'destroy').resolves(); environment.stopLogs(); destroyStub.should.have.been.calledOnce; }); it('should set loghose to null', () => { stopLogsStub.restore(); environment['lh'] = undefined; environment.stopLogs(); should.not.exist(environment['lh]']); }); }); describe('getLoghose', () => { it('should get loghose', async () => { const fakeStream: stream.Readable = new stream.Readable(); const result: any = environment.getLoghose({events: fakeStream}); should.exist(result); }); }); describe('#restart', () => { let isRunningStub: sinon.SinonStub; beforeEach(() => { isRunningStub = sandbox.stub(environment, 'isRunning').resolves(false); }); it('should execute the start.sh and stop.sh scripts and handle success (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', ['start.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); spawnStub.withArgs('/bin/sh', ['stop.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); await environment.restart(); spawnStub.should.have.been.calledTwice; spawnStub.should.have.been.calledWith('/bin/sh', ['start.sh'], sinon.match.any); spawnStub.should.have.been.calledWith('/bin/sh', ['stop.sh'], sinon.match.any); }); it('should execute the start.sh and stop.sh scripts using a custom output adapter (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', ['start.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); spawnStub.withArgs('/bin/sh', ['stop.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); const outputAdapter: sinon.SinonStubbedInstance<TestFabricOutputAdapter> = sandbox.createStubInstance(TestFabricOutputAdapter); await environment.restart(outputAdapter); outputAdapter.log.callCount.should.equal(4); outputAdapter.log.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'stdout'); outputAdapter.log.getCall(1).should.have.been.calledWith(LogType.INFO, undefined, 'stderr'); outputAdapter.log.getCall(2).should.have.been.calledWith(LogType.INFO, undefined, 'stdout'); outputAdapter.log.getCall(3).should.have.been.calledWith(LogType.INFO, undefined, 'stderr'); }); it('should publish busy events and set state before and after handling success (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', ['start.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); spawnStub.withArgs('/bin/sh', ['stop.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); environment.on('busy', eventStub); isRunningStub.resolves(true); const setStateSpy: sinon.SinonSpy = sandbox.spy(environment, 'setState'); await environment.restart(); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.RESTARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STARTED); environment.getState().should.equal(FabricRuntimeState.STARTED); }); it('should publish busy events and set state before and after handling an error, failure to stop (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', ['start.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); spawnStub.withArgs('/bin/sh', ['stop.sh'], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); environment.on('busy', eventStub); isRunningStub.resolves(true); const setStateSpy: sinon.SinonSpy = sandbox.spy(environment, 'setState'); await environment.restart().should.be.rejectedWith(`Failed to execute command "/bin/sh" with arguments "stop.sh" return code 1`); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.RESTARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STARTED); environment.getState().should.equal(FabricRuntimeState.STARTED); }); it('should publish busy events and set state before and after handling an error, failure to start (Linux/MacOS)', async () => { sandbox.stub(process, 'platform').value('linux'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('/bin/sh', ['start.sh'], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); spawnStub.withArgs('/bin/sh', ['stop.sh'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); environment.on('busy', eventStub); isRunningStub.resolves(false); const setStateSpy: sinon.SinonSpy = sandbox.spy(environment, 'setState'); await environment.restart().should.be.rejectedWith(`Failed to execute command "/bin/sh" with arguments "start.sh" return code 1`); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.RESTARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STOPPED); environment.getState().should.equal(FabricRuntimeState.STOPPED); }); it('should execute the start.cmd and stop.cmd scripts and handle success (Windows)', async () => { sandbox.stub(process, 'platform').value('win32'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', 'start.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); spawnStub.withArgs('cmd', ['/c', 'stop.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); await environment.restart(); spawnStub.should.have.been.calledTwice; spawnStub.should.have.been.calledWith('cmd', ['/c', 'start.cmd'], sinon.match.any); spawnStub.should.have.been.calledWith('cmd', ['/c', 'stop.cmd'], sinon.match.any); }); it('should execute the start.sh and stop.sh scripts using a custom output adapter (Windows)', async () => { sandbox.stub(process, 'platform').value('win32'); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', 'start.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); spawnStub.withArgs('cmd', ['/c', 'stop.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); const outputAdapter: sinon.SinonStubbedInstance<TestFabricOutputAdapter> = sandbox.createStubInstance(TestFabricOutputAdapter); await environment.restart(outputAdapter); outputAdapter.log.callCount.should.equal(4); outputAdapter.log.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'stdout'); outputAdapter.log.getCall(1).should.have.been.calledWith(LogType.INFO, undefined, 'stderr'); outputAdapter.log.getCall(2).should.have.been.calledWith(LogType.INFO, undefined, 'stdout'); outputAdapter.log.getCall(3).should.have.been.calledWith(LogType.INFO, undefined, 'stderr'); }); it('should publish busy events and set state before and after handling success (Windows)', async () => { sandbox.stub(process, 'platform').value('win32'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', 'start.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); spawnStub.withArgs('cmd', ['/c', 'stop.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); environment.on('busy', eventStub); isRunningStub.resolves(true); const setStateSpy: sinon.SinonSpy = sandbox.spy(environment, 'setState'); await environment.restart(); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.RESTARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STARTED); environment.getState().should.equal(FabricRuntimeState.STARTED); }); it('should publish busy events and set state before and after handling an error, on stopping (Windows)', async () => { sandbox.stub(process, 'platform').value('win32'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', 'start.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); spawnStub.withArgs('cmd', ['/c', 'stop.cmd'], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); environment.on('busy', eventStub); isRunningStub.resolves(true); const setStateSpy: sinon.SinonSpy = sandbox.spy(environment, 'setState'); await environment.restart().should.be.rejectedWith(`Failed to execute command "cmd" with arguments "/c, stop.cmd" return code 1`); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.RESTARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STARTED); environment.getState().should.equal(FabricRuntimeState.STARTED); }); it('should publish busy events and set state before and after handling an error, on starting (Windows)', async () => { sandbox.stub(process, 'platform').value('win32'); const eventStub: sinon.SinonStub = sandbox.stub(); const spawnStub: sinon.SinonStub = sandbox.stub(child_process, 'spawn'); spawnStub.withArgs('cmd', ['/c', 'start.cmd'], sinon.match.any).callsFake(() => { return mockFailureCommand(); }); spawnStub.withArgs('cmd', ['/c', 'stop.cmd'], sinon.match.any).callsFake(() => { return mockSuccessCommand(); }); environment.on('busy', eventStub); isRunningStub.resolves(false); const setStateSpy: sinon.SinonSpy = sandbox.spy(environment, 'setState'); await environment.restart().should.be.rejectedWith(`Failed to execute command "cmd" with arguments "/c, start.cmd" return code 1`); eventStub.should.have.been.calledTwice; eventStub.should.have.been.calledWithExactly(true); eventStub.should.have.been.calledWithExactly(false); setStateSpy.should.have.been.calledTwice; setStateSpy.firstCall.should.have.been.calledWith(FabricRuntimeState.RESTARTING); setStateSpy.secondCall.should.have.been.calledWith(FabricRuntimeState.STOPPED); environment.getState().should.equal(FabricRuntimeState.STOPPED); }); }); describe('#getState', () => { it('should return starting if the runtime is starting', () => { (environment as any).state = FabricRuntimeState.STARTING; environment.getState().should.equal(FabricRuntimeState.STARTING); }); it('should return stopping if the runtime is stopping', () => { (environment as any).state = FabricRuntimeState.STOPPING; environment.getState().should.equal(FabricRuntimeState.STOPPING); }); it('should return restarting if the runtime is restarting', () => { (environment as any).state = FabricRuntimeState.RESTARTING; environment.getState().should.equal(FabricRuntimeState.RESTARTING); }); it('should return stopped if the runtime is stopped', () => { (environment as any).state = FabricRuntimeState.STOPPED; environment.getState().should.equal(FabricRuntimeState.STOPPED); }); it('should return started if the runtime is started', () => { (environment as any).state = FabricRuntimeState.STARTED; environment.getState().should.equal(FabricRuntimeState.STARTED); }); }); describe('#getPeerChaincodeURL', () => { it('should get the peer chaincode URL', async () => { const url: string = await environment.getPeerChaincodeURL(); url.should.equal('grpc://org1peer-chaincode.127-0-0-1.nip.io:8080'); }); it('should be able to get peer chaincode url for an organisation', async () => { // No peers for Org2 await environment.getPeerChaincodeURL('Org2').should.be.rejectedWith(/There are no Fabric peer nodes/); // Should get the peer chaincode url const url: string = await environment.getPeerChaincodeURL('Org1'); url.should.equal('grpc://org1peer-chaincode.127-0-0-1.nip.io:8080'); }); it('should throw an error if there are no peer nodes', async () => { sandbox.stub(environment, 'getNodes').resolves([]); await environment.getPeerChaincodeURL().should.be.rejectedWith(/There are no Fabric peer nodes/); }); }); describe('#isBusy', () => { it('should return false if the runtime is not busy', () => { (environment as any).busy = false; environment.isBusy().should.be.false; }); it('should return true if the runtime is busy', () => { (environment as any).busy = true; environment.isBusy().should.be.true; }); }); describe('#waitFor', () => { it('should respond immediately if network is alive', async () => { const isAliveStub: sinon.SinonStub = sandbox.stub(environment, 'isAlive').resolves(true); const result: boolean = await environment.waitFor(); result.should.equal(true); isAliveStub.should.have.been.calledOnce; }); it('should return false if never alive', async () => { const numberOfAttempts: number = 10; const interval: number = 2; const isAliveStub: sinon.SinonStub = sandbox.stub(environment, 'isAlive').resolves(false); const sleepStub: sinon.SinonStub = sandbox.stub(TimerUtil, 'sleep').resolves(); const result: boolean = await environment.waitFor(numberOfAttempts, interval); result.should.equal(false); sleepStub.callCount.should.equal(numberOfAttempts); sleepStub.should.have.been.calledWith(interval * 1000); isAliveStub.callCount.should.equal(numberOfAttempts + 1); }); it('should return true if local microfab is eventually alive', async () => { const numberOfAttempts: number = 10; const interval: number = 2; const isAliveStub: sinon.SinonStub = sandbox.stub(environment, 'isAlive'); isAliveStub.onCall(0).resolves(false); // This is the immediate call to check whether to loop isAliveStub.onCall(1).resolves(false); isAliveStub.onCall(2).resolves(false); isAliveStub.onCall(3).resolves(true); const sleepStub: sinon.SinonStub = sandbox.stub(TimerUtil, 'sleep').resolves(); const result: boolean = await environment.waitFor(numberOfAttempts, interval); result.should.equal(true); sleepStub.callCount.should.equal(2); sleepStub.should.have.been.calledWith(interval * 1000); isAliveStub.callCount.should.equal(4); }); }); });
the_stack
import { LiteGraph } from "litegraph.js"; import { Number, String, Boolean } from "./basic/types"; import { Variable, GetVariable, UpdateVariable } from "./basic/variable"; import { Log } from "./basic/log"; import { Debugger } from "./basic/debugger"; import { Cast } from "./basic/cast"; import { KeyCode } from "./basic/key-code"; import { ObjectNode } from "./basic/object"; // Pointer import { RequestPointerLock, ExitPointerLock } from "./basic/pointer-lock"; // Math import { Add, Subtract, Multiply, Divide } from "./math/operation"; import { Random } from "./math/random"; import { Sinus, Cosinus, Tangent } from "./math/trigonometry"; import { Equals, And, Or, NotNull, NotUndefined, NotNullOrUndefined, Not } from "./math/logic"; import { ForLoop } from "./math/loop"; import { Vec2, Vec3, VectorLength } from "./math/vector"; import { AddVectors, MultiplyVectors } from "./math/vector-operation"; import { VectorSplitter } from "./math/vector-splitter"; import { Col3, Col4 } from "./math/color"; import { Sound } from "./sound/sound"; import { PlaySound } from "./sound/play"; import { StopSound } from "./sound/stop"; import { PointerEvent } from "./events/pointer-event"; import { KeyboardEvent } from "./events/keyboard-event"; import { TimeoutEvent } from "./events/set-timeout"; import { StartGameEvent } from "./events/start-game-event"; import { TickGameEvent } from "./events/tick-game-event"; import { CameraCollisionEvent } from "./events/collision-event"; import { WindowEvent } from "./events/window-event"; import { DispatchWindowEvent } from "./events/dispatch-window-event"; import { PickInfos } from "./data/pick-info"; import { GetProperty } from "./property/get-property"; import { SetProperty } from "./property/set-property"; import { CallNodeFunction } from "./node/call-function"; import { DisposeNode } from "./node/dispose"; import { SendNodeMessage } from "./node/send-message"; import { Camera } from "./camera/camera"; import { GetCamera } from "./camera/get-camera"; import { GetCameraDirection } from "./camera/get-direction"; import { TransformCamera } from "./camera/transform"; import { Light } from "./light/light"; import { GetLight } from "./light/get-light"; import { SetLightProperty } from "./light/set-property"; import { TransformLight } from "./light/transform"; import { AddMeshToShadowGenerator } from "./light/add-to-shadow-generator"; import { TransformNode } from "./transform-node/transform-node"; import { Mesh } from "./mesh/mesh"; import { RotateMesh } from "./mesh/rotate"; import { Translate } from "./mesh/translate"; import { PickMesh } from "./mesh/pick"; import { TransformMesh } from "./mesh/transform"; import { AbsoluteTransformMesh } from "./mesh/absolute-transform"; import { GetMesh } from "./mesh/get-mesh"; import { CreateMeshInstance } from "./mesh/create-instance"; import { GetMeshDirection } from "./mesh/get-direction"; import { SetMeshMaterial } from "./mesh/set-material"; import { ApplyImpulse } from "./physics/apply-impulse"; import { CreatePhysicsImpostor } from "./physics/create-physics-impostor"; // Animation import { AnimationGroup } from "./animation/animation-group"; import { PlayAnimationGroup } from "./animation/start-animation-group"; import { StopAnimationGroup } from "./animation/stop-animation-group"; import { PauseAnimationGroup } from "./animation/pause-animation-group"; import { AnimationRatio } from "./animation/ratio"; import { InterpolationAnimation } from "./animation/interpolate"; import { PlayAnimation } from "./animation/start-animations"; import { PlayWeightedAnimation } from "./animation/start-weighted-animation"; import { StopAnimation } from "./animation/stop-animations"; import { EasingFunction } from "./animation/easing"; import { GetAnimationRange } from "./animation/get-animation-range"; // Particle systems import { ParticleSystem } from "./particle-system/particle-system"; import { SetParticleSystemProperty } from "./particle-system/set-property"; // Textures import { Texture } from "./texture/texture"; // Materials import { Material } from "./material/material"; import { SetMaterialTextures } from "./material/set-textures"; export class GraphCode { private static _Initialized: boolean = false; /** * Initializes the graph system. */ public static Init(): void { if (this._Initialized) { return; } // Remove all existing nodes LiteGraph.registered_node_types = { }; // Create basic nodes LiteGraph.registerNodeType("basics/number", Number); LiteGraph.registerNodeType("basics/string", String); LiteGraph.registerNodeType("basics/boolean", Boolean); LiteGraph.registerNodeType("basics/debugger", Debugger); LiteGraph.registerNodeType("basics/log", Log); LiteGraph.registerNodeType("basics/cast", Cast); LiteGraph.registerNodeType("basics/variable", Variable); LiteGraph.registerNodeType("basics/get_variable", GetVariable); LiteGraph.registerNodeType("basics/update_variable", UpdateVariable); LiteGraph.registerNodeType("basics/key_code", KeyCode); LiteGraph.registerNodeType("basics/object", ObjectNode); // Pointer LiteGraph.registerNodeType("pointer/request_pointer_lock", RequestPointerLock); LiteGraph.registerNodeType("pointer/exit_pointer_lock", ExitPointerLock); // Create math nodes LiteGraph.registerNodeType("math/add", Add); LiteGraph.registerNodeType("math/subtract", Subtract); LiteGraph.registerNodeType("math/multiply", Multiply); LiteGraph.registerNodeType("math/divide", Divide); LiteGraph.registerNodeType("math/random", Random); LiteGraph.registerNodeType("logic/equals", Equals); LiteGraph.registerNodeType("logic/and", And); LiteGraph.registerNodeType("logic/or", Or); LiteGraph.registerNodeType("logic/not", Not); LiteGraph.registerNodeType("logic/not_null", NotNull); LiteGraph.registerNodeType("logic/not_undefined", NotUndefined); LiteGraph.registerNodeType("logic/not_null_or_undefined", NotNullOrUndefined); // Loops LiteGraph.registerNodeType("loops/for_loop", ForLoop); // Trigonometry LiteGraph.registerNodeType("trigonometry/sinus", Sinus); LiteGraph.registerNodeType("trigonometry/cosinus", Cosinus); LiteGraph.registerNodeType("trigonometry/tangent", Tangent); // Vectors LiteGraph.registerNodeType("vector/vector_2d", Vec2); LiteGraph.registerNodeType("vector/vector_3d", Vec3); LiteGraph.registerNodeType("vector/vector_length", VectorLength); LiteGraph.registerNodeType("math/add_vectors", AddVectors); LiteGraph.registerNodeType("math/multiply_vectors", MultiplyVectors); LiteGraph.registerNodeType("math/vector_splitter", VectorSplitter); // Colors LiteGraph.registerNodeType("math/color_3", Col3); LiteGraph.registerNodeType("math/color_4", Col4); // Sound LiteGraph.registerNodeType("sound/sound", Sound); LiteGraph.registerNodeType("sound/play_sound", PlaySound); LiteGraph.registerNodeType("sound/stop_sound", StopSound); // Events LiteGraph.registerNodeType("events/pointer_event", PointerEvent); LiteGraph.registerNodeType("events/keyboard_event", KeyboardEvent); LiteGraph.registerNodeType("events/timeout_event", TimeoutEvent); LiteGraph.registerNodeType("events/start_game_event", StartGameEvent); LiteGraph.registerNodeType("events/tick_game_event", TickGameEvent); LiteGraph.registerNodeType("events/collision_event", CameraCollisionEvent); LiteGraph.registerNodeType("events/window_event", WindowEvent); LiteGraph.registerNodeType("events/dispatch_window_event", DispatchWindowEvent); // Data LiteGraph.registerNodeType("data/pick_infos", PickInfos); // Utils LiteGraph.registerNodeType("utils/get_property", GetProperty); LiteGraph.registerNodeType("utils/set_property", SetProperty); // Node LiteGraph.registerNodeType("node/call_node_function", CallNodeFunction); LiteGraph.registerNodeType("node/dispose_node", DisposeNode); LiteGraph.registerNodeType("node/send_message_to_node", SendNodeMessage); // Camera LiteGraph.registerNodeType("camera/camera", Camera); LiteGraph.registerNodeType("camera/get_camera", GetCamera); LiteGraph.registerNodeType("camera/get_camera_direction", GetCameraDirection); LiteGraph.registerNodeType("camera/camera_transform", TransformCamera); // Light LiteGraph.registerNodeType("light/light", Light); LiteGraph.registerNodeType("light/get_light", GetLight); LiteGraph.registerNodeType("light/set_light_property", SetLightProperty); LiteGraph.registerNodeType("light/transform_light", TransformLight); LiteGraph.registerNodeType("light/add_mesh_to_shadow_generator", AddMeshToShadowGenerator); // Transfor Node LiteGraph.registerNodeType("transform/transform_node", TransformNode); // Mesh LiteGraph.registerNodeType("mesh/mesh", Mesh); LiteGraph.registerNodeType("mesh/rotate_mesh", RotateMesh); LiteGraph.registerNodeType("mesh/translate_mesh", Translate); LiteGraph.registerNodeType("mesh/pick_mesh", PickMesh); LiteGraph.registerNodeType("mesh/transform_mesh", TransformMesh); LiteGraph.registerNodeType("mesh/absolute_transform_mesh", AbsoluteTransformMesh); LiteGraph.registerNodeType("mesh/get_mesh", GetMesh); LiteGraph.registerNodeType("mesh/create_mesh_instance", CreateMeshInstance); LiteGraph.registerNodeType("mesh/get_mesh_direction", GetMeshDirection); LiteGraph.registerNodeType("mesh/set_mesh_material", SetMeshMaterial); // Physics LiteGraph.registerNodeType("physics/apply_impulse", ApplyImpulse); LiteGraph.registerNodeType("physics/create_physics_impostor", CreatePhysicsImpostor); // Animation LiteGraph.registerNodeType("animation/animation_group", AnimationGroup); LiteGraph.registerNodeType("animation/play_animation_group", PlayAnimationGroup); LiteGraph.registerNodeType("animation/stop_animation_group", StopAnimationGroup); LiteGraph.registerNodeType("animation/pause_animation_group", PauseAnimationGroup); LiteGraph.registerNodeType("animation/animation_ratio", AnimationRatio); LiteGraph.registerNodeType("animation/interpolation_animation", InterpolationAnimation); LiteGraph.registerNodeType("animation/play_animation", PlayAnimation); LiteGraph.registerNodeType("animation/play_weighted_animation", PlayWeightedAnimation); LiteGraph.registerNodeType("animation/stop_animation", StopAnimation); LiteGraph.registerNodeType("animation/easing_function", EasingFunction); LiteGraph.registerNodeType("animation/get_animation_range", GetAnimationRange); // Particle systems LiteGraph.registerNodeType("particles/particles_system", ParticleSystem); LiteGraph.registerNodeType("particles/set_particles_system_property", SetParticleSystemProperty); // Textures LiteGraph.registerNodeType("texture/texture", Texture); // Materials LiteGraph.registerNodeType("material/material", Material); LiteGraph.registerNodeType("material/set_material_textures", SetMaterialTextures); } }
the_stack
import * as React from 'react'; import assert from '../common/assert'; import { Types } from '../common/Interfaces'; import Timers from '../common/utils/Timers'; export enum GestureType { None, MultiTouch, Pan, PanVertical, PanHorizontal } // These threshold values were chosen empirically. const _pinchZoomPixelThreshold = 3; const _panPixelThreshold = 10; const _tapDurationThreshold = 500; const _longPressDurationThreshold = 750; const _tapPixelThreshold = 4; const _doubleTapDurationThreshold = 250; const _doubleTapPixelThreshold = 20; export interface GestureStatePoint { /** * accumulated distance of the gesture since the touch started */ dx: number; /** * accumulated distance of the gesture since the touch started */ dy: number; } export interface GestureStatePointVelocity extends GestureStatePoint { /** * current velocity of the gesture */ vx: number; /** * current velocity of the gesture */ vy: number; } // We need a method-less really-basic touch event basic type for allowing cross-platform adapting of // web(React)-based touch events into RX touch events, since they're based on the RN type to allow // for zero-work casting and manipulating. export interface TouchListBasic { [index: number]: Types.Touch; length: number; } export interface TouchEventBasic extends Types.SyntheticEvent { // We override this definition because the public // type excludes location and page fields. altKey: boolean; changedTouches: TouchListBasic; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; targetTouches: TouchListBasic; locationX?: number; locationY?: number; pageX?: number; pageY?: number; touches: TouchListBasic; } export abstract class GestureView extends React.Component<Types.GestureViewProps, Types.Stateless> { private _doubleTapTimer: number | undefined; private _pendingLongPressEvent: Types.TapGestureState | undefined; private _longPressTimer: number | undefined; // State for tracking move gestures (pinch/zoom or pan) private _pendingGestureType: GestureType = GestureType.None; private _pendingGestureState: Types.MultiTouchGestureState | Types.PanGestureState | Types.TapGestureState | undefined; // State for tracking double taps private _lastTapEvent: Types.TapGestureState | undefined; // Skip ability for next tap to work around some event issues private _shouldSkipNextTap = false; // State for tracking single taps private _lastGestureStartEvent: TouchEventBasic | undefined; componentWillUnmount() { // Dispose of timer before the component goes away. this._cancelDoubleTapTimer(); } // Returns true if we care about trapping/tracking the event protected _onTouchSeriesStart(event: TouchEventBasic): boolean { this._lastGestureStartEvent = event; // If we're trying to detect a tap, set this as the responder immediately. if (this.props.onTap || this.props.onDoubleTap || this.props.onLongPress || this.props.onContextMenu) { if (this.props.onLongPress) { const gsState = this._touchEventToTapGestureState(event); this._startLongPressTimer(gsState); } return true; } return false; } // Returns true if we care about trapping/tracking the event protected _onTouchChange(event: TouchEventBasic, gestureState: GestureStatePointVelocity): boolean { if (!this._lastGestureStartEvent) { this._lastGestureStartEvent = event; } // If this is the first movement we've seen, try to match it against // the various move gestures that we're looking for. let initializeFromEvent = false; if (this._pendingGestureType === GestureType.None) { this._pendingGestureType = this._detectMoveGesture(event, gestureState); initializeFromEvent = true; } if (this._pendingGestureType === GestureType.MultiTouch) { this._setPendingGestureState(this._sendMultiTouchEvents(event, gestureState, initializeFromEvent, false)); return true; } else if (this._pendingGestureType === GestureType.Pan || this._pendingGestureType === GestureType.PanVertical || this._pendingGestureType === GestureType.PanHorizontal) { const spEvent = this._touchEventToTapGestureState(event); this._setPendingGestureState(this._sendPanEvent(spEvent, gestureState, this._pendingGestureType, initializeFromEvent, false)); return true; } return false; } protected _onTouchSeriesFinished(touchEvent: TouchEventBasic, gestureState: GestureStatePointVelocity) { // Can't possibly be a long press if the touch ended. this._cancelLongPressTimer(); // Close out any of the pending move gestures. if (this._pendingGestureType === GestureType.MultiTouch) { this._sendMultiTouchEvents(touchEvent, gestureState, false, true); this._pendingGestureState = undefined; this._pendingGestureType = GestureType.None; } else if (this._pendingGestureType === GestureType.Pan || this._pendingGestureType === GestureType.PanVertical || this._pendingGestureType === GestureType.PanHorizontal) { const spEvent = this._touchEventToTapGestureState(touchEvent); this._sendPanEvent(spEvent, gestureState, this._pendingGestureType, false, true); this._pendingGestureState = undefined; this._pendingGestureType = GestureType.None; } else if (this._isTap(touchEvent)) { const tapGestureState = this._touchEventToTapGestureState(touchEvent); if (!this.props.onDoubleTap) { // If there is no double-tap handler, we can invoke the tap handler immediately. this._sendTapEvent(tapGestureState); } else if (this._isDoubleTap(tapGestureState)) { // This is a double-tap, so swallow the previous single tap. this._cancelDoubleTapTimer(); this._sendDoubleTapEvent(tapGestureState); } else { // This wasn't a double-tap. Report any previous single tap and start the double-tap // timer so we can determine whether the current tap is a single or double. this._reportDelayedTap(); this._startDoubleTapTimer(tapGestureState); } } else { this._reportDelayedTap(); this._cancelDoubleTapTimer(); } } // Get preferred pan ratio for platform. protected abstract _getPreferredPanRatio(): number; // Returns the timestamp for the touch event in milliseconds. protected abstract _getEventTimestamp(e: TouchEventBasic | Types.MouseEvent): number; protected _skipNextTap() { this._shouldSkipNextTap = true; } private _setPendingGestureState(gestureState: Types.MultiTouchGestureState | Types.PanGestureState | Types.TapGestureState) { this._reportDelayedTap(); this._cancelDoubleTapTimer(); this._cancelLongPressTimer(); this._pendingGestureState = gestureState; } private _detectMoveGesture(e: TouchEventBasic, gestureState: GestureStatePoint): GestureType { if (this._shouldRespondToPinchZoom(e) || this._shouldRespondToRotate(e)) { return GestureType.MultiTouch; } else if (this._shouldRespondToPan(gestureState)) { return GestureType.Pan; } else if (this._shouldRespondToPanVertical(gestureState)) { return GestureType.PanVertical; } else if (this._shouldRespondToPanHorizontal(gestureState)) { return GestureType.PanHorizontal; } return GestureType.None; } // Determines whether a touch event constitutes a tap. The "finger up" // event must be within a certain distance and within a certain time // from where the "finger down" event occurred. private _isTap(e: TouchEventBasic): boolean { if (!this._lastGestureStartEvent) { return false; } const initialTimeStamp = this._getEventTimestamp(this._lastGestureStartEvent); const initialPageX = this._lastGestureStartEvent.pageX!; const initialPageY = this._lastGestureStartEvent.pageY!; const timeStamp = this._getEventTimestamp(e); return (timeStamp - initialTimeStamp <= _tapDurationThreshold && this._calcDistance(initialPageX - e.pageX!, initialPageY - e.pageY!) <= _tapPixelThreshold); } // This method assumes that the caller has already determined that two // taps have been detected in a row with no intervening gestures. It // is responsible for determining if they occurred within close proximity // and within a certain threshold of time. protected _isDoubleTap(e: Types.TapGestureState) { if (!this._lastTapEvent) { return false; } return (e.timeStamp - this._lastTapEvent.timeStamp <= _doubleTapDurationThreshold && this._calcDistance(this._lastTapEvent.pageX - e.pageX, this._lastTapEvent.pageY - e.pageY) <= _doubleTapPixelThreshold); } // Starts a timer that reports a previous tap if it's not canceled by a subsequent gesture. protected _startDoubleTapTimer(e: Types.TapGestureState) { this._lastTapEvent = e; this._doubleTapTimer = Timers.setTimeout(() => { this._reportDelayedTap(); this._doubleTapTimer = undefined; }, _doubleTapDurationThreshold); } // Cancels any pending double-tap timer. protected _cancelDoubleTapTimer() { if (this._doubleTapTimer) { Timers.clearTimeout(this._doubleTapTimer); this._doubleTapTimer = undefined; } } protected _startLongPressTimer(gsState: Types.TapGestureState, isDefinitelyMouse = false) { if (this._pendingLongPressEvent) { return; } this._pendingLongPressEvent = gsState; this._longPressTimer = Timers.setTimeout(() => { this._reportLongPress(); this._longPressTimer = undefined; }, _longPressDurationThreshold); } private _reportLongPress() { if (!this._pendingLongPressEvent) { return; } if (this.props.onLongPress) { this.props.onLongPress(this._pendingLongPressEvent); } this._pendingLongPressEvent = undefined; } protected _cancelLongPressTimer() { if (this._longPressTimer) { Timers.clearTimeout(this._longPressTimer); this._longPressTimer = undefined; } this._pendingLongPressEvent = undefined; } // If there was a previous tap recorded but we haven't yet reported it because we were // waiting for a potential second tap, report it now. protected _reportDelayedTap() { if (this._lastTapEvent && this.props.onTap) { this._sendTapEvent(this._lastTapEvent); this._lastTapEvent = undefined; } } protected _clearLastTap() { this._lastTapEvent = undefined; } private static _isActuallyMouseEvent(e: TouchEventBasic | undefined): boolean { if (!e) { return false; } const nativeEvent = e as any; if (nativeEvent.button !== undefined) { return true; } else if (nativeEvent.isRightButton || nativeEvent.IsRightButton) { return true; } else if (nativeEvent.isMiddleButton || nativeEvent.IsMiddleButton) { return true; } return false; } private _shouldRespondToPinchZoom(e: TouchEventBasic) { if (!this.props.onPinchZoom) { return false; } // Do we see two touches? if (!e.touches || e.touches.length !== 2) { return false; } // Has the user started to pinch or zoom? const distance = this._calcDistance(e.touches[0].pageX - e.touches[1].pageX, e.touches[0].pageY - e.touches[1].pageY); if (distance >= _pinchZoomPixelThreshold) { return true; } return false; } private _shouldRespondToRotate(e: TouchEventBasic) { if (!this.props.onRotate) { return false; } // Do we see two touches? if (!e.touches || e.touches.length !== 2) { return false; } return true; } protected _shouldRespondToPan(gestureState: GestureStatePoint) { if (!this.props.onPan) { return false; } // Has the user started to pan? const panThreshold = (this.props.panPixelThreshold !== undefined && this.props.panPixelThreshold > 0) ? this.props.panPixelThreshold : _panPixelThreshold; return (this._calcDistance(gestureState.dx, gestureState.dy) >= panThreshold); } protected _shouldRespondToPanVertical(gestureState: GestureStatePoint) { if (!this.props.onPanVertical) { return false; } // Has the user started to pan? const panThreshold = (this.props.panPixelThreshold !== undefined && this.props.panPixelThreshold > 0) ? this.props.panPixelThreshold : _panPixelThreshold; const isPan = Math.abs(gestureState.dy) >= panThreshold; if (isPan && this.props.preferredPan === Types.PreferredPanGesture.Horizontal) { return Math.abs(gestureState.dy) > Math.abs(gestureState.dx * this._getPreferredPanRatio()); } return isPan; } protected _shouldRespondToPanHorizontal(gestureState: GestureStatePoint) { if (!this.props.onPanHorizontal) { return false; } // Has the user started to pan? const panThreshold = (this.props.panPixelThreshold !== undefined && this.props.panPixelThreshold > 0) ? this.props.panPixelThreshold : _panPixelThreshold; const isPan = Math.abs(gestureState.dx) >= panThreshold; if (isPan && this.props.preferredPan === Types.PreferredPanGesture.Vertical) { return Math.abs(gestureState.dx) > Math.abs(gestureState.dy * this._getPreferredPanRatio()); } return isPan; } private _calcDistance(dx: number, dy: number) { return Math.sqrt(dx * dx + dy * dy); } private _calcAngle(touches: TouchListBasic): number { const a = touches[0]; const b = touches[1]; let degrees = this._radiansToDegrees(Math.atan2(b.pageY - a.pageY, b.pageX - a.pageX)); if (degrees < 0) { degrees += 360; } return degrees; } private _radiansToDegrees(rad: number): number { return rad * 180 / Math.PI; } private _sendMultiTouchEvents(e: TouchEventBasic, gestureState: GestureStatePointVelocity, initializeFromEvent: boolean, isComplete: boolean) { const p = this._pendingGestureState as Types.MultiTouchGestureState; let multiTouchEvent: Types.MultiTouchGestureState; // If the user lifted up one or both fingers, the multitouch gesture // is halted. Just return the existing gesture state. if (!e.touches || e.touches.length !== 2) { multiTouchEvent = p; p.isComplete = isComplete; } else { const centerPageX = (e.touches[0].pageX + e.touches[1].pageX) / 2; const centerPageY = (e.touches[0].pageY + e.touches[1].pageY) / 2; const centerClientX = (e.touches[0].locationX + e.touches[1].locationX) / 2; const centerClientY = (e.touches[0].locationY + e.touches[1].locationY) / 2; const width = Math.abs(e.touches[0].pageX - e.touches[1].pageX); const height = Math.abs(e.touches[0].pageY - e.touches[1].pageY); const distance = this._calcDistance(width, height); const angle = this._calcAngle(e.touches); const initialCenterPageX = initializeFromEvent ? centerPageX : p.initialCenterPageX; const initialCenterPageY = initializeFromEvent ? centerPageY : p.initialCenterPageY; const initialCenterClientX = initializeFromEvent ? centerClientX : p.initialCenterClientX; const initialCenterClientY = initializeFromEvent ? centerClientY : p.initialCenterClientY; const initialWidth = initializeFromEvent ? width : p.initialWidth; const initialHeight = initializeFromEvent ? height : p.initialHeight; const initialDistance = initializeFromEvent ? distance : p.initialDistance; const initialAngle = initializeFromEvent ? angle : p.initialAngle; const velocityX = initializeFromEvent ? 0 : gestureState.vx; const velocityY = initializeFromEvent ? 0 : gestureState.vy; multiTouchEvent = { initialCenterPageX: initialCenterPageX, initialCenterPageY: initialCenterPageY, initialCenterClientX: initialCenterClientX, initialCenterClientY: initialCenterClientY, initialWidth: initialWidth, initialHeight: initialHeight, initialDistance: initialDistance, initialAngle: initialAngle, centerPageX: centerPageX, centerPageY: centerPageY, centerClientX: centerClientX, centerClientY: centerClientY, velocityX: velocityX, velocityY: velocityY, width: width, height: height, distance: distance, angle: angle, isComplete: isComplete, timeStamp: e.timeStamp, isTouch: !GestureView._isActuallyMouseEvent(e), }; } if (this.props.onPinchZoom) { this.props.onPinchZoom(multiTouchEvent); } if (this.props.onRotate) { this.props.onRotate(multiTouchEvent); } return multiTouchEvent; } protected _touchEventToTapGestureState(e: TouchEventBasic): Types.TapGestureState { let pageX = e.pageX!; let pageY = e.pageY!; let clientX = e.locationX!; let clientY = e.locationY!; // Grab the first touch. If the user adds additional touch events, // we will ignore them. If we use e.pageX/Y, we will be using the average // of the touches, so we'll see a discontinuity. if (e.touches && e.touches.length > 0) { pageX = e.touches[0].pageX; pageY = e.touches[0].pageY; clientX = e.touches[0].locationX; clientY = e.touches[0].locationY; } return { timeStamp: this._getEventTimestamp(e), clientX, clientY, pageX, pageY, isTouch: !GestureView._isActuallyMouseEvent(e), }; } protected _mouseEventToTapGestureState(e: Types.MouseEvent): Types.TapGestureState { const xyOffset = this._getClientXYOffset(); return { timeStamp: this._getEventTimestamp(e), clientX: e.clientX - xyOffset.x, clientY: e.clientY - xyOffset.y, pageX: e.pageX || 0, pageY: e.pageY || 0, isTouch: false, }; } protected _getClientXYOffset(): { x: number; y: number } { return { x: 0, y: 0 }; } private _sendPanEvent(e: Types.TapGestureState, gestureState: GestureStatePointVelocity, gestureType: GestureType, initializeFromEvent: boolean, isComplete: boolean) { const state = this._pendingGestureState as Types.PanGestureState; assert(this._lastGestureStartEvent, 'Gesture start event must not be null.'); const initialPageX = this._lastGestureStartEvent ? this._lastGestureStartEvent.pageX! : initializeFromEvent ? e.pageX : state.initialPageX; const initialPageY = this._lastGestureStartEvent ? this._lastGestureStartEvent.pageY! : initializeFromEvent ? e.pageY : state.initialPageY; const initialClientX = this._lastGestureStartEvent ? this._lastGestureStartEvent.locationX! : initializeFromEvent ? e.clientX : state.initialClientX; const initialClientY = this._lastGestureStartEvent ? this._lastGestureStartEvent.locationY! : initializeFromEvent ? e.clientY : state.initialClientY; const velocityX = initializeFromEvent ? 0 : gestureState.vx; const velocityY = initializeFromEvent ? 0 : gestureState.vy; const panEvent: Types.PanGestureState = { initialPageX: initialPageX, initialPageY: initialPageY, initialClientX: initialClientX, initialClientY: initialClientY, pageX: e.pageX, pageY: e.pageY, clientX: e.clientX, clientY: e.clientY, velocityX: velocityX, velocityY: velocityY, isComplete: isComplete, timeStamp: e.timeStamp, isTouch: !GestureView._isActuallyMouseEvent(this._lastGestureStartEvent), }; switch (gestureType) { case GestureType.Pan: if (this.props.onPan) { this.props.onPan(panEvent); } break; case GestureType.PanVertical: if (this.props.onPanVertical) { this.props.onPanVertical(panEvent); } break; case GestureType.PanHorizontal: if (this.props.onPanHorizontal) { this.props.onPanHorizontal(panEvent); } break; default: // do nothing; } return panEvent; } private static _toMouseButton(nativeEvent: any): number { if (nativeEvent.button !== undefined) { return nativeEvent.button; } else if (nativeEvent.isRightButton || nativeEvent.IsRightButton) { return 2; } else if (nativeEvent.isMiddleButton || nativeEvent.IsMiddleButton) { return 1; } return 0; } // Protected only as a hack for supporting keyboard nav clicking from native-common/GestureView protected _sendTapEvent = (tapEvent: Types.TapGestureState) => { // we need to skip tap after succesfull pan event // mouse up would otherwise trigger both pan & tap if (this._shouldSkipNextTap) { this._shouldSkipNextTap = false; return; } const button = GestureView._toMouseButton(tapEvent); if (button === 2) { // Always handle secondary button, even if context menu is not set - it shouldn't trigger onTap. if (this.props.onContextMenu) { this.props.onContextMenu(tapEvent); } } else if (this.props.onTap) { this.props.onTap(tapEvent); } }; protected _sendDoubleTapEvent(e: Types.TapGestureState) { // If user did a double click with different mouse buttons, eg. left (50ms) right // both clicks need to be registered as separate events. const lastButton = GestureView._toMouseButton(this._lastTapEvent!); const button = GestureView._toMouseButton(e); if (lastButton !== button || button === 2) { this._sendTapEvent(this._lastTapEvent!); return; } if (this.props.onDoubleTap) { this.props.onDoubleTap(e); } this._lastTapEvent = undefined; } } export default GestureView;
the_stack
import { GraphModel } from '@tensorflow/tfjs'; import { ConfigResult, DetectResult, Line, RecognizeOptions, RecognizeResult, Rectangle, Scheduler, } from 'tesseract.js'; import { useCallback, useEffect, useRef, useState, } from 'react'; import useGraphModel from './useGraphModel'; import useLogger from './useLogger'; import useTesseract from './useTesseract'; import { ZeroOneRange } from '../utils/types'; import { newProfiler, Profiler } from '../utils/profiler'; import { DetectionBox, graphModelExecute } from '../utils/graphModel'; import { brightnessFilter, contrastFilter, FilterFunc, greyscaleFilter, Pixels, preprocessPixels, relativeToAbsolute, } from '../utils/image'; import { JobTypes } from '../utils/tesseract'; import { toFloatFixed } from '../utils/numbers'; import { Loggers } from '../utils/logger'; export type DetectionPerformance = { processing: number, avgProcessing: number, inference: number, avgInference: number, ocr: number, avgOcr: number, total: number, avgFps: number, fps: number, }; export type DetectedLink = { url: string, x1: number, y1: number, x2: number, y2: number, }; export type UseLinkDetectorProps = { modelURL: string, maxBoxesNum: number, scoreThreshold: number, iouThreshold: number, workersNum: number, language: string, }; export type DetectProps = { video: HTMLVideoElement, videoBrightness: number, videoContrast: number, resizeToSize: number, applyFilters: boolean, regionProposalsPadding: ZeroOneRange, useRegionProposals: boolean, }; export type UseLinkDetectorOutput = { detectLinks: (props: DetectProps) => Promise<DetectionPerformance | null>, detectedLinks: DetectedLink[], error: string | null, loadingProgress: ZeroOneRange | null, loadingStage: string | null, httpsBoxes: DetectionBox[] | null, regionProposals: Rectangle[], pixels: Pixels | null, }; export type TesseractDetection = ConfigResult | RecognizeResult | DetectResult; // @see: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url const URL_REG_EXP = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)/gi; const extractLinkFromText = (text: string): string | null => { const urls: string[] | null = text.match(URL_REG_EXP); if (!urls || !urls.length) { return null; } return urls[0]; }; const extractLinkFromDetection = ( detection: TesseractDetection | null, logger: Loggers, ): DetectedLink | null => { if (!detection || !detection.data || !detection.data.lines || !detection.data.lines.length) { logger.logDebug('extractLinkFromDetection: empty'); return null; } for (let lineIndex = 0; lineIndex < detection.data.lines.length; lineIndex += 1) { const line: Line = detection.data.lines[lineIndex]; const url: string | null = extractLinkFromText(line.text); logger.logDebug('extractLinkFromDetection: line link', { url, text: line.text }); if (url) { const detectedLink: DetectedLink = { url, x1: line.bbox.x0, y1: line.bbox.y0, x2: line.bbox.x1, y2: line.bbox.y1, }; logger.logDebug('extractLinkFromDetection: detected', { detectedLink }); return detectedLink; } } return null; }; const useLinksDetector = (props: UseLinkDetectorProps): UseLinkDetectorOutput => { const { modelURL, iouThreshold, maxBoxesNum, scoreThreshold, workersNum, language, } = props; const preprocessingProfiler = useRef<Profiler>(newProfiler()); const inferenceProfiler = useRef<Profiler>(newProfiler()); const ocrProfiler = useRef<Profiler>(newProfiler()); const onFrameProfiler = useRef<Profiler>(newProfiler()); const modelRef = useRef<GraphModel | null>(null); const tesseractSchedulerRef = useRef<Scheduler | null>(null); const logger: Loggers = useLogger({ context: 'useLinksDetector' }); const [detectedLinks, setDetectedLinks] = useState<DetectedLink[]>([]); const [pixels, setPixels] = useState<Pixels | null>(null); const [detectionError, setDetectionError] = useState<string | null>(null); const [httpsBoxes, setHttpsBoxes] = useState<DetectionBox[] | null>(null); const [regionProposals, setRegionProposals] = useState<Rectangle[]>([]); const [loadingProgress, setLoadingProgress] = useState<ZeroOneRange | null>(null); const [loadingStage, setLoadingStage] = useState<string | null>(null); const { model, error: modelError, loadingProgress: modelLoadingProgress, } = useGraphModel({ modelURL, warmup: true, }); const { scheduler: tesseractScheduler, loaded: tesseractSchedulerLoaded, error: tesseractSchedulerError, loadingProgress: tesseractLoadingProgress, } = useTesseract({ workersNum, language, }); const detectLinks = async (detectProps: DetectProps): Promise<DetectionPerformance | null> => { const { video, videoBrightness, videoContrast, resizeToSize, applyFilters, regionProposalsPadding, useRegionProposals, } = detectProps; logger.logDebug('detectLinks', detectProps); if (!modelRef.current) { const errMsg = 'Model is not ready for detection yet'; logger.logError(errMsg); setDetectionError(errMsg); return null; } /* eslint-disable no-else-return */ if (!tesseractSchedulerRef.current) { const errMsg = 'Tesseract is not loaded yet'; logger.logError(errMsg); setDetectionError(errMsg); return null; } else if (tesseractSchedulerRef.current.getNumWorkers() !== workersNum) { const errMsg = 'Tesseract workers are not loaded yet'; logger.logError(errMsg); setDetectionError(errMsg); return null; } onFrameProfiler.current.start(); // Image preprocessing. const filters: FilterFunc[] = applyFilters ? [ brightnessFilter(videoBrightness), contrastFilter(videoContrast), greyscaleFilter(), ] : []; preprocessingProfiler.current.start(); let processedPixels: Pixels | null = null; try { processedPixels = preprocessPixels({ pixels: video, resizeToSize, filters, }); } catch (error) { const errMessage: string = (error && error.message) || 'Image preprocessing failed'; logger.logError(errMessage); setDetectionError(errMessage); } if (!processedPixels) { return null; } setPixels(processedPixels); const imageProcessingTime = preprocessingProfiler.current.stop(); // HTTPS prefixes detection model execution. inferenceProfiler.current.start(); const httpsPredictions: DetectionBox[] | null = await graphModelExecute({ model: modelRef.current, pixels: processedPixels, maxBoxesNum, scoreThreshold, iouThreshold, }); const modelExecutionTime = inferenceProfiler.current.stop(); setHttpsBoxes(httpsPredictions); // OCR execution. ocrProfiler.current.start(); const rectanglesImage: Rectangle[] = [ { left: 0, top: 0, width: processedPixels.width, height: processedPixels.height, }, ]; /* eslint-disable-next-line max-len */ const rectanglesRegions: Rectangle[] = !useRegionProposals || !httpsPredictions || !httpsPredictions.length ? [] : httpsPredictions.map((httpsPrediction: DetectionBox): Rectangle => { const { x1, y1, y2 } = httpsPrediction; const imageW: number = (processedPixels && processedPixels.width) || 0; const imageH: number = (processedPixels && processedPixels.height) || 0; const left: number = relativeToAbsolute(x1 - regionProposalsPadding, imageW); const top: number = relativeToAbsolute(y1 - regionProposalsPadding, imageH); const bottom: number = relativeToAbsolute(y2 + regionProposalsPadding, imageH); const width: number = imageW - left; const height: number = bottom - top; return { left, top, width, height, }; }); const rectangles: Rectangle[] = useRegionProposals ? rectanglesRegions : rectanglesImage; setRegionProposals(rectangles); logger.logDebug('detectLinks: tesseract is ready', { numWorkers: tesseractSchedulerRef.current.getNumWorkers(), rectangles: { ...rectangles }, }); if (rectangles.length) { const texts: Array<TesseractDetection | null> = await Promise.all( rectangles.map((rectangle: Rectangle): Promise<TesseractDetection | null> => { const recognizeOptions: Partial<RecognizeOptions> = { rectangle }; if (!tesseractSchedulerRef.current) { return Promise.resolve(null); } return tesseractSchedulerRef.current.addJob( JobTypes.Recognize, processedPixels, recognizeOptions, ); }), ); if (texts && texts.length) { const currentDetectedLinks: Array<DetectedLink | null> = texts .map((text: TesseractDetection | null): DetectedLink | null => { return extractLinkFromDetection(text, logger); }) .filter( (detection: DetectedLink | null): boolean => detection !== null, ); // @ts-ignore setDetectedLinks(currentDetectedLinks); } else { // If no links are recognized we should clear the previously recognized links. // However to give users more time to click on them even if the next recognition // round was not successful we may avoid clearing the array of links. // setDetectedLinks([]); } logger.logDebug('recognized texts', { texts }); } else { logger.logDebug('skipping the text recognition'); } const ocrExecutionTime = ocrProfiler.current.stop(); const onFrameTime = onFrameProfiler.current.stop(); // Performance summary. const detectionPerformance: DetectionPerformance = { processing: imageProcessingTime, avgProcessing: preprocessingProfiler.current.avg(), inference: modelExecutionTime, avgInference: inferenceProfiler.current.avg(), ocr: ocrExecutionTime, avgOcr: ocrProfiler.current.avg(), total: onFrameTime, avgFps: onFrameProfiler.current.avgFps(), fps: onFrameProfiler.current.fps(), }; logger.logDebugTable('onFrame', detectionPerformance); return detectionPerformance; }; const detectLinksCallback = useCallback(detectLinks, [ modelRef, iouThreshold, logger, maxBoxesNum, scoreThreshold, workersNum, tesseractSchedulerRef, ]); // Calculate the loading progress. useEffect(() => { const normalizedProgress: ZeroOneRange = toFloatFixed( (modelLoadingProgress + tesseractLoadingProgress) / 2, 2, ); logger.logDebug('useEffect: loading progress', { modelLoadingProgress, tesseractLoadingProgress, normalizedProgress, loadingProgress, }); setLoadingProgress(normalizedProgress); setLoadingStage('Loading links detector'); }, [loadingProgress, modelLoadingProgress, logger, tesseractLoadingProgress]); // Update model references. useEffect(() => { logger.logDebug('useEffect: Model'); modelRef.current = model; }, [model, logger]); // Update tesseract scheduler references. useEffect(() => { logger.logDebug('useEffect: Tesseract Scheduler'); if (!tesseractScheduler || !tesseractSchedulerLoaded) { return; } tesseractSchedulerRef.current = tesseractScheduler; }, [tesseractScheduler, logger, tesseractSchedulerLoaded]); return { detectedLinks, detectLinks: detectLinksCallback, loadingProgress, loadingStage, pixels, httpsBoxes, regionProposals, error: modelError || detectionError || tesseractSchedulerError, }; }; export default useLinksDetector;
the_stack
import { addEvent, bubble, callWithCurrentCtxWithEvents, deref, emitEvent, EventNames, IBobrilCacheNode, IBobrilComponent, IEventParam, ieVersion, now, preventDefault, CommonUseIsHook, buildUseIsHook, } from "./core"; import { isBoolean } from "./isFunc"; import { newHashObj } from "./localHelpers"; declare module "./core" { interface IBubblingAndBroadcastEvents { /// called after click or tap onClick?(event: IBobrilMouseEvent): GenericEventResult; onDoubleClick?(event: IBobrilMouseEvent): GenericEventResult; onContextMenu?(event: IBobrilMouseEvent): GenericEventResult; onMouseDown?(event: IBobrilMouseEvent): GenericEventResult; onMouseUp?(event: IBobrilMouseEvent): GenericEventResult; onMouseOver?(event: IBobrilMouseEvent): GenericEventResult; onMouseMove?(event: IBobrilMouseEvent): GenericEventResult; onMouseWheel?(event: IBobrilMouseWheelEvent): GenericEventResult; onPointerDown?(event: IBobrilPointerEvent): GenericEventResult; onPointerMove?(event: IBobrilPointerEvent): GenericEventResult; onPointerUp?(event: IBobrilPointerEvent): GenericEventResult; onPointerCancel?(event: IBobrilPointerEvent): GenericEventResult; } interface IBobrilEvents { /// does not bubble, called only when mouse comes into that node, onPointerMove could be used instead if need bubbling onMouseEnter?(event: IBobrilMouseEvent): void; /// does not bubble, called only when mouse leaves from that node, onPointerMove could be used instead if need bubbling onMouseLeave?(event: IBobrilMouseEvent): void; /// does not bubble, called when mouse comes to some child of that node, onPointerMove could be used instead if need bubbling onMouseIn?(event: IBobrilMouseEvent): void; /// does not bubble, called when mouse leaves from some child of that node, onPointerMove could be used instead if need bubbling onMouseOut?(event: IBobrilMouseEvent): void; } } export interface IBobrilMouseEvent extends IEventParam { x: number; y: number; /// 1 - left (or touch), 2 - middle, 3 - right <- it does not make sense but that's W3C button: number; /// 1 - single click, 2 - double click, 3+ - multi click count: number; shift: boolean; ctrl: boolean; alt: boolean; meta: boolean; cancelable: boolean; } export enum BobrilPointerType { Mouse = 0, Touch = 1, Pen = 2, } export interface IBobrilPointerEvent extends IBobrilMouseEvent { id: number; type: BobrilPointerType; } export interface IBobrilMouseWheelEvent extends IBobrilMouseEvent { dx: number; dy: number; } const MoveOverIsNotTap = 13; const TapShouldBeShorterThanMs = 750; const MaxBustDelay = 500; const MaxBustDelayForIE = 800; const BustDistance = 50; let ownerCtx: any = null; let invokingOwner: boolean; const onClickText = "onClick"; const onDoubleClickText = "onDoubleClick"; // PureFuncs: isMouseOwner, isMouseOwnerEvent export function isMouseOwner(ctx: any): boolean { return ownerCtx === ctx; } export function isMouseOwnerEvent(): boolean { return invokingOwner; } export function registerMouseOwner(ctx: any): void { ownerCtx = ctx; } export function releaseMouseOwner(): void { ownerCtx = null; } function invokeMouseOwner(handlerName: string, param: any): boolean { if (ownerCtx == undefined) { return false; } var c = ownerCtx.me.component; var handler = c[handlerName]; if (!handler) { // no handler available return false; } invokingOwner = true; var stop = callWithCurrentCtxWithEvents(() => handler.call(c, ownerCtx, param), ownerCtx); invokingOwner = false; return stop; } function addEvent5( name: string, callback: (ev: any, target: Node | undefined, node: IBobrilCacheNode | undefined) => boolean ) { addEvent(name, 5, callback); } var pointersEventNames = ["PointerDown", "PointerMove", "PointerUp", "PointerCancel"] as const; var i: number; function type2Bobril(t: any): BobrilPointerType { if (t === "mouse" || t === 4) return BobrilPointerType.Mouse; if (t === "pen" || t === 3) return BobrilPointerType.Pen; return BobrilPointerType.Touch; } function buildHandlerPointer(name: string) { return function handlePointerDown( ev: PointerEvent, target: Node | undefined, node: IBobrilCacheNode | undefined ): boolean { target = ev.target as Node; node = deref(target); let button = ev.button + 1; let type = type2Bobril(ev.pointerType); let buttons = ev.buttons; if (button === 0 && type === BobrilPointerType.Mouse && buttons) { button = 1; while (!(buttons & 1)) { buttons = buttons >> 1; button++; } } var param: IBobrilPointerEvent = { target: node!, id: ev.pointerId, cancelable: normalizeCancelable(ev), type: type, x: ev.clientX, y: ev.clientY, button: button, shift: ev.shiftKey, ctrl: ev.ctrlKey, alt: ev.altKey, meta: ev.metaKey || false, count: ev.detail, }; if (emitEvent("!" + name, param, target, node)) { preventDefault(ev); return true; } return false; }; } function buildHandlerTouch(name: string) { return function handlePointerDown( ev: TouchEvent, target: Node | undefined, node: IBobrilCacheNode | undefined ): boolean { var preventDef = false; for (var i = 0; i < ev.changedTouches.length; i++) { var t = ev.changedTouches[i]!; target = t.target as Node; node = deref(target); var param: IBobrilPointerEvent = { target: node!, id: t.identifier + 2, cancelable: normalizeCancelable(ev), type: BobrilPointerType.Touch, x: t.clientX, y: t.clientY, button: 1, shift: ev.shiftKey, ctrl: ev.ctrlKey, alt: ev.altKey, meta: ev.metaKey || false, count: ev.detail, }; if (emitEvent("!" + name, param, target, node)) preventDef = true; } if (preventDef) { preventDefault(ev); return true; } return false; }; } function buildHandlerMouse(name: string) { return function handlePointer( ev: MouseEvent, target: Node | undefined, node: IBobrilCacheNode | undefined ): boolean { target = ev.target as Node; node = deref(target); var param: IBobrilPointerEvent = { target: node!, id: 1, type: BobrilPointerType.Mouse, cancelable: normalizeCancelable(ev), x: ev.clientX, y: ev.clientY, button: decodeButton(ev), shift: ev.shiftKey, ctrl: ev.ctrlKey, alt: ev.altKey, meta: ev.metaKey || false, count: ev.detail, }; if (emitEvent("!" + name, param, target, node)) { preventDefault(ev); return true; } return false; }; } function listenMouse() { addEvent5("mousedown", buildHandlerMouse(pointersEventNames[0] /*"PointerDown"*/)); addEvent5("mousemove", buildHandlerMouse(pointersEventNames[1] /*"PointerMove"*/)); addEvent5("mouseup", buildHandlerMouse(pointersEventNames[2] /*"PointerUp"*/)); } if ((<any>window).ontouchstart !== undefined) { addEvent5("touchstart", buildHandlerTouch(pointersEventNames[0] /*"PointerDown"*/)); addEvent5("touchmove", buildHandlerTouch(pointersEventNames[1] /*"PointerMove"*/)); addEvent5("touchend", buildHandlerTouch(pointersEventNames[2] /*"PointerUp"*/)); addEvent5("touchcancel", buildHandlerTouch(pointersEventNames[3] /*"PointerCancel"*/)); listenMouse(); } else if (window.onpointerdown !== undefined) { for (i = 0; i < 4 /*pointersEventNames.length*/; i++) { var name = pointersEventNames[i]!; addEvent5(name.toLowerCase(), buildHandlerPointer(name)); } } else { listenMouse(); } for (var j = 0; j < 4 /*pointersEventNames.length*/; j++) { ((name: string) => { var onName = "on" + name; addEvent( "!" + name, 50, (ev: IBobrilPointerEvent, _target: Node | undefined, node: IBobrilCacheNode | undefined) => { return invokeMouseOwner(onName, ev) || bubble(node, onName as EventNames, ev) != undefined; } ); })(pointersEventNames[j]!); } var pointersDown: { [id: number]: BobrilPointerType } = newHashObj(); var toBust: Array<number>[] = []; var firstPointerDown = -1; var firstPointerDownTime = 0; var firstPointerDownX = 0; var firstPointerDownY = 0; var tapCanceled = false; var lastMouseEv: IBobrilPointerEvent | undefined; function diffLess(n1: number, n2: number, diff: number) { return Math.abs(n1 - n2) < diff; } var prevMousePath: (IBobrilCacheNode | null)[] = []; export const pointerRevalidateEventName = "!PointerRevalidate"; export function revalidateMouseIn() { if (lastMouseEv) { emitEvent(pointerRevalidateEventName, lastMouseEv, undefined, lastMouseEv.target); } } addEvent(pointerRevalidateEventName, 3, mouseEnterAndLeave); function vdomPathFromCacheNode(n: IBobrilCacheNode | undefined): IBobrilCacheNode[] { var res = []; while (n != undefined) { res.push(n); n = n.parent; } return res.reverse(); } const mouseOverHookSet = new Set<CommonUseIsHook>(); export let useIsMouseOver = buildUseIsHook(mouseOverHookSet); function mouseEnterAndLeave(ev: IBobrilPointerEvent) { lastMouseEv = ev; var node = ev.target; var toPath = vdomPathFromCacheNode(node); mouseOverHookSet.forEach((v) => v.update(toPath)); bubble(node, "onMouseOver", ev); var common = 0; while (common < prevMousePath.length && common < toPath.length && prevMousePath[common] === toPath[common]) common++; var n: IBobrilCacheNode | null; var c: IBobrilComponent; var i = prevMousePath.length; if (i > 0 && (i > common || i != toPath.length)) { n = prevMousePath[i - 1]!; if (n) { c = n.component; if (c && c.onMouseOut) c.onMouseOut(n.ctx!, ev); } } while (i > common) { i--; n = prevMousePath[i]!; if (n) { c = n.component; if (c && c.onMouseLeave) c.onMouseLeave(n.ctx!, ev); } } while (i < toPath.length) { n = toPath[i]!; if (n) { c = n.component; if (c && c.onMouseEnter) c.onMouseEnter(n.ctx!, ev); } i++; } prevMousePath = toPath; if (i > 0 && (i > common || i != prevMousePath.length)) { n = prevMousePath[i - 1]!; if (n) { c = n.component; if (c && c.onMouseIn) c.onMouseIn(n.ctx!, ev); } } return false; } function noPointersDown(): boolean { return Object.keys(pointersDown).length === 0; } function bustingPointerDown( ev: IBobrilPointerEvent, _target: Node | undefined, _node: IBobrilCacheNode | undefined ): boolean { if (firstPointerDown === -1 && noPointersDown()) { firstPointerDown = ev.id; firstPointerDownTime = now(); firstPointerDownX = ev.x; firstPointerDownY = ev.y; tapCanceled = false; mouseEnterAndLeave(ev); } pointersDown[ev.id] = ev.type; if (firstPointerDown !== ev.id) { tapCanceled = true; } return false; } function bustingPointerMove( ev: IBobrilPointerEvent, target: Node | undefined, node: IBobrilCacheNode | undefined ): boolean { // Browser forgot to send mouse up? Let's fix it if (ev.type === BobrilPointerType.Mouse && ev.button === 0 && pointersDown[ev.id] != null) { ev.button = 1; emitEvent("!PointerUp", ev, target, node); ev.button = 0; } if (firstPointerDown === ev.id) { mouseEnterAndLeave(ev); if ( !diffLess(firstPointerDownX, ev.x, MoveOverIsNotTap) || !diffLess(firstPointerDownY, ev.y, MoveOverIsNotTap) ) tapCanceled = true; } else if (noPointersDown()) { mouseEnterAndLeave(ev); } return false; } let clickingSpreeStart: number = 0; let clickingSpreeCount: number = 0; function shouldPreventClickingSpree(clickCount: number): boolean { if (clickingSpreeCount == 0) return false; let n = now(); if (n < clickingSpreeStart + 1000 && clickCount >= clickingSpreeCount) { clickingSpreeStart = n; clickingSpreeCount = clickCount; return true; } clickingSpreeCount = 0; return false; } export function preventClickingSpree() { clickingSpreeCount = 2; clickingSpreeStart = now(); } function bustingPointerUp( ev: IBobrilPointerEvent, target: Node | undefined, node: IBobrilCacheNode | undefined ): boolean { delete pointersDown[ev.id]; if (firstPointerDown == ev.id) { mouseEnterAndLeave(ev); firstPointerDown = -1; if (ev.type == BobrilPointerType.Touch && !tapCanceled) { if (now() - firstPointerDownTime < TapShouldBeShorterThanMs) { emitEvent("!PointerCancel", ev, target, node); shouldPreventClickingSpree(1); var handled = invokeMouseOwner(onClickText, ev) || bubble(node, onClickText, ev) != null; var delay = ieVersion() ? MaxBustDelayForIE : MaxBustDelay; toBust.push([ev.x, ev.y, now() + delay, handled ? 1 : 0]); return handled; } } else if (tapCanceled) { ignoreClick(ev.x, ev.y); } } return false; } function bustingPointerCancel( ev: IBobrilPointerEvent, _target: Node | undefined, _node: IBobrilCacheNode | undefined ): boolean { delete pointersDown[ev.id]; if (firstPointerDown == ev.id) { firstPointerDown = -1; } return false; } function bustingClick(ev: MouseEvent, _target: Node | undefined, _node: IBobrilCacheNode | undefined): boolean { var n = now(); for (var i = 0; i < toBust.length; i++) { var j = toBust[i]!; if (j[2]! < n) { toBust.splice(i, 1); i--; continue; } if (diffLess(j[0]!, ev.clientX, BustDistance) && diffLess(j[1]!, ev.clientY, BustDistance)) { toBust.splice(i, 1); if (j[3]) preventDefault(ev); return true; } } return false; } var bustingEventNames = ["!PointerDown", "!PointerMove", "!PointerUp", "!PointerCancel", "^click"] as const; var bustingEventHandlers = [ bustingPointerDown, bustingPointerMove, bustingPointerUp, bustingPointerCancel, bustingClick, ]; for (var i = 0; i < 5 /*bustingEventNames.length*/; i++) { addEvent(bustingEventNames[i]!, 3, bustingEventHandlers[i]!); } function createHandlerMouse(handlerName: string) { return (ev: IBobrilPointerEvent, _target: Node | undefined, node: IBobrilCacheNode | undefined) => { if (firstPointerDown != ev.id && !noPointersDown()) return false; if (invokeMouseOwner(handlerName, ev) || bubble(node, handlerName as EventNames, ev)) { return true; } return false; }; } var mouseHandlerNames = ["Down", "Move", "Up", "Up"]; for (var i = 0; i < 4; i++) { addEvent(bustingEventNames[i]!, 80, createHandlerMouse("onMouse" + mouseHandlerNames[i])); } function decodeButton(ev: MouseEvent): number { return ev.which || ev.button; } function normalizeCancelable(ev: Event): boolean { var c = ev.cancelable; return !isBoolean(c) || c; } function createHandler(handlerName: string, allButtons?: boolean) { return (ev: MouseEvent, _target: Node | undefined, node: IBobrilCacheNode | undefined) => { let button = decodeButton(ev) || 1; // Ignore non left mouse click/dblclick event, but not for contextmenu event if (!allButtons && button !== 1) return false; let param: IBobrilMouseEvent = { target: node!, x: ev.clientX, y: ev.clientY, button: button, cancelable: normalizeCancelable(ev), shift: ev.shiftKey, ctrl: ev.ctrlKey, alt: ev.altKey, meta: ev.metaKey || false, count: ev.detail || 1, }; if (handlerName == onDoubleClickText) param.count = 2; if ( shouldPreventClickingSpree(param.count) || invokeMouseOwner(handlerName, param) || bubble(node, handlerName as EventNames, param) ) { preventDefault(ev); return true; } return false; }; } export function nodeOnPoint(x: number, y: number): IBobrilCacheNode | undefined { return deref(document.elementFromPoint(x, y) as HTMLElement); } // click must have higher priority over onchange detection addEvent5("^click", createHandler(onClickText)); addEvent5("^dblclick", createHandler(onDoubleClickText)); addEvent5("contextmenu", createHandler("onContextMenu", true)); let wheelSupport = ("onwheel" in document.createElement("div") ? "" : "mouse") + "wheel"; function handleMouseWheel(ev: any, _target: Node | undefined, node: IBobrilCacheNode | undefined): boolean { let button = ev.button + 1; let buttons = ev.buttons; if (button === 0 && buttons) { button = 1; while (!(buttons & 1)) { buttons = buttons >> 1; button++; } } let dx = 0, dy: number; if (wheelSupport == "mousewheel") { dy = (-1 / 40) * ev.wheelDelta; ev.wheelDeltaX && (dx = (-1 / 40) * ev.wheelDeltaX); } else { dx = ev.deltaX; dy = ev.deltaY; } var param: IBobrilMouseWheelEvent = { target: node!, dx, dy, x: ev.clientX, y: ev.clientY, cancelable: normalizeCancelable(ev), button: button, shift: ev.shiftKey, ctrl: ev.ctrlKey, alt: ev.altKey, meta: ev.metaKey || false, count: ev.detail, }; if (invokeMouseOwner("onMouseWheel", param) || bubble(node, "onMouseWheel", param)) { preventDefault(ev); return true; } return false; } addEvent5(wheelSupport, handleMouseWheel); export const pointersDownCount = () => Object.keys(pointersDown).length; export const firstPointerDownId = () => firstPointerDown; export const ignoreClick = (x: number, y: number) => { var delay = ieVersion() ? MaxBustDelayForIE : MaxBustDelay; toBust.push([x, y, now() + delay, 1]); }; let lastInteractionWasKeyboard = false; const inputTypesWithPermanentFocusVisible = /te(l|xt)|search|url|email|password|number|month|week|(date)?(time)?(-local)?/i; function hasAlwaysFocusVisible(element: typeof document.activeElement): boolean { if (element == null) { return false; } if ( element.tagName == "INPUT" && inputTypesWithPermanentFocusVisible.test((element as HTMLInputElement).type) && !(element as HTMLInputElement).readOnly ) { return true; } if (element.tagName == "TEXTAREA" && !(element as HTMLTextAreaElement).readOnly) { return true; } return (element as HTMLElement).isContentEditable; } addEvent(bustingEventNames[0], 2, () => { lastInteractionWasKeyboard = false; return false; }); addEvent("keydown", 2, (ev) => { if (!ev.metaKey && !ev.altKey && !ev.ctrlKey) { lastInteractionWasKeyboard = true; } return false; }); export function shouldBeFocusVisible() { return lastInteractionWasKeyboard || hasAlwaysFocusVisible(document.activeElement); }
the_stack
import { cloneDeep, uniqueId } from 'lodash'; import { getLogger } from 'loglevel'; import * as Monaco from 'monaco-editor/esm/vs/editor/editor.api'; import { PmApiService } from '../../../common/services/pmapi/PmApiService'; import { Dict } from '../../../common/types/utils'; import { MonacoLanguageDefinition } from '../../../components/monaco/MonacoEditorWrapper'; import { getTokenValues, TokenValue } from '../../../datasources/lib/language'; import { PCPBPFtraceDataSource } from '../datasource'; import { BPFtraceQuery } from '../types'; import * as BPFtraceLanguage from './BPFtraceLanguage.json'; // this prevents monaco from being included in the redis datasource // (it it already in its own chunk in vendors~monaco-editor.js) declare const monaco: typeof Monaco; const log = getLogger('BPFtraceLanguageDefinition'); export class BPFtraceLanguageDefinition implements MonacoLanguageDefinition { languageId: string; private pmApiService: PmApiService; private dynamicProbeCompletions: Dict<string, Monaco.languages.CompletionItem[]> = {}; // kprobes based on current running kernel private staticProbeCompletions: Monaco.languages.CompletionItem[] = []; // probes which are not in `bpftrace -l` (BEGIN, END, interval, ...) private variableCompletions: Monaco.languages.CompletionItem[] = []; private functionCompletions: Monaco.languages.CompletionItem[] = []; private disposeCompletionProvider?: Monaco.IDisposable; constructor(private datasource: PCPBPFtraceDataSource, private getQuery: () => BPFtraceQuery) { this.languageId = uniqueId('bpftrace'); this.pmApiService = datasource.pmApiService; } register() { this.staticProbeCompletions = BPFtraceLanguage.probes.map(f => ({ kind: monaco.languages.CompletionItemKind.Event, label: f.name, insertText: f.name, range: undefined as any, })); this.variableCompletions = BPFtraceLanguage.variables.map(f => ({ kind: monaco.languages.CompletionItemKind.Variable, label: f.name, insertText: f.insertText ?? f.name, documentation: { value: `${f.name}\n\n${f.doc}`, isTrusted: true, }, range: undefined as any, })); this.functionCompletions = BPFtraceLanguage.functions.map(f => { const name = f.def.substring(0, f.def.indexOf('(')); return { kind: monaco.languages.CompletionItemKind.Function, label: name, insertText: name, documentation: { value: `${f.def}\n\n${f.doc}`, isTrusted: true, }, range: undefined as any, }; }); monaco.languages.register({ id: this.languageId }); monaco.languages.setLanguageConfiguration(this.languageId, { autoClosingPairs: [ { open: '(', close: ')' }, { open: '"', close: '"' }, ], // autocompletions replace the current "word" (without this setting, we get kprobe:kprobe:something) // the default separators except `@$:` wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\'\"\,\.\<\>\/\?\s]+)/g, }); monaco.languages.setMonarchTokensProvider(this.languageId, { tokenPostfix: '.bpftrace', // do not append languageId (which is random) probes: 'BEGIN|END|' + [ '(k|u)(ret)?probe', 'tracepoint', 'usdt', 'profile', 'interval', 'software', 'hardware', 'watchpoint', 'k(ret)?func', ] .map(p => `${p}:[a-zA-Z0-9_\\-:./]*`) .join('|'), keywords: ['if', 'else', 'unroll', 'return'], storageType: ['struct', 'union', 'enum'], builtinVariables: [ ...BPFtraceLanguage.variables.map(v => v.name), 'args', 'arg0', 'arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6', 'arg7', 'arg8', 'arg9', ], builtinConstants: ['true', 'false'], builtinFunctions: BPFtraceLanguage.functions.map(f => f.def.substring(0, f.def.indexOf('('))), operators: [ '=', '||', '&&', '|', '^', '&', '==', '!=', '<=', '>=', '<<', '+', '-', '*', '/', '%', '!', '~', '++', '--', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>=', '>>', '=>', ], symbols: /[=><!~?:&|+\-*\/\^%]+/, tokenizer: { root: [ [/#\s*(include|import|pragma|line|define|undef)/, 'keyword'], // compiler directives [/<.*>/, 'string'], // compiler directive value ['@probes', 'type.probe'], [ /[a-zA-Z_][a-zA-Z0-9_]*/, { cases: { '@keywords': 'keyword', '@storageType': 'keyword', '@builtinVariables': 'identifier', '@builtinConstants': 'identifier', '@builtinFunctions': 'keyword', }, }, ], [/(@|\$)[a-zA-Z_][a-zA-Z0-9_]*/, 'identifier'], [/[{}()\[\]]/, 'brackets'], [/[ \t\v\f\r\n]+/, ''], [/\/\*/, 'comment', '@comment'], [/\/\/.*$/, 'comment'], [ /@symbols/, { cases: { '@operators': 'delimiter', '@default': '', }, }, ], [/[0-9_]*\.[0-9_]+([eE][\-+]?\d+)?[fFdD]?/, 'number.float'], [/0[xX][0-9a-fA-F_]+/, 'number.hex'], [/0[bB][01_]+/, 'number.hex'], [/[0-9_]+/, 'number'], [/[;,.]/, 'delimiter'], [/".*?"/, 'string'], ], comment: [ [/[^\/*]+/, 'comment'], [/\*\//, 'comment', '@pop'], [/[\/*]/, 'comment'], ], }, } as Monaco.languages.IMonarchLanguage); this.disposeCompletionProvider = monaco.languages.registerCompletionItemProvider(this.languageId, { triggerCharacters: [':'], provideCompletionItems: async (model, position) => { try { // the 'range' property gets modified by monaco, therefore return a clone instead of the real object return cloneDeep(await this.findCompletions(getTokenValues(model, position))); } catch (error) { log.error('Error while auto-completing', error, error?.data); return; } }, }); } deregister() { this.disposeCompletionProvider?.dispose(); } async findProbeCompletions(token: TokenValue): Promise<Monaco.languages.CompletionList> { const { url, hostspec } = this.datasource.getUrlAndHostspec(this.getQuery()); const endpointId = `${url}::${hostspec}`; if (!(endpointId in this.dynamicProbeCompletions)) { const fetchResponse = await this.pmApiService.fetch(url, { hostspec, names: ['bpftrace.info.tracepoints'], }); const probes = (fetchResponse.values[0].instances[0].value as string) .split(',') .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); for (let i = 0, numProbes = probes.length; i < numProbes; i++) { if (probes[i].startsWith('kprobe:')) { probes.push('kretprobe:' + probes[i].substring(probes[i].indexOf(':') + 1)); } if (probes[i].startsWith('kfunc:')) { probes.push('kretfunc:' + probes[i].substring(probes[i].indexOf(':') + 1)); } } this.dynamicProbeCompletions[endpointId] = probes.map(probe => ({ kind: monaco.languages.CompletionItemKind.Event, label: probe, insertText: probe, range: undefined as any, })); } // Monaco performance degrades significantly with a big number of autocompletion items (~172343 probes) const completions = [...this.staticProbeCompletions, ...this.dynamicProbeCompletions[endpointId]!].filter( completion => (completion.label as string).includes(token.value) ); if (completions.length < 100) { return { suggestions: completions, incomplete: false }; } else { completions.splice(100); return { suggestions: completions, incomplete: true }; } } async findCompletions(tokens: TokenValue[]) { if (tokens.length === 0) { return; } const currentToken = tokens[tokens.length - 1]; let depth = 0; // depth of {} blocks, 0 = global scope let filter = 0; // check if inside filter (==1) or not (==0) for (let i = tokens.length - 1; i >= 0; i--) { const token = tokens[i]; if (token.type === 'brackets.bpftrace' && token.value === '{') { depth++; } else if (token.type === 'brackets.bpftrace' && token.value === '}') { depth--; } else if (depth === 0 && token.type === 'delimiter.bpftrace' && token.value === '/') { filter = (filter + 1) % 2; } } // TODO: completionProvider doesn't get triggered inside comments if (depth === 0 && filter === 0) { // global scope return await this.findProbeCompletions(currentToken); } else if (depth === 0 && filter === 1) { // global scope, inside filter return { suggestions: this.variableCompletions }; } else { // action block return { suggestions: this.variableCompletions.concat(this.functionCompletions) }; } } }
the_stack
import { assert } from "chai"; import * as P from "proptest"; import * as fc from "fast-check"; import * as Loriginal from "../src"; import { List, adjust, ap, concat, drop, dropLast, dropWhile, empty, equals, every, filter, find, findIndex, first, foldl, foldr, forEach, from, includes, insert, insertAll, join, last, length, list, map, none, nth, of, pair, partition, pluck, pop, prepend, range, reject, remove, repeat, reverse, some, splitAt, tail, take, takeLast, times, toArray, update } from "../src"; import { checkList, installCheck } from "./check"; import { nothing, just, Maybe, isJust } from "./utils"; import * as R from "ramda"; import { DropCommand, ConcatCommand, TakeCommand, MapCommand, ReverseCommand, ConcatPreCommand, FilterCommand } from "./commands"; const L: typeof Loriginal = installCheck(Loriginal); const check = P.createProperty(it); // Generates a list with length between 0 and size const genList = P.nat.map(n => range(0, n)); // Generates a list with length in the full 32 integer range const genBigList = P.between(0, 10000).map(n => range(0, n)); function numberArray(start: number, end: number): number[] { let array = []; for (let i = start; i < end; ++i) { array.push(i); } return array; } function appendList( start: number, end: number, l: List<number> = empty() ): List<number> { for (let i = start; i < end; ++i) { l = L.append(i, l); } return l; } function prependList( start: number, end: number, l: List<number> = empty() ): List<number> { for (let i = end - 1; i >= start; --i) { l = prepend(i, l); } return l; } function prependAll<A>(l1: List<A>, l2: List<A>): List<A> { return L.foldr((a, l) => L.prepend(a, l), l2, l1); } function assertIndicesFromTo( list: List<number>, from: number, to: number, offset: number = 0 ): void { for (let i = 0; i < to - from; ++i) { let elm: number; try { elm = nth(i + offset, list)!; } catch (err) { throw new Error(`Error while indexing ${i + offset}\n${err}`); } assert.strictEqual(elm, from + i); } } function cheapAssertIndicesFromTo( list: List<number>, from: number, to: number ): void { const length = to - from; if (length > 100) { assertIndicesFromTo(list, from, from + 50); assertIndicesFromTo(list, to - 50, to, length - 50); const middle = Math.floor(length / 2); assertIndicesFromTo(list, from + middle, from + middle + 1, middle); } else { assertIndicesFromTo(list, from, to); } } function assertIndexEqual<A>(i: number, l1: List<A>, l2: List<A>): void { const fst = nth(i, l1); if (L.isList(fst)) { assertListEqual(fst, nth(i, l2) as any); } else { assert.deepEqual(nth(i, l1), nth(i, l2), `expected equality at index ${i}`); } } export function assertListEqual<A>(l1: List<A>, l2: List<A>): void { assert.equal(l1.length, l2.length, "same length"); const length = l1.length; if (length > 500) { // If the list is long we cheap out for (let i = 0; i < 100; ++i) { assertIndexEqual(i, l1, l2); } const first = (length * 0.25) | 0; const middle = (length * 0.5) | 0; const third = (length * 0.75) | 0; assertIndexEqual(first, l1, l2); assertIndexEqual(middle, l1, l2); assertIndexEqual(third, l1, l2); for (let i = l1.length - 100; i < l1.length; ++i) { assertIndexEqual(i, l1, l2); } } else { for (let i = 0; i < l1.length; ++i) { assertIndexEqual(i, l1, l2); } } } const isEven = (n: number) => n % 2 === 0; const square = (n: number) => n * n; const sum = (a: number, b: number) => a + b; class Identity<A> { constructor(readonly value: A) {} "fantasy-land/equals"(b: any): boolean { return "value" in b ? this.value === b.value : false; } } describe("List", () => { it("against built-in array", () => { const integerArrayArb = fc.array(fc.integer(), 10000); fc.assert( fc.property( integerArrayArb, fc.commands( [ integerArrayArb.map(vs => new ConcatCommand(vs)), integerArrayArb.map(vs => new ConcatPreCommand(vs)), fc.nat().map(num => new DropCommand(num)), fc.nat().map(num => new TakeCommand(num)), fc.integer().map(val => new FilterCommand(val)), fc.integer().map(val => new MapCommand(val)), fc.constant(new ReverseCommand()) ], 25 ), (initialValues, cmds) => { const model = { data: Array.from(initialValues) }; const real = { data: L.from(initialValues) }; fc.modelRun(() => ({ model, real }), cmds); } ) ); }); describe("repeat", () => { it("creates list of n repeated elements", () => { [10, 100].forEach(n => { const l = repeat("foo", n); assert.strictEqual(length(l), n); for (const value of l) { assert.strictEqual(value, "foo"); } }); }); }); describe("times", () => { it("creates list of n elements repeating a fonction n times", () => { const l = times(n => n * n, 4); assert.isTrue(equals(l, list(0, 1, 4, 9))); }); }); describe("append", () => { it("can append 129 elements", () => { let l = appendList(0, 129); assertIndicesFromTo(l, 0, 129); }); it("can append elements", () => { fc.assert( fc.property(fc.nat(32 ** 3 + 32), n => { const l = appendList(0, n); assertIndicesFromTo(l, 0, n); }), { numRuns: 5 } ); }); it("can append tree of depth 2", () => { const size = 32 * 32 * 32 + 32; const list = range(0, size); assertIndicesFromTo(list, 0, size); }); it("copies suffix when it should", () => { const l1 = L.append(0, empty()); const l2 = L.append(1, l1); const l3 = L.append(2, l1); assert.strictEqual(last(l2), 1); assert.strictEqual(last(l3), 2); }); it("should work with size tables", () => { const size = 32 * 5 + 1; const list1 = concat(appendList(0, size), appendList(size, size * 2)); const list2 = appendList(size * 2, size * 3, list1); assertIndicesFromTo(list2, 0, size * 3); }); }); describe("prepend", () => { it("prepends items", () => { [ 32, // everything sits in prefix 32 + 32 + 1, // tail is pushed down 32 ** 2 + 32 + 1, // depth is 2 and tail is pushed down 32 ** 2 + 2 * 32 + 1, 2081, 32 ** 3 + 2 * 32 + 1 ].forEach(n => { let l = empty(); for (let i = n - 1; i >= 0; --i) { l = L.prepend(i, l); } assertIndicesFromTo(l, 0, n); }); }); it("prepends many items", () => { [ 32 // 1048641 // large ].forEach(n => { let l = empty(); for (let i = n - 1; i >= 0; --i) { l = L.prepend(i, l); } assertIndicesFromTo(l, 0, n); }); }); it("should work with size tables", () => { // Attempt prepending to a list that has size-tables from // concatenation const size = 32 * 5 + 1; const list1 = concat( appendList(size, size * 2), appendList(size * 2, size * 3) ); const list2 = prependList(0, size, list1); assertIndicesFromTo(list2, 0, size * 3); }); it("properly fills up a tree of depth one that has size tables", () => { const prependSize = 1000; const size = 65; const list = prependList(prependSize, prependSize + size); const list2 = prependList(prependSize + size, prependSize + size + size); const concatenated = concat(list, list2); const final = prependList(0, prependSize, concatenated); assertIndicesFromTo(final, 0, prependSize + size + size); }); it("should work with two levels of size tables", () => { const size = 32 * 10 + 1; const l1 = appendList(size * 1, size * 2); const l2 = appendList(size * 2, size * 3); const l3 = appendList(size * 3, size * 4); const l4 = appendList(size * 4, size * 5); const l5 = appendList(size * 5, size * 6); const catenated = concat(concat(concat(concat(l1, l2), l3), l4), l5); const final = prependList(0, size, catenated); assertIndicesFromTo(final, 0, size * 6); }); it("correctly uses offset when prepending in the presence of size tables", () => { // This test ensures that prepending to a list with size-tables // works correctly. In the test the height of the tree will be // increased when prepending. This introduces a non-zero offset. // The additional prepends fills up this offset. const prependSize = 1259; const size = 405; const list1 = prependList(prependSize, prependSize + size); const list2 = prependList(prependSize + size, prependSize + 2 * size); const concatenated = concat(list1, list2); const final = prependList(0, prependSize, concatenated); assertIndicesFromTo(final, 0, prependSize + 2 * size); }); it("prepend to concatenated list", () => { fc.assert( fc.property( fc.tuple(fc.nat(10000), fc.nat(100000), fc.nat(100000)), ([n, m, p]) => { const [a, b, c] = [ L.range(0, n), L.range(n, n + m), L.range(n + m, n + m + p) ]; const bc = L.concat(b, c); const abc = prependAll(a, bc); assertIndicesFromTo(abc, 0, n + m + p); } ), { numRuns: 5 } ); }); }); describe("append and prepend", () => { it("prepend to 32 size appended", () => { let l = empty(); const n = 32; for (let i = 1; i < n + 1; ++i) { l = L.append(i, l); } l = prepend(0, l); assertIndicesFromTo(l, 0, n + 1); }); it("can append and prepend", () => { let l = empty(); const n = 1000; for (let i = 0; i < n; ++i) { l = prepend(n - i - 1, l); l = L.append(n + i, l); } }); it("can append when there is offset", () => { let l = empty(); const n = 32 ** 2 + 32 * 2; const m = 32 ** 2; // * 31 - 32 * 3; const nm = 33; // first we prepend enough elements to grow the tree to height // 2, then we push additionally 64 elements to arrive at a list // with an offset for (let i = n - 1; i >= 0; --i) { l = prepend(i + nm, l); } // next we append elements to fill the right space up for (let i = 0; i < m; ++i) { l = L.append(n + nm + i, l); } // finally we push enough elements to trigger one more prefix to // be pushed down for (let i = nm - 1; 0 <= i; --i) { l = prepend(i, l); } assertIndicesFromTo(l, 0, n + m + nm); }); }); describe("nth", () => { it("returns undefined on -1 and empyt list", () => { assert.strictEqual(L.nth(-1, L.empty()), undefined); }); }); describe("list", () => { it("creates a list with the given elements", () => { const l = list(0, 1, 2, 3); assertIndicesFromTo(l, 0, 4); }); }); describe("of", () => { it("creates a singleton", () => { const l = of("foo"); assert.strictEqual(l.length, 1); assert.strictEqual(nth(0, l), "foo"); }); }); describe("pair", () => { it("creates a list of two elements", () => { const p = pair("foo", "bar"); assert.strictEqual(length(p), 2); assert.strictEqual(nth(0, p), "foo"); assert.strictEqual(nth(1, p), "bar"); }); }); describe("first and last", () => { it("gets the last element of a short list", () => { assert.strictEqual(last(list("a", "b", "c", "d")), "d"); }); it("gets the last element of a long list", () => { assert.strictEqual(last(appendList(0, 100)), 99); }); it("can get the last element when prefix overflows", () => { assert.strictEqual(last(prependList(0, 33)), 32); }); it("returns undefined on empty list", () => { assert.strictEqual(first(list()), undefined); assert.strictEqual(last(list()), undefined); }); it("returns the first element based on prefix size", () => { const l = L.prepend(0, L.empty()); L.prepend(1, l); assert.strictEqual(L.first(l), 0); }); it("gets the last element of prepended list", () => { const l = prepend(0, prepend(1, prepend(2, empty()))); assert.strictEqual(last(l), 2); }); it("gets first element of prepended list", () => { const l = prepend(0, prepend(1, prepend(2, empty()))); assert.strictEqual(first(l), 0); }); it("gets first element of appended list", () => { const l = L.append(3, L.append(2, L.append(1, L.append(0, empty())))); assert.strictEqual(first(l), 0); }); it("can get the first element when suffix overflows", () => { assert.strictEqual(first(appendList(0, 33)), 0); }); it("returns the last element based on suffix size", () => { const l = L.append(0, L.empty()); L.append(1, l); assert.strictEqual(L.last(l), 0); }); }); describe("concat", () => { check("has left identity", genList, l => { assertListEqual(concat(empty(), l), l); return true; }); check("has right identity", genList, l => { assertListEqual(concat(l, empty()), l); return true; }); check( "is associative", P.three(P.range(1_000_000).map(n => range(0, n / 3))), ([xs, ys, zs]) => { const lhs = concat(xs, concat(ys, zs)); const rhs = concat(concat(xs, ys), zs); assertListEqual(lhs, rhs); return true; }, { tests: 10 } ); it("is associative on concrete examples", () => { const xs = list(0); const ys = L.append(0, L.append(0, L.append(1, repeat(0, 30)))); const zs = repeat(0, 31); const lhs = concat(xs, concat(ys, zs)); const rhs = concat(concat(xs, ys), zs); assert.isTrue(equals(lhs, rhs)); }); it("concats empty sides", () => { const l = appendList(0, 4); assert.strictEqual(concat(l, empty()), l); assert.strictEqual(concat(empty(), l), l); }); describe("right is small", () => { it("combined suffix size is smaller than 32", () => { let l1 = appendList(0, 12); let l2 = appendList(12, 31); const catenated = concat(l1, l2); assert.strictEqual(length(catenated), 31); assertIndicesFromTo(catenated, 0, 31); }); it("right has prefix and suffix that can be combined", () => { let l1 = appendList(0, 12); let l2 = L.append( 16, L.append(15, prepend(12, prepend(13, prepend(14, empty())))) ); const concatenated = concat(l1, l2); assert.strictEqual(length(concatenated), 17); assertIndicesFromTo(concatenated, 0, 17); }); it("affixes takes up 3 affixes when combined", () => { let l1 = appendList(0, 30); let l2 = appendList(60, 90, prependList(30, 60)); const concatenated = concat(l1, l2); assert.strictEqual(length(concatenated), 90); assertIndicesFromTo(concatenated, 0, 90); }); it("left suffix is full", () => { [32, 32 * 4, 32 * 5, 32 * 12].forEach(leftSize => { const l1 = appendList(0, leftSize); const l2 = appendList(leftSize, leftSize + 30); const catenated = concat(l1, l2); assert.strictEqual(catenated.length, leftSize + 30); for (let i = 0; i < leftSize + 30; ++i) { assert.strictEqual(nth(i, catenated), i); } }); }); it("left is full tree", () => { const leftSize = 32 * 32 * 32 + 32; const l1 = appendList(0, leftSize); assertIndicesFromTo(l1, 0, leftSize); const l2 = appendList(leftSize, leftSize + 30); const catenated = concat(l1, l2); assert.strictEqual(catenated.length, leftSize + 30); assertIndicesFromTo(catenated, 0, leftSize + 30); }).timeout(5000); it("left suffix is arbitrary size", () => { [70, 183, 1092].forEach(leftSize => { const l1 = appendList(0, leftSize); const l2 = appendList(leftSize, leftSize + 30); const catenated = concat(l1, l2); assert.strictEqual(catenated.length, leftSize + 30); assertIndicesFromTo(catenated, 0, leftSize + 30); }); }); it("both left and right has prefix and suffix", () => { [[40, 33]].forEach(([leftSize, rightSize]) => { const l1 = appendList(0, leftSize); const l2 = appendList(leftSize, leftSize + rightSize); const catenated = concat(l1, l2); assertIndicesFromTo(catenated, 0, leftSize + rightSize); }); }); it("node has to be pushed down without room for it", () => { [[32 * 2 + 1, 32]].forEach(([leftSize, rightSize]) => { const l1 = appendList(0, leftSize); const l2 = appendList(leftSize, leftSize + rightSize); const catenated = concat(l1, l2); assertIndicesFromTo(catenated, 0, leftSize + rightSize); }); }); }); describe("satisfies invariant 1", () => { it("left nor right has root", () => { const left = appendList(0, 32); const right = appendList(32, 32 * 2); const catenated = concat(left, right); assertIndicesFromTo(catenated, 0, left.length + right.length); // first relies on the invariant assert.strictEqual(first(catenated), 0); }); it("left is only suffix and right has root", () => { const left = appendList(0, 32); const right = appendList(32, 32 + 32 * 3); const catenated = concat(left, right); assertIndicesFromTo(catenated, 0, left.length + right.length); // first relies on the invariant assert.strictEqual(first(catenated), 0); }); }); describe("both are large", () => { it("concats once properly", () => { [[83, 128], [2381, 3720]].forEach(([leftSize, rightSize]) => { const l1 = appendList(0, leftSize); const l2 = appendList(leftSize, leftSize + rightSize); const catenated = concat(l1, l2); assertIndicesFromTo(catenated, 0, leftSize + rightSize); }); }); it("does balancing", () => { const size = 4 * 32 + 1; const l1 = appendList(0, size * 1); const l2 = appendList(size * 1, size * 2); const l3 = appendList(size * 2, size * 3); const l4 = appendList(size * 3, size * 4); const l5 = appendList(size * 4, size * 5); const catenated = concat(concat(concat(concat(l1, l2), l3), l4), l5); assert.strictEqual(catenated.length, size * 5); assertIndicesFromTo(catenated, 0, size * 5); }); it("does balancing on trees that are three levels deep", () => { // this test hits the case where balancing takes place not at // the root and where the balanced nodes fits inside a single // parent node. I.e. after balancing there are <= 32 nodes. // // `l1` will be one level deeper than `l2`. And `l2` fits // inside the right most branch of the tree in `l1`, Thus when // rebalancing happens the balanced nodes fits in a single // leaf. const size1 = 32 ** 3 - 32 * 13; const size2 = 32 * 15; const l1 = appendList(0, size1); const l2 = appendList(size1, size1 + size2); const catenated = concat(l1, l2); assert.strictEqual(catenated.length, size1 + size2); assertIndicesFromTo(catenated, 0, size1 + size2); }); it("does balancing when right is largest", () => { const size1 = 32 * 15; const size2 = 32 ** 3 - 32 * 13; const l1 = appendList(0, size1); const l2 = appendList(size1, size1 + size2); const catenated = concat(l1, l2); assert.strictEqual(catenated.length, size1 + size2); assertIndicesFromTo(catenated, 0, size1 + size2); }); it("balances when concating 5 large lists", () => { const sizes = [17509, 19454, 13081, 16115, 21764]; let sum = 0; let l = empty(); for (const size of sizes) { const list2 = appendList(sum, sum + size); sum += size; l = concat(l, list2); } assertIndicesFromTo(l, 0, sum); }); it("inserts tail when path must be created", () => { // The right side will have to be inserted as a tail. Parts of // the path to the tail location does not exist so it must be // created. const sizes = [7202, 32]; let sum = 0; let l = empty(); for (const size of sizes) { const list2 = appendList(sum, sum + size); sum += size; l = concat(l, list2); } assertIndicesFromTo(l, 0, sum); }); it("updates size tables when pushing down tail", () => { // The right side will have to be inserted as a tail. Nodes // must be copied down to where the tail is inserted and the // nodes have size tables that must be updated accordingly. const sizes = [9972, 273, 12315]; let sum = 0; let l = empty(); for (const size of sizes) { const list2 = appendList(sum, sum + size); sum += size; l = concat(l, list2); } assertIndicesFromTo(l, 0, sum); }); }); check( "toArray distributes over concat", P.between(0, 1000000).replicate(2), ([n, m]) => { const left = L.range(0, n); const right = L.range(n, n + m); assert.deepEqual( L.toArray(left).concat(L.toArray(right)), L.toArray(L.concat(left, right)) ); return true; }, { tests: 10 } ); it("concatenates prepended list with appended list", () => { fc.assert( fc.property(fc.nat(32 ** 2), fc.nat(32 ** 2), (n, m) => { const l1 = prependList(0, n); const l2 = appendList(n, n + m); const l = L.concat(l1, l2); assertIndicesFromTo(l, 0, n + m); }), { numRuns: 25, examples: [[1089, 273], [1089, 1089]] } ); }); }); describe("map", () => { it("maps function over list", () => { [30, 100, 32 * 4 + 1].forEach(n => { const l = range(0, n); const mapped = map(square, l); for (let i = 0; i < n; ++i) { assert.strictEqual(nth(i, mapped), i * i); } }); }); it("maps over prepended list", () => { const l = prependList(0, 50); const mapped = map(square, l); for (let i = 0; i < 50; ++i) { assert.strictEqual(nth(i, mapped), i * i); } }); it("executes the mapping function from left to right", () => { // This matters if the mapping function isn't pure const l = appendList(32, 32 * 3, prependList(0, 32)); const arr: number[] = []; L.map(n => arr.push(n), l); assert.deepEqual(arr, L.toArray(l)); }); }); describe("pluck", () => { it("gets properties from objects", () => { const l = list( { foo: 0, bar: "a" }, { foo: 1, bar: "b" }, { foo: 2, bar: "c" }, { foo: 3, bar: "d" } ); const plucked = pluck("foo", l); assert.strictEqual(plucked.length, 4); assertIndicesFromTo(plucked, 0, 4); }); }); describe("applicative", () => { it("ap", () => { const l = ap( list((n: number) => n + 2, (n: number) => 2 * n, (n: number) => n * n), list(1, 2, 3) ); assert.isTrue(equals(l, list(3, 4, 5, 2, 4, 6, 1, 4, 9))); }); }); describe("monad", () => { it("flattens lists", () => { const nested = list( list(0, 1, 2, 3), list(4), empty(), list(5, 6, 7, 8, 9) ); const flattened = L.flatten(nested); assert.strictEqual(flattened.length, 10); assertIndicesFromTo(flattened, 0, 10); }); it("has flatMap", () => { const l = list(1, 2, 3); const l2 = L.flatMap(n => list(n, 2 * n, n * n), l); assert.isTrue(equals(l2, list(1, 2, 1, 2, 4, 4, 3, 6, 9))); }); }); describe("fold", () => { it("folds from the left appended", () => { [10, 32 * 4 + 5].forEach(n => { const result = foldl( (arr, i) => (arr.push(i), arr), <number[]>[], prependList(0, n) ); assert.deepEqual(result, numberArray(0, n)); }); }); it("folds from the left prepended", () => { [10, 32 * 4 + 5].forEach(n => { const result = foldl( (arr, i) => (arr.push(i), arr), <number[]>[], prependList(0, n) ); assert.deepEqual(result, numberArray(0, n)); }); }); it("folds from the right appended", () => { [10, 32 * 4 + 5].forEach(n => { const result = foldr( (i, arr) => (arr.push(i), arr), <number[]>[], appendList(0, n) ); assert.deepEqual(result, numberArray(0, n).reverse()); }); }); it("folds from the right prepended", () => { [10, 32 * 4 + 5].forEach(n => { const result = foldr( (i, arr) => (arr.push(i), arr), <number[]>[], prependList(0, n) ); assert.deepEqual(result, numberArray(0, n).reverse()); }); }); }); describe("traversable", () => { it("traverse works with maybe", () => { const safeDiv = (n: number) => (d: number) => d === 0 ? nothing : just(n / d); const r = L.traverse(Maybe, safeDiv(10), list(2, 4, 5)); assert.isTrue(isJust(r) && L.equals(r.val, list(5, 2.5, 2))); assert.strictEqual( L.traverse(Maybe, safeDiv(10), list(2, 0, 5)), nothing ); }); it("sequence works with maybe", () => { const l1 = list(just(0), just(1), just(2)); const r = L.sequence(Maybe, l1); assert.isTrue(isJust(r) && L.equals(r.val, list(0, 1, 2))); const l2 = list(nothing, just(1), just(2)); assert.strictEqual(L.sequence(Maybe, l2), nothing); const l3 = list(just(0), just(1), nothing); assert.strictEqual(L.sequence(Maybe, l3), nothing); }); }); describe("scan", () => { it("accumulates results", () => { const l = list(1, 3, 5, 4, 2); const l2 = L.scan((n, m) => n + m, 0, l); assertListEqual(l2, list(0, 1, 4, 9, 13, 15)); }); it("can change type", () => { const l = list(1, 3, 5, 4, 2); const l2 = L.scan((s, m) => s + m.toString(), "", l); assertListEqual(l2, list("", "1", "13", "135", "1354", "13542")); }); }); describe("forEach", () => { it("calls function for each element", () => { const arr: number[] = []; forEach(element => arr.push(element), list(0, 1, 2, 3, 4)); assert.deepEqual(arr, [0, 1, 2, 3, 4]); }); }); describe("filter and reject", () => { function isString(a: any): a is string { return typeof a === "string"; } it("filters element", () => { const l1 = list(0, 1, 2, 3, 4, 5, 6); const l2 = filter(isEven, l1); assert.strictEqual(length(l2), 4); for (let i = 0; i < length(l2); ++i) { assert.isTrue(isEven(nth(i, l2)!), `${i} is ${nth(i, l2)}`); } }); it("works with user-defined type guards", () => { const l = L.list<number | string>(0, "one", 2, "three", 4, "five"); const l2 = L.filter(isString, l); const l3 = L.map(s => s[0], l2); assertListEqual(l3, L.list("o", "t", "f")); }); it("rejects element", () => { const l1 = list(0, 1, 2, 3, 4, 5, 6); const l2 = reject(isEven, l1); assert.strictEqual(length(l2), 3); for (let i = 0; i < length(l2); ++i) { assert.isFalse(isEven(nth(i, l2)!), `${i} is ${nth(i, l2)}`); } }); it("partitions elements in two arrays", () => { const [fst, snd] = partition(isEven, list(0, 1, 2, 3, 4, 5)); assert.isTrue(equals(fst, list(0, 2, 4))); assert.isTrue(equals(snd, list(1, 3, 5))); }); it("partition works with type predicate", () => { const l = L.list<number | string>(0, "one", 2, "three", 4, "five"); const [strings, numbers] = L.partition(isString, l); assertListEqual(strings, L.list("one", "three", "five")); assertListEqual(numbers, L.list(0, 2, 4)); }); }); describe("foldl based functions", () => { it("join", () => { const s = join(", ", list("one", "two", "three")); assert.equal(s, "one, two, three"); }); }); describe("every, some, and none", () => { const l1 = list(2, 4, 6, 8); const l2 = list(2, 3, 4, 6, 7, 8); const l3 = list(1, 3, 5, 7); it("returns true from every when all elements satisfy predicate", () => { assert.strictEqual(every(isEven, empty()), true); assert.strictEqual(every(isEven, l1), true); assert.strictEqual(every(isEven, l2), false); assert.strictEqual(every(isEven, l3), false); }); it("returns true from every when all elements satisfy predicate", () => { assert.strictEqual(some(isEven, empty()), false); assert.strictEqual(some(isEven, l1), true); assert.strictEqual(some(isEven, l2), true); assert.strictEqual(some(isEven, l3), false); }); it("returns true from every when all elements satisfy predicate", () => { assert.strictEqual(none(isEven, empty()), true); assert.strictEqual(none(isEven, l1), false); assert.strictEqual(none(isEven, l2), false); assert.strictEqual(none(isEven, l3), true); }); }); describe("find", () => { it("finds the first element satisfying predicate", () => { assert.strictEqual(find(isEven, list(1, 3, 4, 5, 6)), 4); }); it("returns undefined if no element is found", () => { assert.strictEqual(find(isEven, list(1, 3, 5, 7)), undefined); }); it("finds the index of the first element satisfying predicate", () => { assert.strictEqual(findIndex(isEven, list(1, 3, 4, 5, 6)), 2); }); it("returns undefined if no element is found", () => { assert.strictEqual(findIndex(isEven, list(1, 3, 5, 7)), -1); }); // The tests below ensures that all cases in the internal `foldlCb` // are being tested const l = appendList(0, 32 * 3); it("finds in prefix", () => { const result = find(n => n === 20, l); assert.strictEqual(result, 20); }); it("finds in tree", () => { const result = find(n => n === 32 + 4, l); assert.strictEqual(result, 32 + 4); }); it("finds in suffix", () => { const result = find(n => n === 32 * 2 + 4, l); assert.strictEqual(result, 32 * 2 + 4); }); it("finds in deep tree", () => { const l2 = appendList(0, 1500 * 6); const result = find(n => n % 1500 === 0 && n !== 0 && n !== 1500, l2); assert.strictEqual(result, 1500 * 2); }); }); describe("findLast", () => { it("finds the last element satisfying predicate", () => { assert.strictEqual(L.findLast(isEven, list(1, 3, 4, 5, 6, 7)), 6); }); it("finds the last element in prefix", () => { const result = L.findLast(n => n <= 4, L.range(0, 60)); assert.strictEqual(result, 4); }); it("finds the last element in prefix when there is tree", () => { const result = L.findLast(n => n <= 4, L.range(0, 90)); assert.strictEqual(result, 4); }); check( "findLast is equivalent to reverse and find", P.range(32 ** 3 + 32).chain(n => P.between(0, n + 1).map(m => [n, m])), ([n, m]) => { const l = L.range(0, n); assert.equal( L.findLast(x => x <= m, l), L.find(x => x <= m, L.reverse(l)) ); return true; } ); }); describe("foldlWhile", () => { it("stops folding when false", () => { const isOdd = (_acc: any, x: number) => x % 2 === 1; const xs = L.list(1, 3, 5, 60, 777, 800); assert.strictEqual(L.foldlWhile(isOdd, sum, 0, xs), 9); const ys = L.list(2, 4, 6); assert.strictEqual(L.foldlWhile(isOdd, sum, 111, ys), 111); }); }); describe("indexOf", () => { const l = L.list(12, 4, 2, 89, 6, 18, 7); it("finds first element by strict equality", () => { assert.strictEqual(L.indexOf(89, l), 3); assert.strictEqual(L.indexOf(7, l), 6); assert.strictEqual(L.indexOf(12, l), 0); }); it("return -1 if no element is found", () => { assert.strictEqual(L.indexOf(10, l), -1); }); }); describe("lastIndexOf", () => { const l = L.list(12, 4, 2, 18, 89, 2, 18, 7); it("finds last element by strict equality", () => { assert.strictEqual(L.lastIndexOf(18, l), 6); assert.strictEqual(L.lastIndexOf(2, l), 5); assert.strictEqual(L.lastIndexOf(12, l), 0); }); it("return -1 if no element is found", () => { assert.strictEqual(L.lastIndexOf(10, l), -1); }); }); describe("contains", () => { it("returns true if element is present", () => { assert.strictEqual(includes(3, list(0, 1, 2, 3, 4, 5)), true); }); it("returns false if element is not present", () => { assert.strictEqual(includes(3, list(0, 1, 2, 4, 5)), false); }); }); describe("equals", () => { it("returns false if lists are not of the same length", () => { assert.isFalse(L.equals(list(0, 1, 2, 3), list(0, 1, 2, 3, 4))); }); it("returns false if elements differ in content", () => { assert.isFalse(L.equals(list(0, 1, 9, 3, 4), list(0, 1, 2, 3, 4))); }); it("returns true if lists are identical", () => { const l = list(0, 1, 2, 3, 4); assert.isTrue(L.equals(l, l)); }); it("returns true if lists are equivalent", () => { assert.isTrue(L.equals(list(0, 1, 2, 3, 4), list(0, 1, 2, 3, 4))); }); it("handles setoids", () => { const l1 = L.list(new Identity(1), new Identity(2)); const l2 = L.list(new Identity(1), new Identity(2)); assert.isTrue(L.equals(l1, l2)); }); it("compares elements with function", () => { assert.isTrue( L.equalsWith( (n, m) => Math.floor(n) === Math.floor(m), L.list(2.1, 2.4, 3.8, 1.3), L.list(2.7, 2.4, 3.2, 1.9) ) ); }); }); describe("iteration", () => { it("iterates over leftwise dense list", () => { [ 20, // a list where there is no elements in tree 50, // both suffix and prefix 1000, // a tree with larger depth, 32 ** 2 + 3 // an even larger tree ].forEach(n => { const l = range(0, n); let last = -1; for (const element of l) { assert.strictEqual(element, last + 1); last = element; } assert.strictEqual(last, n - 1); }); }); it("iterates backwards over a list", () => { [ 20, // a list where there is no elements in tree 50, // both suffix and prefix 3 * 32, // both suffix and prefix 1000, // a tree with larger depth, 32 ** 2 + 3 // an even larger tree ].forEach(n => { const l = L.range(0, n); let l2 = L.empty(); for (const n of L.backwards(l)) { l2 = L.prepend(n, l2); } // console.log(L.toArray(l2)); assertListEqual(l, l2); }); }); }); describe("update", () => { it("changes element in prefix", () => { const l = prependList(0, 32 * 4); const l2 = update(14, -1, l); assert.strictEqual(nth(14, l2), -1); }); it("changes element in suffix", () => { const l = appendList(0, 32 * 4); const l2 = update(14, -1, l); assert.strictEqual(nth(14, l2), -1); }); it("changes element in the middle of appended tree", () => { const l = appendList(0, 32 ** 3); const index = Math.floor(32 ** 3 / 2); const l2 = update(index, -1, l); assert.strictEqual(nth(index, l2), -1); }); it("changes element in the middle of prepended tree", () => { const l = prependList(0, 32 ** 3); const index = Math.floor(32 ** 3 / 2); const l2 = update(index, -1, l); assert.strictEqual(nth(index, l2), -1); }); it("changes first element in tree", () => { const l = prependList(0, 32 * 3); const l2 = update(32, -1, l); assert.strictEqual(nth(32, l2), -1); }); it("changes last element in tree", () => { const l = prependList(0, 32 ** 3); const l2 = update(32 ** 3 - 32, -1, l); assert.strictEqual(nth(32 ** 3 - 32, l2), -1); }); it("sets entire list", () => { const length = 32 ** 3; let l = empty(); for (let i = 0; i < length; ++i) { l = prepend(-1, l); } for (let i = 0; i < length; ++i) { l = update(i, i, l); } assertIndicesFromTo(l, 0, length); }); it("works with size tables", () => { const size = 32 * 5 + 1; const catenated = concat(appendList(0, size), appendList(size, size * 2)); const list1 = update(32 * 7, 0, catenated); assert.strictEqual(nth(32 * 7, list1), 0); const list2 = update(32 + 162, 0, catenated); assert.strictEqual(nth(32 + 162, list2), 0); const list3 = update(40, 0, catenated); assert.strictEqual(nth(40, list3), 0); }); it("returns list unchanged if out of bounds", () => { const l = list(0, 1, 2, 3, 4); assert.strictEqual(update(-1, 3, l), l); assert.strictEqual(update(5, 3, l), l); }); }); describe("adjust", () => { it("it applies function to index", () => { const l = list(0, 1, 2, 3, 4, 5); const l2 = adjust(2, square, l); assert.strictEqual(nth(2, l2), 4); }); it("returns list unchanged if out of bounds", () => { const l = list(0, 1, 2, 3, 4); assert.strictEqual(adjust(-1, square, l), l); assert.strictEqual(adjust(5, square, l), l); }); }); describe("slice", () => { it("returns same list when nothing is sliced off", () => { [[100, 0, 100], [100, -120, 120]].forEach(([n, from, to]) => { const l = appendList(0, n); const sliced = L.slice(from, to, l); assert.strictEqual(l, sliced); }); }); it("returns empty list when end is before start", () => { const l = appendList(0, 100); assert.strictEqual(length(L.slice(50, 50, l)), 0); assert.strictEqual(length(L.slice(55, 34, l)), 0); }); it("can slice to infinity", () => { const sliced = L.slice(2, Infinity, list(0, 1, 2, 3, 4, 5)); assert.equal(sliced.length, 4); assertIndicesFromTo(sliced, 2, 5); }); [ { n: 32 * 3 + 10, from: 4, to: Infinity, prepend: true, msg: "slices off of prefix" }, { n: 10000, from: 2, to: 6, prepend: false, msg: "slices part prefix" }, { n: 32 * 3 + 10, from: 0, to: -3, prepend: false, msg: "slices off of suffix" }, { n: 32 * 3, from: 32 * 3 - 10, to: 32 * 3 - 2, prepend: false, msg: "slices part of suffix" }, { n: 32 * 3, from: 34, to: Infinity, prepend: false, msg: "slices tree from left" }, { n: 32 ** 3 + 38, from: 1000, to: Infinity, prepend: false, msg: "slices large tree from left" }, { // will go down 0 -> 31 -> 31 -> 27 the 27 will be moved to // the prefix and will have an empty path that should be // pruned n: 32 ** 4 + 38, from: 32 ** 3 - 5 + 32, to: Infinity, prepend: false, msg: "slices from left when a paths single leaf is moved to prefix" }, { n: 32 * 3 + 5, from: 0, to: 32 * 3, prepend: false, msg: "slices from right a number of elements equal to suffix length" }, { // will go down 31 -> 0 -> 0 -> 27 the 27 will be moved to // the prefix and will have an empty path that should be // pruned n: 32 ** 4 + 38, from: 0, to: 32 ** 4 + 32, prepend: false, msg: "slices from right when a paths single leaf is moved to prefix" }, { // will go down into two neighbor leaf nodes and move them to affixes n: 32 ** 2 + 38, from: 32 * 4 + 12, to: 32 * 4 + 12 + 36, prepend: false, msg: "sets root to undefined when sliced fits into affixes" }, { n: 65, from: 38, to: 49, prepend: false, msg: "slices down into tree leaf node" }, { n: 97, from: 34, to: 48, prepend: false, msg: "tree is reduced to single affix" }, { n: 32 ** 3 + 19, from: 312, to: 518, prepend: false, msg: "slices when both indices lie in the tree and the height must be reduced" }, { n: 32 ** 3, from: 500, to: 32 ** 3 - 500, prepend: false, msg: "slices a some elements of both ends of a deep tree" } ].forEach(({ n, from, to, prepend, msg }) => { it(msg, () => { const l = prepend ? prependList(0, n) : appendList(0, n); const sliced = L.slice(from, to, l); const end = to < 0 ? n + to : Math.min(to, n); assert.strictEqual(sliced.length, end - from); if (sliced.length <= 64) { // if the sliced list can fit into affixes the root should // be undefined assert.isUndefined(sliced.root); } cheapAssertIndicesFromTo(sliced, from, end); }).timeout(50000); }); it("sliced list can be concated", () => { // This test catches a bug where the list `left` below would not // get the correct height from `slice`. This incorrect height // makes the following concat fail. const l = range(0, 128); const left = L.slice(0, 50, l); const l2 = concat(left, range(50, 100)); assert.strictEqual(l2.length, 100); assertIndicesFromTo(l2, 0, 100); }); it("reduces height", () => { const size = 32 ** 3 + 33; // This test case tests that the height of the tree is reduced // when a deep tree is sliced into a very small tree. const l = range(0, size); const left = 15809; const right = left + 2 * 32 + 16; const l2 = L.slice(left, right, l); // Tree should have one layer so we should find number in array assert.isNumber(l2.root!.array[0]); assert.strictEqual(nth(40, l2), left + 40); assertIndicesFromTo(l2, left, right); }); it("reduces height when joining slices", () => { // This test creates a tree with three layers and slices down // left 0 -> 31 -> 3 and right 1 -> 1 -> 2. This means that // since 0 != 1 we invoke sliceLeft and sliceRight with nothing // in the middle. The left slice becomes undefined so the single // right slice becomes the top of the tree and the height can // then be reduced. const size = 32 ** 3 + 1; const l = range(0, size); const l2 = L.slice(1028, 1090, l); // Tree should have one layer so we should find number in array assert.isNumber(l2.root!.array[0]); assertIndicesFromTo(l2, 1028, 1090); }); it("slice handles size tables from concat when slicing from left", () => { const size = 32 ** 2; const l = concat(appendList(0, size), appendList(size, 2 * size)); cheapAssertIndicesFromTo(l, 0, 2 * size); const left = 100; const right = 2 * size; const sliced = L.slice(left, right, l); cheapAssertIndicesFromTo(sliced, left, right); }); it("slice handles size tables from concat both ends", () => { const size = 32 ** 2; const l = concat(appendList(0, size), appendList(size, 2 * size)); const left = 100; const right = 2 * size - 100; const sliced = L.slice(left, right, l); cheapAssertIndicesFromTo(sliced, left, right); }); it("handles size tables when indexing", () => { // In this test `slice` must select the right path based on the // size tables that results from the concatenation. const sum = 52 + 65; const l = concat(appendList(0, 52), appendList(52, sum)); const left = 62; const right = 106; const sliced = L.slice(left, right, l); cheapAssertIndicesFromTo(sliced, left, right); }); it("can slice off front and back in short list with elements in both affixes", () => { const l = L.append(3, prependList(0, 3)); const a = L.dropLast(1, L.drop(1, l)); const b = L.slice(1, 3, l); assertListEqual(a, b); }); it("can slice several times off of a last list", () => { const a = appendList(0, 1329); const b = L.drop(L.length(L.takeWhile(l => l <= 200, a)), a); const c = L.takeWhile(l => l <= 203, b); const d = L.drop(L.length(c), b); const c1 = L.append(L.nth(0, d), c); const c2 = L.dropLast(1, L.drop(1, c1)); assertListEqual(c2, list(202, 203)); }); it("handles size tables and offset at the same time", () => { let f: List<number> = L.list(); let g: number[] = []; f = L.concat(f, L.from(numberArray(0, 5440))); g = [...g, ...numberArray(0, 5440)]; f = L.concat(f, L.from(numberArray(0, 6338))); g = [...g, ...numberArray(0, 6338)]; f = L.drop(4194, f); g = g.slice(4194); f = L.drop(6229, f); g = g.slice(6229); assert.deepEqual(L.toArray(f), g); }); }); describe("drop", () => { it("drops element from the left", () => { ([ [10, 20, true], // we only take from suffix [10, 32 * 3, false], // we should only take from prefix [100, 1000, true], // stop in tree [999, 1000, true], [64, 32 ** 3 + 32 * 3, true] // height should be reduced ] as [number, number, boolean][]).forEach(([amount, n, shouldAppend]) => { const l = shouldAppend ? appendList(0, n) : prependList(0, n); const dropped = drop(amount, l); assert.strictEqual(dropped.length, n - amount); assertIndicesFromTo(dropped, amount, n); }); }); it("returns same list when dropping zero elements", () => { [[0, 10], [0, 120]].forEach(([amount, n]) => { const l = appendList(0, n); const taken = drop(amount, l); assert.strictEqual(l, taken); }); }); it("drops element from the right", () => { ([ [10, 20, true], // we only take from suffix [10, 32 * 3, false], // we should only take from prefix [100, 1000, true], // stop in tree [999, 1000, true], [64, 32 ** 3 + 32 * 3, true] // height should be reduced ] as [number, number, boolean][]).forEach(([amount, n, shouldAppend]) => { const l = shouldAppend ? appendList(0, n) : prependList(0, n); const dropped = dropLast(amount, l); assert.strictEqual(dropped.length, n - amount); assertIndicesFromTo(dropped, 0, n - amount); }); }); }); describe("take", () => { it("takes element from the left", () => { ([ [10, 20, true], // we only take from suffix [10, 32 * 3, false], // we should only take from prefix [100, 1000, true], // stop in tree [999, 1000, true], [64, 32 ** 3 + 32 * 3, true] // height should be reduced ] as [number, number, boolean][]).forEach(([amount, n, shouldAppend]) => { const l = shouldAppend ? appendList(0, n) : prependList(0, n); const taken = take(amount, l); assert.strictEqual(taken.length, amount); assertIndicesFromTo(l, 0, amount); }); }); it("returns same list when taking more than length", () => { [[10, 10], [12, 9]].forEach(([amount, n]) => { const l = appendList(0, n); const taken = take(amount, l); assert.strictEqual(l, taken); }); }); it("takes element from the right", () => { ([ [10, 20, true], // we only take from suffix [10, 32 * 3, false], // we should only take from prefix [100, 1000, true], // stop in tree [999, 1000, true], [64, 32 ** 3 + 32 * 3, true] // height should be reduced ] as [number, number, boolean][]).forEach(([amount, n, shouldAppend]) => { const l = shouldAppend ? appendList(0, n) : prependList(0, n); const taken = takeLast(amount, l); assert.strictEqual(taken.length, amount); assertIndicesFromTo(taken, n - amount, n); }); }); }); describe("take and drop", () => { const l = list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); it("takes elements as long as predicate is true", () => { const l2 = L.takeWhile(n => n < 6, l); assert.strictEqual(l2.length, 6); assertIndicesFromTo(l2, 0, 6); }); it("takes last elements as long as predicate is true", () => { const l2 = L.takeLastWhile(n => n >= 5, l); assert.strictEqual(l2.length, 5); assertIndicesFromTo(l2, 5, 10); }); it("returns empty list when predicate is always false", () => { assertListEqual(L.takeLastWhile(_ => false, l), L.empty()); assertListEqual(L.takeWhile(_ => false, l), L.empty()); }); it("returns same list when predicate is always true", () => { assert.strictEqual(L.takeLastWhile(_ => true, l), l); assert.strictEqual(L.takeWhile(_ => true, l), l); }); describe("dropWhile", () => { it("drops elements that satisfies the predicate", () => { const l2 = dropWhile(n => n < 6, l); assert.strictEqual(l2.length, 4); assertIndicesFromTo(l2, 6, 10); }); it("returns empty list when predicate is always true", () => { assertListEqual(L.dropWhile(_ => true, l), L.empty()); }); it("returns the same list when predicate is always false", () => { assert.strictEqual(L.dropWhile(_ => false, l), l); }); }); }); describe("dropRepeats", () => { it("dropRepeats", () => { assertListEqual( L.dropRepeats(L.list(0, 0, 1, 1, 1, 2, 3, 3, 4, 4)), L.list(0, 1, 2, 3, 4) ); }); it("dropRepeatsWith", () => { assertListEqual( L.dropRepeatsWith( (n, m) => Math.floor(n) === Math.floor(m), L.list(0, 0.4, 1.2, 1.1, 1.8, 2.2, 3.8, 3.4, 4.7, 4.2) ), L.list(0, 1.2, 2.2, 3.8, 4.7) ); }); }); describe("concat and slice", () => { check("concat then splitAt is no-op", genBigList.replicate(2), ([l, m]) => { const [l2, m2] = L.splitAt(l.length, L.concat(l, m)); checkList(l2); checkList(m2); assert.isTrue(L.equals(l, l2)); assert.isTrue(L.equals(m, m2)); return true; }); check( "splitAt then concat is no-op", P.range(2) .big() .array() .chain(xs => P.record({ xs: P.Gen.of(xs), i: P.range(xs.length + 1) })), ({ xs, i }) => { const li = list(...xs); const [left, right] = splitAt(i, li); assertListEqual(concat(left, right), li); return true; } ); check( "concat then slice", P.between(0, 40000) .replicate(2) .chain(([n, m]) => P.range(n + m + 1).chain(to => P.record({ n: P.Gen.of(n), m: P.Gen.of(m), from: P.range(to + 1), to: P.Gen.of(to) }) ) ), ({ n, m, from, to }) => { const left = L.range(0, n); const right = L.range(n, n + m); const cat = L.concat(left, right); const sliced = L.slice(from, to, cat); assertListEqual( sliced, L.from( numberArray(0, n) .concat(numberArray(n, n + m)) .slice(from, to) ) ); assert.deepEqual( L.toArray(sliced), numberArray(0, n) .concat(numberArray(n, n + m)) .slice(from, to) ); return true; } ); check( "slices elements off concatenated list", P.between(0, 10000).chain(n => P.between(0, n) .three() .map(ns => [n, ...ns]) ), ([n, a, b, c]) => { // console.log(n, a, b, c); const fst = L.range(0, a); const snd = L.range(a, n); const catenated = L.concat(fst, snd); const from = Math.min(b, c); const to = Math.max(b, c); const sliced = L.slice(from, to, catenated); cheapAssertIndicesFromTo(sliced, from, to); return true; } ); it("slices after concat", () => { let l1 = prependList(0, 1089); const l2 = L.from(R.repeat(0, 34)); const cat = L.concat(l1, l2); const sliced = L.slice(0, 2, cat); assertListEqual(sliced, L.list(0, 1)); }); }); describe("splitAt", () => { it("splits at index", () => { const l = list(0, 1, 2, 3, 4, 5, 6, 7, 8); const [left, right] = splitAt(4, l); assertIndicesFromTo(left, 0, 3); assertIndicesFromTo(right, 4, 8); }); it("splits at negative index", () => { const l = list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0); const [left, right] = splitAt(-4, l); assertIndicesFromTo(left, 0, 6); assertIndicesFromTo(right, 7, 0); }); }); describe("splitWhen", () => { const l = list(0, 1, 2, 3, 4, 5, 6); it("splits when predicate is true", () => { const [left, right] = L.splitWhen(n => n > 3, l); assertListEqual(left, L.list(0, 1, 2, 3)); assertListEqual(right, L.list(4, 5, 6)); }); it("gives empty second list if predicate is never true", () => { const [left, right] = L.splitWhen(_ => false, l); assertListEqual(left, l); assertListEqual(right, empty()); }); }); describe("splitEvery", () => { it("splits into lists of the given size", () => { const l = list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); assertListEqual( L.splitEvery(3, l), L.list(L.list(0, 1, 2), L.list(3, 4, 5), L.list(6, 7, 8), L.list(9)) ); const l2 = list(0, 1, 2, 3, 4, 5, 6, 7, 8); assertListEqual( L.splitEvery(3, l2), L.list(L.list(0, 1, 2), L.list(3, 4, 5), L.list(6, 7, 8)) ); }); }); describe("remove", () => { const l = range(0, 100); it("removes element from the start", () => { const lr = remove(0, 23, l); assert.strictEqual(lr.length, 100 - 23); assertIndicesFromTo(lr, 23, 100); }); it("removes element from the end", () => { const lr = remove(60, 40, l); assert.strictEqual(lr.length, 100 - 40); assertIndicesFromTo(lr, 0, 60); }); it("removes single element at index", () => { const l2 = remove(50, 1, l); assert.strictEqual(l2.length, 99); assertIndicesFromTo(l2, 0, 49); }); it("removes several element at index", () => { const l2 = remove(45, 7, l); assert.strictEqual(l2.length, 100 - 7); assertIndicesFromTo(l2, 0, 45); assertIndicesFromTo(l2, 45 + 7, 100, 45); }); }); describe("tail", () => { it("removes the first element", () => { const l = prependList(0, 20); const tailed = tail(l); assert.strictEqual(tailed.length, 19); assertIndicesFromTo(tailed, 1, 20); }); it("returns the empty list when given the empty list", () => { assertListEqual(L.tail(L.empty()), L.empty()); }); }); describe("pop", () => { it("removes the last element", () => { const l = prependList(0, 20); const tailed = pop(l); assert.strictEqual(tailed.length, 19); assertIndicesFromTo(tailed, 0, 19); }); }); describe("toArray", () => { it("converts list to array", () => { const l = list(0, 1, 2, 3, 4, 5, 6, 7); const array = toArray(l); assert.deepEqual(array, [0, 1, 2, 3, 4, 5, 6, 7]); }); }); describe("from", () => { it("converts an array into a list", () => { const array = [0, 1, 2, 3, 4, 5, 6, 7, 8]; const l = from(array); assert.strictEqual(l.length, array.length); assertIndicesFromTo(l, 0, 9); }); it("from and toArray are inverses in case", () => { const n = 1058; const arr = numberArray(0, n); assert.deepEqual(arr, L.toArray(L.from(arr))); }); it("from and toArray are inverses", () => { fc.assert( fc.property(fc.nat(800000), n => { const arr = numberArray(0, n); assert.deepEqual(arr, L.toArray(L.from(arr))); }), { numRuns: 10 } ); }); function* iterable(n: number): IterableIterator<number> { for (let i = 0; i < n; ++i) { yield i; } } it("converts an iterable into a list", () => { const l = from(iterable(20)); assert.strictEqual(l.length, 20); assertIndicesFromTo(l, 0, 20); }); it("converts an iterable into a list same as Array.from even with falsy done", () => { const iterable = () => <any>{ [Symbol.iterator]() { let idx = 0; return { next: () => (idx++ === 0 ? { value: 1 } : { done: true }) }; } }; const l = from(iterable()); assert.deepEqual(Array.from(iterable()), L.toArray(l)); }); it("converts an array into a list", () => { assertListEqual(L.list(0, 1, 2, 3, 4), L.from([0, 1, 2, 3, 4])); }); it("converts a string into a list", () => { assertListEqual(L.from("hello"), L.list("h", "e", "l", "l", "o")); }); }); describe("insert and insertAll", () => { it("inserts element in list", () => { const l = list(0, 1, 2, 3, 5, 6, 7); const l2 = insert(4, 4, l); assert.strictEqual(nth(4, l2), 4); assertIndicesFromTo(l2, 0, 8); }); it("inserts all elements in list", () => { const l = list(0, 1, 2, 6, 7, 8); const l2 = insertAll(3, list(3, 4, 5), l); assertIndicesFromTo(l2, 0, 9); }); }); describe("reverse", () => { it("reverses a list", () => { const l = list(7, 6, 5, 4, 3, 2, 1, 0); const l2 = reverse(l); assertIndicesFromTo(l2, 0, 8); }); }); describe("isList", () => { it("returns true for list", () => { assert.isTrue(L.isList(list(0, 1, 2, 3))); }); it("gives correct type", () => { const l: any = list(0, 1, 2, 3, 4); if (L.isList<number>(l)) { L.append(5, l); // this should not give type error } }); it("returns false for other things", () => { assert.isFalse(L.isList([0, 1, 2, 3, 4])); assert.isFalse(L.isList({ foo: 0, bar: 1 })); assert.isFalse(L.isList(7)); assert.isFalse(L.isList("hello")); }); }); describe("zip", () => { it("can zipWith", () => { const l1 = L.list(0, 1, 2, 3, 4, 5); const l2 = L.list(3, 1, 4, 5, 3, 8); const r = L.zipWith(sum, l1, l2); assert.isTrue(equals(r, list(3, 2, 6, 8, 7, 13))); }); it("zipWith caps to shortest length", () => { const short = list(0, 1, 2); const long = list(2, 4, 9, 1, 2, 8); assertListEqual(L.zipWith(sum, short, long), list(2, 5, 11)); assertListEqual(L.zipWith(sum, long, short), list(2, 5, 11)); }); it("zip zips too pairs", () => { const as = list("a", "b", "c"); const bs = list(0, 1, 2); assertListEqual(L.zip(as, bs), list(["a", 0], ["b", 1], ["c", 2])); }); }); describe("sorting", () => { class Pair { constructor(readonly fst: number, readonly snd: number) {} "fantasy-land/lte"(b: Pair): boolean { if (this.fst === b.fst) { return this.snd <= b.snd; } else { return this.fst <= b.fst; } } } function compareNumber(a: number, b: number): -1 | 0 | 1 { if (a === b) { return 0; } else if (a < b) { return -1; } else { return 1; } } const unsorted = list( { n: 2, m: 1 }, { n: 1, m: 1 }, { n: 1, m: 2 }, { n: 1, m: 3 }, { n: 0, m: 1 }, { n: 3, m: 1 } ); const unsortedPairs = list( new Pair(2, 1), new Pair(1, 1), new Pair(1, 2), new Pair(1, 2), new Pair(1, 3), new Pair(0, 1), new Pair(3, 1) ); it("sort returns same list on empty list ", () => { const l = empty(); assert.strictEqual(l, L.sort(l)); }); it("sort sorts primitives ", () => { const l = L.list(5, 2, 9, 1, 7, 3, 9); assert.deepEqual(L.toArray(L.sort(l)), L.toArray(l).sort()); }); it("sort sorts Fantasy Land Ords", () => { const sorted = L.sort(unsortedPairs); const sortedPairs = [ new Pair(0, 1), new Pair(1, 1), new Pair(1, 2), new Pair(1, 2), new Pair(1, 3), new Pair(2, 1), new Pair(3, 1) ]; assert.deepEqual(L.toArray(sorted), sortedPairs); }); it("sortBy returns same list on empty list ", () => { const l = empty(); assert.strictEqual( l, L.sortBy(_ => { throw new Error("Should not be called"); }, l) ); }); it("sortBy is stable", () => { const sorted = L.sortBy(e => e.n, unsorted); assert.deepEqual(L.toArray(sorted), [ { n: 0, m: 1 }, { n: 1, m: 1 }, { n: 1, m: 2 }, { n: 1, m: 3 }, { n: 2, m: 1 }, { n: 3, m: 1 } ]); }); it("sortBy sort Fantasy Land Ords", () => { const unsorted = L.map( pair => ({ pair, sum: pair.fst + pair.snd }), unsortedPairs ); const sorted = L.sortBy(o => o.pair, unsorted); assert.deepEqual(L.toArray(sorted), [ { pair: new Pair(0, 1), sum: 1 }, { pair: new Pair(1, 1), sum: 2 }, { pair: new Pair(1, 2), sum: 3 }, { pair: new Pair(1, 2), sum: 3 }, { pair: new Pair(1, 3), sum: 4 }, { pair: new Pair(2, 1), sum: 3 }, { pair: new Pair(3, 1), sum: 4 } ]); }); it("sortWith is stable", () => { const sorted = L.sortWith((a, b) => compareNumber(a.n, b.n), unsorted); assert.deepEqual(L.toArray(sorted), [ { n: 0, m: 1 }, { n: 1, m: 1 }, { n: 1, m: 2 }, { n: 1, m: 3 }, { n: 2, m: 1 }, { n: 3, m: 1 } ]); }); }); describe("group", () => { it("group", () => { const l = L.list(1, 1, 1, 2, 2, 3, 4, 4); assertListEqual( L.group(l), L.list(L.list(1, 1, 1), L.list(2, 2), L.list(3), L.list(4, 4)) ); }); it("groups empty list to empty list", () => { assertListEqual(L.group(L.empty()), L.empty()); }); it("groupWith", () => { const l = L.list(4.2, 4.5, 1.1, 1.4, 3.5, 3.9); const l2 = L.groupWith((a, b) => Math.floor(a) === Math.floor(b), l); assertListEqual( l2, L.list(L.list(4.2, 4.5), L.list(1.1, 1.4), L.list(3.5, 3.9)) ); }); }); describe("intersperse", () => { it("inserts separator", () => { assertListEqual( L.intersperse(0, L.list(1, 2, 3, 4, 5)), L.list(1, 0, 2, 0, 3, 0, 4, 0, 5) ); }); }); describe("isEmpty", () => { it("returns true for empty list", () => { assert.isTrue(L.isEmpty(L.list())); }); it("returns false for non-empty list", () => { assert.isFalse(L.isEmpty(L.list(0, 1, 2, 3))); }); }); describe("toJSON", () => { it("works with numbers", () => { const l = list(0, 1, 2, 3, 4); const a = [0, 1, 2, 3, 4]; assert.strictEqual(JSON.stringify(l), JSON.stringify(a)); }); it("works with strings", () => { const l = list("one", "two", "three"); const a = ["one", "two", "three"]; assert.strictEqual(JSON.stringify(l), JSON.stringify(a)); }); it("works with objects", () => { const l = list({ one: 1 }, { two: 2 }, { three: 3 }); const a = [{ one: 1 }, { two: 2 }, { three: 3 }]; assert.strictEqual(JSON.stringify(l), JSON.stringify(a)); }); }); });
the_stack
import * as chai from "chai"; import "url-search-params-polyfill"; import { MindSphereSdk } from "../src"; import { EdgeAppInstanceModels } from "../src/api/sdk/open-edge/open-edge-models"; import { decrypt, loadAuth } from "../src/api/utils"; import { setupDeviceTestStructure, tearDownDeviceTestStructure } from "./test-device-setup-utils"; import { getPasskeyForUnitTest } from "./test-utils"; chai.should(); const timeOffset = new Date().getTime(); describe("[SDK] DeviceManagementClient.EdgeAppInstance", () => { const auth = loadAuth(); const sdk = new MindSphereSdk({ ...auth, basicAuth: decrypt(auth, getPasskeyForUnitTest()), }); const edgeAppInstanceClient = sdk.GetEdgeAppInstanceManagementClient(); const tenant = sdk.GetTenant(); const testAppInstance = { name: `testAppInst_${tenant}_${timeOffset}`, appInstanceId: `testAppInst_${tenant}_${timeOffset}`, deviceId: "string", releaseId: "string", applicationId: `testApp_${tenant}_${timeOffset}`, }; const testConfigurations = { deviceId: `${tenant}.UnitTestDeviceType`, appId: "718ca5ad0...", appReleaseId: "718ca5ad0...", appInstanceId: "718ca5ad0...", configuration: { sampleKey1: "sampleValue1", sampleKey2: "sampleValue2", }, }; let deviceTypeId = "aee2e37f-f562-4ed6-b90a-c43208dc054a"; let assetTypeId = `${tenant}.UnitTestDeviceAssetType`; let assetId = ""; let gFolderid = ""; let deviceId = ""; let appId = ""; let appReleaseId = ""; let appInstanceId = ""; before(async () => { // tear Down test infrastructure await tearDownDeviceTestStructure(sdk); // Setup the testing architecture const { device, deviceAsset, deviceType, deviceAssetType, folderid } = await setupDeviceTestStructure(sdk); assetTypeId = `${(deviceAssetType as any).id}`; deviceTypeId = `${(deviceType as any).id}`; assetId = `${(deviceAsset as any).assetId}`; deviceId = `${(device as any).id}`; gFolderid = `${folderid}`; testConfigurations.deviceId = `${(device as any).id}`; // Create a new app testAppInstance.deviceId = `${deviceId}`; testAppInstance.releaseId = `V001${timeOffset}`; const appInstRes = await edgeAppInstanceClient.PostAppInstance(testAppInstance); appInstanceId = (appInstRes as any).id; appId = (appInstRes as any).applicationId; appReleaseId = (appInstRes as any).releaseId; // Create a new app instance configuration testConfigurations.deviceId = `${deviceId}`; testConfigurations.appId = `${appId}`; testConfigurations.appInstanceId = `${appInstanceId}`; testConfigurations.appReleaseId = `${appReleaseId}`; await edgeAppInstanceClient.PostAppInstanceConfigurations(testConfigurations); }); after(async () => { // delete App configuration await edgeAppInstanceClient.DeleteAppInstanceConfiguration(appInstanceId); // Delete the app await edgeAppInstanceClient.DeleteAppInstance(appInstanceId); // tear Down test infrastructure await tearDownDeviceTestStructure(sdk); }); it("SDK should not be undefined", async () => { sdk.should.not.be.undefined; }); it("standard properties shoud be defined", async () => { edgeAppInstanceClient.should.not.be.undefined; edgeAppInstanceClient.GetGateway().should.be.equal(auth.gateway); (await edgeAppInstanceClient.GetToken()).length.should.be.greaterThan(200); (await edgeAppInstanceClient.GetToken()).length.should.be.greaterThan(200); }); it("should GET all app instances by deviceId @sanity", async () => { edgeAppInstanceClient.should.not.be.undefined; const apps = await edgeAppInstanceClient.GetAppInstances(deviceId); apps.should.not.be.undefined; apps.should.not.be.null; (apps as any).page.number.should.equal(0); (apps as any).page.size.should.equal(10); (apps as any).content.length.should.be.gte(0); }); it("should GET all app instances by deviceId (with size param)", async () => { edgeAppInstanceClient.should.not.be.undefined; const apps = await edgeAppInstanceClient.GetAppInstances(deviceId, 100, 0, "ASC"); apps.should.not.be.undefined; apps.should.not.be.null; (apps as any).page.number.should.equal(0); (apps as any).page.size.should.equal(100); (apps as any).content.length.should.be.gte(0); }); it("should GET the deployement status of the application instance by id", async () => { edgeAppInstanceClient.should.not.be.undefined; const status = await edgeAppInstanceClient.GetAppInstanceLifecycle(appInstanceId); status.should.not.be.undefined; status.should.not.be.null; (status as any).id.should.not.be.undefined; (status as any).id.should.not.be.null; (status as any).status.should.not.be.undefined; (status as any).status.should.not.be.null; }); it("should POST a new app instance for the given device id", async () => { edgeAppInstanceClient.should.not.be.undefined; // Add new device testAppInstance.name = `testAppInst_${tenant}_${timeOffset}_A`; testAppInstance.appInstanceId = `testAppInst_${tenant}_${timeOffset}_A`; testAppInstance.applicationId = `testApp_${tenant}_${timeOffset}_A`; testAppInstance.deviceId = `${deviceId}`; testAppInstance.releaseId = `V001${timeOffset}`; const appInstRes = await edgeAppInstanceClient.PostAppInstance(testAppInstance); appInstRes.should.not.be.undefined; appInstRes.should.not.be.null; (appInstRes as any).id.should.not.be.undefined; (appInstRes as any).id.should.not.be.null; (appInstRes as any).name.should.not.be.undefined; (appInstRes as any).name.should.not.be.null; (appInstRes as any).releaseId.should.not.be.undefined; (appInstRes as any).releaseId.should.not.be.null; (appInstRes as any).applicationId.should.not.be.undefined; (appInstRes as any).applicationId.should.not.be.null; const _appInstanceId = (appInstRes as any).id; // Delete App await edgeAppInstanceClient.DeleteAppInstance(_appInstanceId); }); it("should DELETE an app instance", async () => { edgeAppInstanceClient.should.not.be.undefined; // Create a new app instance testAppInstance.name = `testAppInst_${tenant}_${timeOffset}_B`; testAppInstance.appInstanceId = `testAppInst_${tenant}_${timeOffset}_B`; testAppInstance.applicationId = `testApp_${tenant}_${timeOffset}_B`; testAppInstance.deviceId = `${deviceId}`; testAppInstance.releaseId = `V001${timeOffset}`; const appInstRes = await edgeAppInstanceClient.PostAppInstance(testAppInstance); appInstRes.should.not.be.undefined; appInstRes.should.not.be.null; const _appInstanceId = (appInstRes as any).id; // Delete App await edgeAppInstanceClient.DeleteAppInstance(_appInstanceId); }); it("should PATCH Status of Application Release Instance", async () => { edgeAppInstanceClient.should.not.be.undefined; // Create a new instance testAppInstance.name = `testAppInst_${tenant}_${timeOffset}_C`; testAppInstance.appInstanceId = `testAppInst_${tenant}_${timeOffset}_C`; testAppInstance.applicationId = `testApp_${tenant}_${timeOffset}_C`; testAppInstance.deviceId = `${deviceId}`; testAppInstance.releaseId = `V001${timeOffset}`; const appInstRes = await edgeAppInstanceClient.PostAppInstance(testAppInstance); appInstRes.should.not.be.undefined; appInstRes.should.not.be.null; const _appInstanceId = (appInstRes as any).id; const testStatus = { status: EdgeAppInstanceModels.ApplicationInstanceLifeCycleStatus.StatusEnum.STOPPED, }; const _status = await edgeAppInstanceClient.PatchAppInstanceStatus(_appInstanceId, testStatus); _status.should.not.be.undefined; _status.should.not.be.null; (_status as any).status.should.equal( EdgeAppInstanceModels.ApplicationInstanceLifeCycleStatus.StatusEnum.STOPPED ); // Delete App await edgeAppInstanceClient.DeleteAppInstance(_appInstanceId); }); it("should GET all application configurations by device id @sanity", async () => { edgeAppInstanceClient.should.not.be.undefined; const configurations = await edgeAppInstanceClient.GetAppInstanceConfigurations(deviceId); configurations.should.not.be.undefined; configurations.should.not.be.null; (configurations as any).page.number.should.equal(0); (configurations as any).page.size.should.equal(10); (configurations as any).content.length.should.be.gte(0); }); it("should GET all app instance configurations by deviceId (with size param)", async () => { edgeAppInstanceClient.should.not.be.undefined; const configurations = await edgeAppInstanceClient.GetAppInstanceConfigurations(deviceId, 10, 0, "ASC"); configurations.should.not.be.undefined; configurations.should.not.be.null; (configurations as any).page.number.should.equal(0); (configurations as any).page.size.should.equal(10); (configurations as any).content.length.should.be.gte(0); }); it("should GET an instance configuration by id", async () => { edgeAppInstanceClient.should.not.be.undefined; // console.log(deviceId); // console.log(deviceTypeId); // console.log(appInstanceId); const all = await edgeAppInstanceClient.GetAppInstanceConfigurations(deviceId); // console.log(all); const configuration = await edgeAppInstanceClient.GetAppInstanceConfiguration(appInstanceId); configuration.should.not.be.undefined; configuration.should.not.be.null; (configuration as any).deviceId.should.not.be.undefined; (configuration as any).deviceId.should.not.be.null; (configuration as any).appId.should.not.be.undefined; (configuration as any).appId.should.not.be.null; (configuration as any).appReleaseId.should.not.be.undefined; (configuration as any).appReleaseId.should.not.be.null; (configuration as any).appInstanceId.should.not.be.undefined; (configuration as any).appInstanceId.should.not.be.null; }); it("should POST a new app instance configuration for the given device id and application instance id", async () => { edgeAppInstanceClient.should.not.be.undefined; // Delete App inst configuration await edgeAppInstanceClient.DeleteAppInstanceConfiguration(appInstanceId); // Add new configuration testConfigurations.deviceId = `${deviceId}`; testConfigurations.appId = `${appId}`; testConfigurations.appInstanceId = `${appInstanceId}`; testConfigurations.appReleaseId = `${appReleaseId}`; testConfigurations.configuration = { sampleKey1: "sampleValue1_A", sampleKey2: "sampleValue2_A", }; const instConfRes = await edgeAppInstanceClient.PostAppInstanceConfigurations(testConfigurations); instConfRes.should.not.be.undefined; instConfRes.should.not.be.null; (instConfRes as any).deviceId.should.not.be.undefined; (instConfRes as any).deviceId.should.not.be.null; (instConfRes as any).appId.should.not.be.undefined; (instConfRes as any).appId.should.not.be.null; (instConfRes as any).appReleaseId.should.not.be.undefined; (instConfRes as any).appReleaseId.should.not.be.null; (instConfRes as any).appInstanceId.should.not.be.undefined; (instConfRes as any).appInstanceId.should.not.be.null; }); it("should PATCH specified instance configuration", async () => { edgeAppInstanceClient.should.not.be.undefined; testConfigurations.deviceId = `${deviceId}`; testConfigurations.appId = `${appId}`; testConfigurations.appInstanceId = `${appInstanceId}`; testConfigurations.appReleaseId = `${appReleaseId}`; testConfigurations.configuration = { sampleKey1: `sampleValue1_B_${timeOffset}`, sampleKey2: `sampleValue2_B_${timeOffset}`, }; const instConfRes = await edgeAppInstanceClient.PatchAppInstanceConfigurationData( appInstanceId, testConfigurations ); instConfRes.should.not.be.undefined; instConfRes.should.not.be.null; (instConfRes as any).deviceId.should.not.be.undefined; (instConfRes as any).deviceId.should.not.be.null; (instConfRes as any).appId.should.not.be.undefined; (instConfRes as any).appId.should.not.be.null; (instConfRes as any).appReleaseId.should.not.be.undefined; (instConfRes as any).appReleaseId.should.not.be.null; (instConfRes as any).appInstanceId.should.not.be.undefined; (instConfRes as any).appInstanceId.should.not.be.null; }); /* it("should PATCH all instance configurations", async () => { edgeAppInstanceClient.should.not.be.undefined; const testAllConfigurations = { instanceConfigurations: [ { id: "Config01", configuration: { sampleKey1: `sampleValue1_C_1_${timeOffset}`, sampleKey2: `sampleValue2_C_1_${timeOffset}` } } ] }; await edgeAppInstanceClient.PatchAppInstanceConfigurations(testAllConfigurations); }); */ it("should DELETE an app instance configuration", async () => { // Delete App inst configuration await edgeAppInstanceClient.DeleteAppInstanceConfiguration(appInstanceId); }); });
the_stack
* vConsole core class */ import pkg from '../../package.json'; import * as tool from '../lib/tool'; import $ from '../lib/query'; import './core.less'; import tpl from './core.html'; import tplTabbar from './tabbar.html'; import tplTabbox from './tabbox.html'; import tplTopBarItem from './topbar_item.html'; import tplToolItem from './tool_item.html'; // built-in plugins import VConsolePlugin from '../lib/plugin'; import VConsoleLogPlugin from '../log/log'; import VConsoleDefaultPlugin from '../log/default'; import VConsoleSystemPlugin from '../log/system'; import VConsoleNetworkPlugin from '../network/network'; import VConsoleElementPlugin from '../element/element'; import VConsoleStoragePlugin from '../storage/storage'; declare interface VConsoleOptions { defaultPlugins?: string[]; maxLogNumber?: number; theme?: '' | 'dark' | 'light'; disableLogScrolling?: boolean; onReady?: Function; onClearLog?: Function; } const VCONSOLE_ID = '#__vconsole'; class VConsole { version: string; $dom: HTMLElement; isInited: boolean; option: VConsoleOptions = {}; activedTab: string; tabList: any[]; pluginList: {}; switchPos: { hasMoved: boolean; // exclude click event x: number; // right y: number; // bottom startX: number; startY: number; endX: number; endY: number; }; // export helper functions to public tool = tool; $ = $; // export static class static VConsolePlugin = VConsolePlugin; static VConsoleLogPlugin = VConsoleLogPlugin; static VConsoleDefaultPlugin = VConsoleDefaultPlugin; static VConsoleSystemPlugin = VConsoleSystemPlugin; static VConsoleNetworkPlugin = VConsoleNetworkPlugin; static VConsoleElementPlugin = VConsoleElementPlugin; static VConsoleStoragePlugin = VConsoleStoragePlugin; constructor(opt) { if (!!$.one(VCONSOLE_ID)) { console.debug('vConsole is already exists.'); return; } let that = this; this.version = pkg.version; this.$dom = null; this.isInited = false; this.option = { defaultPlugins: ['system', 'network', 'element', 'storage'] }; this.activedTab = ''; this.tabList = []; this.pluginList = {}; this.switchPos = { hasMoved: false, // exclude click event x: 0, // right y: 0, // bottom startX: 0, startY: 0, endX: 0, endY: 0 }; // export helper functions to public this.tool = tool; this.$ = $; // merge options if (tool.isObject(opt)) { for (let key in opt) { this.option[key] = opt[key]; } } // add built-in plugins this._addBuiltInPlugins(); // try to init let _onload = function() { if (that.isInited) { return; } that._render(); // that._mockTap(); that._bindEvent(); that._autoRun(); }; if (document !== undefined) { if (document.readyState === 'loading') { $.bind(<any>window, 'DOMContentLoaded', _onload); } else { _onload(); } } else { // if document does not exist, wait for it let _timer; let _pollingDocument = function() { if (!!document && document.readyState == 'complete') { _timer && clearTimeout(_timer); _onload(); } else { _timer = setTimeout(_pollingDocument, 1); } }; _timer = setTimeout(_pollingDocument, 1); } } /** * add built-in plugins */ _addBuiltInPlugins() { // add default log plugin this.addPlugin(new VConsoleDefaultPlugin('default', 'Log')); // add other built-in plugins according to user's config const list = this.option.defaultPlugins; const plugins = { 'system': {proto: VConsoleSystemPlugin, name: 'System'}, 'network': {proto: VConsoleNetworkPlugin, name: 'Network'}, 'element': {proto: VConsoleElementPlugin, name: 'Element'}, 'storage': {proto: VConsoleStoragePlugin, name: 'Storage'} }; if (!!list && tool.isArray(list)) { for (let i=0; i<list.length; i++) { let tab = plugins[list[i]]; if (!!tab) { this.addPlugin(new tab.proto(list[i], tab.name)); } else { console.debug('Unrecognized default plugin ID:', list[i]); } } } } /** * render panel DOM * @private */ _render() { if (! $.one(VCONSOLE_ID)) { const e = document.createElement('div'); e.innerHTML = tpl; document.documentElement.insertAdjacentElement('beforeend', e.children[0]); } this.$dom = $.one(VCONSOLE_ID); // reposition switch button const switchX = <any>tool.getStorage('switch_x') * 1, switchY = <any>tool.getStorage('switch_y') * 1; this.setSwitchPosition(switchX, switchY); // modify font-size const dpr = window.devicePixelRatio || 1; const viewportEl = document.querySelector('[name="viewport"]'); if (viewportEl) { const viewportContent = viewportEl.getAttribute('content') || ''; const initialScale = viewportContent.match(/initial\-scale\=\d+(\.\d+)?/); const scale = initialScale ? parseFloat(initialScale[0].split('=')[1]) : 1; if (scale < 1) { this.$dom.style.fontSize = 13 * dpr + 'px'; } } // remove from less to present transition effect $.one('.vc-mask', this.$dom).style.display = 'none'; // set theme this._updateTheme(); } /** * Update theme * @private */ _updateTheme() { let theme = this.option.theme; if (theme !== 'light' && theme !== 'dark') { theme = ''; // use system theme } this.$dom.setAttribute('data-theme', theme); } setSwitchPosition(switchX, switchY) { const $switch = $.one('.vc-switch', this.$dom); [switchX, switchY] = this._getSwitchButtonSafeAreaXY($switch, switchX, switchY); this.switchPos.x = switchX; this.switchPos.y = switchY; $switch.style.right = switchX + 'px'; $switch.style.bottom = switchY + 'px'; tool.setStorage('switch_x', switchX); tool.setStorage('switch_y', switchY); } /** * Get an safe [x, y] position for switch button * @private */ _getSwitchButtonSafeAreaXY($switch, x, y) { const docWidth = Math.max(document.documentElement.offsetWidth, window.innerWidth); const docHeight = Math.max(document.documentElement.offsetHeight, window.innerHeight); // check edge if (x + $switch.offsetWidth > docWidth) { x = docWidth - $switch.offsetWidth; } if (y + $switch.offsetHeight > docHeight) { y = docHeight - $switch.offsetHeight; } if (x < 0) { x = 0; } if (y < 20) { y = 20; } // safe area for iOS Home indicator return [x, y]; } /** * simulate tap event by touchstart & touchend * @private */ _mockTap() { let tapTime = 700, // maximun tap interval tapBoundary = 10; // max tap move distance let lastTouchStartTime, touchstartX, touchstartY, touchHasMoved = false, targetElem = null; this.$dom.addEventListener('touchstart', function(e) { // todo: if double click if (lastTouchStartTime === undefined) { const touch = e.targetTouches[0]; const target = <Element>e.target; touchstartX = touch.pageX; touchstartY = touch.pageY; lastTouchStartTime = e.timeStamp; targetElem = (target.nodeType === Node.TEXT_NODE ? target.parentNode : target); } }, false); this.$dom.addEventListener('touchmove', function(e) { const touch = e.changedTouches[0]; if (Math.abs(touch.pageX - touchstartX) > tapBoundary || Math.abs(touch.pageY - touchstartY) > tapBoundary) { touchHasMoved = true; } }); this.$dom.addEventListener('touchend', function(e) { // move and time within limits, manually trigger `click` event if (touchHasMoved === false && e.timeStamp - lastTouchStartTime < tapTime && targetElem != null) { let tagName = targetElem.tagName.toLowerCase(), needFocus = false, hasSelection = false; switch (tagName) { case 'textarea': // focus needFocus = true; break; case 'input': switch (targetElem.type) { case 'button': case 'checkbox': case 'file': case 'image': case 'radio': case 'submit': needFocus = false; break; default: needFocus = !targetElem.disabled && !targetElem.readOnly; } default: break; } if (typeof window.getSelection === 'function') { const selection = getSelection(); if (selection.rangeCount && selection.type === 'range') { // type: None|Caret|Range hasSelection = true; } } if (needFocus) { targetElem.focus(); } else if (!hasSelection) { e.preventDefault(); // prevent click 300ms later } if (!targetElem.disabled && !targetElem.readOnly) { const touch = e.changedTouches[0]; const event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); event.initEvent('click', true, true); targetElem.dispatchEvent(event); } } // reset values lastTouchStartTime = undefined; touchHasMoved = false; targetElem = null; }, false); } /** * bind DOM events * @private */ _bindEvent() { const that = this; // drag & drop switch button const $switch = $.one('.vc-switch', that.$dom); $.bind($switch, 'touchstart', function(e) { that.switchPos.startX = e.touches[0].pageX; that.switchPos.startY = e.touches[0].pageY; that.switchPos.hasMoved = false; }); $.bind($switch, 'touchend', function(e) { if (!that.switchPos.hasMoved) { return; } that.switchPos.startX = 0; that.switchPos.startY = 0; that.switchPos.hasMoved = false; that.setSwitchPosition(that.switchPos.endX, that.switchPos.endY); }); $.bind($switch, 'touchmove', function(e) { if (e.touches.length <= 0) { return; } const offsetX = e.touches[0].pageX - that.switchPos.startX, offsetY = e.touches[0].pageY - that.switchPos.startY; let x = Math.floor(that.switchPos.x - offsetX), y = Math.floor(that.switchPos.y - offsetY); [x, y] = that._getSwitchButtonSafeAreaXY($switch, x, y); $switch.style.right = x + 'px'; $switch.style.bottom = y + 'px'; that.switchPos.endX = x; that.switchPos.endY = y; that.switchPos.hasMoved = true; e.preventDefault(); }); // show console panel $.bind($.one('.vc-switch', that.$dom), 'click', function() { that.show(); }); // hide console panel $.bind($.one('.vc-hide', that.$dom), 'click', function() { that.hide(); }); // hide console panel when tap background mask $.bind($.one('.vc-mask', that.$dom), 'click', function(e) { if (e.target != $.one('.vc-mask')) { return false; } that.hide(); }); // show tab box $.delegate($.one('.vc-tabbar', that.$dom), 'click', '.vc-tab', function(e) { let tabName = this.dataset.tab; if (tabName == that.activedTab) { return; } that.showTab(tabName); }); // disable background scrolling let $content = $.one('.vc-content', that.$dom); let preventMove = false; $.bind($content, 'touchstart', function (e) { let top = $content.scrollTop, totalScroll = $content.scrollHeight, currentScroll = top + $content.offsetHeight; if (top === 0) { // when content is on the top, // reset scrollTop to lower position to prevent iOS apply scroll action to background $content.scrollTop = 1; // however, when content's height is less than its container's height, // scrollTop always equals to 0 (it is always on the top), // so we need to prevent scroll event manually if ($content.scrollTop === 0) { if (!$.hasClass(e.target, 'vc-cmd-input')) { // skip input preventMove = true; } } } else if (currentScroll === totalScroll) { // when content is on the bottom, // do similar processing $content.scrollTop = top - 1; if ($content.scrollTop === top) { if (!$.hasClass(e.target, 'vc-cmd-input')) { preventMove = true; } } } }); $.bind($content, 'touchmove', function (e) { if (preventMove) { e.preventDefault(); } }); $.bind($content, 'touchend', function (e) { preventMove = false; }); }; /** * auto run after initialization * @private */ _autoRun() { this.isInited = true; // init plugins for (let id in this.pluginList) { this._initPlugin(this.pluginList[id]); } // show first tab if (this.tabList.length > 0) { this.showTab(this.tabList[0]); } this.triggerEvent('ready'); } /** * trigger a vConsole.option event * @protect */ triggerEvent(eventName: string, param?: any) { eventName = 'on' + eventName.charAt(0).toUpperCase() + eventName.slice(1); if (tool.isFunction(this.option[eventName])) { this.option[eventName].apply(this, param); } } /** * init a plugin * @private */ _initPlugin(plugin) { let that = this; plugin.vConsole = this; // start init plugin.trigger('init'); // render tab (if it is a tab plugin then it should has tab-related events) plugin.trigger('renderTab', function(tabboxHTML) { // add to tabList that.tabList.push(plugin.id); // render tabbar let $tabbar = $.render(tplTabbar, {id: plugin.id, name: plugin.name}); $.one('.vc-tabbar', that.$dom).insertAdjacentElement('beforeend', $tabbar); // render tabbox let $tabbox = $.render(tplTabbox, {id: plugin.id}); if (!!tabboxHTML) { if (tool.isString(tabboxHTML)) { $tabbox.innerHTML += tabboxHTML; } else if (tool.isFunction(tabboxHTML.appendTo)) { tabboxHTML.appendTo($tabbox); } else if (tool.isElement(tabboxHTML)) { $tabbox.insertAdjacentElement('beforeend', tabboxHTML); } } $.one('.vc-content', that.$dom).insertAdjacentElement('beforeend', $tabbox); }); // render top bar plugin.trigger('addTopBar', function(btnList) { if (!btnList) { return; } let $topbar = $.one('.vc-topbar', that.$dom); for (let i=0; i<btnList.length; i++) { let item = btnList[i]; let $item = <HTMLElement>$.render(tplTopBarItem, { name: item.name || 'Undefined', className: item.className || '', pluginID: plugin.id }); if (item.data) { for (let k in item.data) { $item.dataset[k] = item.data[k]; } } if (tool.isFunction(item.onClick)) { $.bind($item, 'click', function(e) { let enable = item.onClick.call($item); if (enable === false) { // do nothing } else { $.removeClass($.all('.vc-topbar-' + plugin.id), 'vc-actived'); $.addClass($item, 'vc-actived'); } }); } $topbar.insertAdjacentElement('beforeend', $item); } }); // render tool bar plugin.trigger('addTool', function(toolList) { if (!toolList) { return; } let $defaultBtn = $.one('.vc-tool-last', that.$dom); for (let i=0; i<toolList.length; i++) { let item = toolList[i]; let $item = $.render(tplToolItem, { name: item.name || 'Undefined', pluginID: plugin.id }); if (item.global == true) { $.addClass($item, 'vc-global-tool'); } if (tool.isFunction(item.onClick)) { $.bind($item, 'click', function(e) { item.onClick.call($item); }); } $defaultBtn.parentNode.insertBefore($item, $defaultBtn); } }); // end init plugin.isReady = true; plugin.trigger('ready'); } /** * trigger an event for each plugin * @private */ _triggerPluginsEvent(eventName) { for (let id in this.pluginList) { if (this.pluginList[id].isReady) { this.pluginList[id].trigger(eventName); } } } /** * trigger an event by plugin's name * @private */ _triggerPluginEvent(pluginName, eventName) { let plugin = this.pluginList[pluginName]; if (!!plugin && plugin.isReady) { plugin.trigger(eventName); } } /** * add a new plugin * @public * @param object VConsolePlugin object * @return boolean */ addPlugin(plugin) { // ignore this plugin if it has already been installed if (this.pluginList[plugin.id] !== undefined) { console.debug('Plugin ' + plugin.id + ' has already been added.'); return false; } this.pluginList[plugin.id] = plugin; // init plugin only if vConsole is ready if (this.isInited) { this._initPlugin(plugin); // if it's the first plugin, show it by default if (this.tabList.length == 1) { this.showTab(this.tabList[0]); } } return true; } /** * remove a plugin * @public * @param string pluginID * @return boolean */ removePlugin(pluginID) { pluginID = (pluginID + '').toLowerCase(); let plugin = this.pluginList[pluginID]; // skip if is has not been installed if (plugin === undefined) { console.debug('Plugin ' + pluginID + ' does not exist.'); return false; } // trigger `remove` event before uninstall plugin.trigger('remove'); // the plugin will not be initialized before vConsole is ready, // so the plugin does not need to handle DOM-related actions in this case if (this.isInited) { let $tabbar = $.one('#__vc_tab_' + pluginID); $tabbar && $tabbar.parentNode.removeChild($tabbar); // remove topbar let $topbar = $.all('.vc-topbar-' + pluginID, this.$dom); for (let i=0; i<$topbar.length; i++) { $topbar[i].parentNode.removeChild($topbar[i]); } // remove content let $content = $.one('#__vc_log_' + pluginID); $content && $content.parentNode.removeChild($content); // remove tool bar let $toolbar = $.all('.vc-tool-' + pluginID, this.$dom); for (let i=0; i<$toolbar.length; i++) { $toolbar[i].parentNode.removeChild($toolbar[i]); } } // remove plugin from list let index = this.tabList.indexOf(pluginID); if (index > -1) { this.tabList.splice(index, 1); } try { delete this.pluginList[pluginID]; } catch (e) { this.pluginList[pluginID] = undefined; } // show the first plugin by default if (this.activedTab == pluginID) { if (this.tabList.length > 0) { this.showTab(this.tabList[0]); } } return true; } /** * show console panel * @public */ show() { if (!this.isInited) { return; } let that = this; // before show console panel, // trigger a transitionstart event to make panel's property 'display' change from 'none' to 'block' let $panel = $.one('.vc-panel', this.$dom); $panel.style.display = 'block'; // set 10ms delay to fix confict between display and transition setTimeout(function() { $.addClass(that.$dom, 'vc-toggle'); that._triggerPluginsEvent('showConsole'); let $mask = $.one('.vc-mask', that.$dom); $mask.style.display = 'block'; }, 10); } /** * hide console panel * @public */ hide() { if (!this.isInited) { return; } $.removeClass(this.$dom, 'vc-toggle'); setTimeout(() => { // panel will be hidden by CSS transition in 0.3s $.one('.vc-mask', this.$dom).style.display = 'none'; $.one('.vc-panel', this.$dom).style.display = 'none'; }, 330); this._triggerPluginsEvent('hideConsole'); } /** * show switch button * @public */ showSwitch() { if (!this.isInited) { return; } let $switch = $.one('.vc-switch', this.$dom); $switch.style.display = 'block'; } /** * hide switch button */ hideSwitch() { if (!this.isInited) { return; } let $switch = $.one('.vc-switch', this.$dom); $switch.style.display = 'none'; } /** * show a tab * @public */ showTab(tabID) { if (!this.isInited) { return; } let $logbox = $.one('#__vc_log_' + tabID); // set actived status $.removeClass($.all('.vc-tab', this.$dom), 'vc-actived'); $.addClass($.one('#__vc_tab_' + tabID), 'vc-actived'); $.removeClass($.all('.vc-logbox', this.$dom), 'vc-actived'); $.addClass($logbox, 'vc-actived'); // show topbar let $curTopbar = $.all('.vc-topbar-' + tabID, this.$dom); $.removeClass($.all('.vc-toptab', this.$dom), 'vc-toggle'); $.addClass($curTopbar, 'vc-toggle'); if ($curTopbar.length > 0) { $.addClass($.one('.vc-content', this.$dom), 'vc-has-topbar'); } else { $.removeClass($.one('.vc-content', this.$dom), 'vc-has-topbar'); } // show toolbar $.removeClass($.all('.vc-tool', this.$dom), 'vc-toggle'); $.addClass($.all('.vc-tool-' + tabID, this.$dom), 'vc-toggle'); // trigger plugin event this.activedTab && this._triggerPluginEvent(this.activedTab, 'hide'); this.activedTab = tabID; this._triggerPluginEvent(this.activedTab, 'show'); } /** * update option(s) * @public */ setOption(keyOrObj, value) { if (tool.isString(keyOrObj)) { this.option[keyOrObj] = value; this._triggerPluginsEvent('updateOption'); this._updateTheme(); } else if (tool.isObject(keyOrObj)) { for (let k in keyOrObj) { this.option[k] = keyOrObj[k]; } this._triggerPluginsEvent('updateOption'); this._updateTheme(); } else { console.debug('The first parameter of vConsole.setOption() must be a string or an object.'); } } /** * uninstall vConsole * @public */ destroy() { if (!this.isInited) { return; } // remove plugins let IDs = Object.keys(this.pluginList); for (let i = IDs.length - 1; i >= 0; i--) { this.removePlugin(IDs[i]); } // remove DOM this.$dom.parentNode.removeChild(this.$dom); // reverse isInited when destroyed this.isInited = false; } } // END class export default VConsole;
the_stack
import * as React from "react"; import { Color, colorFromHTMLColor, ColorGradient, colorToHTMLColorHEX, deepClone, interpolateColors, } from "../../core"; import { ColorPalette, predefinedPalettes } from "../resources"; import { ColorPicker, colorToCSS } from "./fluentui_color_picker"; import { InputField } from "./color_space_picker"; import { TabsView } from "./tabs_view"; import { ReorderListView } from "../views/panels/object_list_editor"; import { Button } from "../views/panels/widgets/controls"; import { Callout, Dropdown } from "@fluentui/react"; import { Colorspace } from "./fluent_ui_gradient_picker"; export interface GradientPickerProps { defaultValue?: ColorGradient; onPick?: (gradient: ColorGradient) => void; } export interface GradientPickerState { currentTab: string; currentGradient: ColorGradient; isPickerOpen: boolean; currentItemId: string; currentColor: Color; currentItemIdx: number; } export class GradientPicker extends React.Component< GradientPickerProps, GradientPickerState > { public static tabs = [ { name: "palettes", label: "Palettes" }, { name: "custom", label: "Custom" }, ]; constructor(props: GradientPickerProps) { super(props); this.state = { currentTab: "palettes", currentGradient: this.props.defaultValue || { colorspace: Colorspace.LAB, colors: [ { r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }, ], }, isPickerOpen: false, currentItemId: "", currentColor: null, currentItemIdx: null, }; } public selectGradient(gradient: ColorGradient, emit: boolean = false) { this.setState( { currentGradient: gradient, }, () => { if (emit) { if (this.props.onPick) { this.props.onPick(gradient); } } } ); } public renderGradientPalettes() { const items = predefinedPalettes.filter( (x) => x.type == "sequential" || x.type == "diverging" ); const groups: [string, ColorPalette[]][] = []; const group2Index = new Map<string, number>(); for (const p of items) { const groupName = p.name.split("/")[0]; let group: ColorPalette[]; if (group2Index.has(groupName)) { group = groups[group2Index.get(groupName)][1]; } else { group = []; group2Index.set(groupName, groups.length); groups.push([groupName, group]); } group.push(p); } return ( <section className="palettes"> <ul> {groups.map((group, index) => { return ( <li key={`m${index}`}> <div className="label">{group[0]}</div> <ul> {group[1].map((x) => { const gradient: ColorGradient = { colors: x.colors[0], colorspace: Colorspace.LAB, }; return ( <li key={x.name} className="item" onClick={() => this.selectGradient(gradient, true)} > <GradientView gradient={gradient} /> <label>{x.name.split("/")[1]}</label> </li> ); })} </ul> </li> ); })} </ul> </section> ); } private changeColorPickerState(id: string, color: Color, idx: number) { this.setState({ ...this.state, isPickerOpen: !this.state.isPickerOpen, currentItemId: id, currentColor: color, currentItemIdx: idx, }); } private renderColorPicker(): JSX.Element { return ( <> {this.state.isPickerOpen && ( <Callout target={`#${this.state.currentItemId}`} onDismiss={() => this.changeColorPickerState(this.state.currentItemId, null, null) } alignTargetEdge > <ColorPicker defaultValue={this.state.currentColor} onPick={(color) => { const newGradient = deepClone(this.state.currentGradient); newGradient.colors[this.state.currentItemIdx] = color; this.selectGradient(newGradient, true); }} parent={this} /> </Callout> )} </> ); } // eslint-disable-next-line public render() { return ( <div className="gradient-picker"> <TabsView tabs={GradientPicker.tabs} currentTab={this.state.currentTab} onSelect={(tab) => this.setState({ currentTab: tab })} /> {this.state.currentTab == "palettes" ? this.renderGradientPalettes() : null} {this.state.currentTab == "custom" ? ( <section className="gradient-editor"> <div className="row"> <GradientView gradient={this.state.currentGradient} /> </div> <div className="colors-scroll"> <ReorderListView enabled={true} onReorder={(dragIndex, dropIndex) => { const newGradient = deepClone(this.state.currentGradient); ReorderListView.ReorderArray( newGradient.colors, dragIndex, dropIndex ); this.selectGradient(newGradient, true); }} > {this.state.currentGradient.colors.map((color, i) => { return ( <div className="color-row" key={`m${i}`}> <span id={`color_${i}`} className="color-item" style={{ background: colorToCSS(color) }} onClick={() => { this.changeColorPickerState(`color_${i}`, color, i); }} /> <InputField defaultValue={colorToHTMLColorHEX(color)} onEnter={(value) => { const newColor = colorFromHTMLColor(value); const newGradient = deepClone( this.state.currentGradient ); newGradient.colors[i] = newColor; this.selectGradient(newGradient, true); return true; }} /> <Button icon={"ChromeClose"} onClick={() => { if (this.state.currentGradient.colors.length > 1) { const newGradient = deepClone( this.state.currentGradient ); newGradient.colors.splice(i, 1); this.selectGradient(newGradient, true); } }} /> </div> ); })} {this.renderColorPicker()} </ReorderListView> </div> <div className="row"> <Button icon={"general/plus"} text="Add" onClick={() => { const newGradient = deepClone(this.state.currentGradient); newGradient.colors.push({ r: 150, g: 150, b: 150 }); this.selectGradient(newGradient, true); }} />{" "} <Button icon={"Sort"} text="Reverse" onClick={() => { const newGradient = deepClone(this.state.currentGradient); newGradient.colors.reverse(); this.selectGradient(newGradient, true); }} />{" "} <Dropdown options={[ { key: Colorspace.HCL, text: "HCL" }, { key: Colorspace.LAB, text: "Lab" }, ]} onChange={(event, option) => { if (option) { const newGradient = deepClone(this.state.currentGradient); newGradient.colorspace = option.key as Colorspace; this.selectGradient(newGradient, true); } }} /> </div> </section> ) : null} </div> ); } } export class GradientView extends React.PureComponent< { gradient: ColorGradient; }, Record<string, never> > { protected refCanvas: HTMLCanvasElement; public componentDidMount() { this.componentDidUpdate(); } public componentDidUpdate() { // Chrome doesn't like get/putImageData in this method // Doing so will cause the popup editor to not layout, although any change in its style will fix setTimeout(() => { if (!this.refCanvas || !this.props.gradient) { return; } const ctx = this.refCanvas.getContext("2d"); const width = this.refCanvas.width; const height = this.refCanvas.height; const scale = interpolateColors( this.props.gradient.colors, this.props.gradient.colorspace ); const data = ctx.getImageData(0, 0, width, height); for (let i = 0; i < data.width; i++) { const t = i / (data.width - 1); const c = scale(t); for (let y = 0; y < data.height; y++) { let ptr = (i + y * data.width) * 4; data.data[ptr++] = c.r; data.data[ptr++] = c.g; data.data[ptr++] = c.b; data.data[ptr++] = 255; } } ctx.putImageData(data, 0, 0); }, 0); } public render() { return ( <span className="gradient-view"> <canvas ref={(e) => (this.refCanvas = e)} width={50} height={2} /> </span> ); } }
the_stack
import type { MikroORM } from '@mikro-orm/core'; import type { MySqlDriver } from '@mikro-orm/mysql'; import { Author2, Book2 } from '../entities-sql'; import { initORMMySql, mockLogger } from '../bootstrap'; import { Author2Subscriber } from '../subscribers/Author2Subscriber'; import { EverythingSubscriber } from '../subscribers/EverythingSubscriber'; import { FlushSubscriber } from '../subscribers/FlushSubscriber'; import { Test2Subscriber } from '../subscribers/Test2Subscriber'; describe('read-replicas', () => { let orm: MikroORM<MySqlDriver>; beforeAll(async () => orm = await initORMMySql()); beforeEach(async () => orm.getSchemaGenerator().clearDatabase()); afterEach(() => { orm.config.set('debug', false); Author2Subscriber.log.length = 0; EverythingSubscriber.log.length = 0; FlushSubscriber.log.length = 0; Test2Subscriber.log.length = 0; }); describe('when preferReadReplicas is true (default behaviour)', () => { test('will prefer replicas for read operations outside a transaction', async () => { const mock = mockLogger(orm, ['query']); let author = new Author2('Jon Snow', 'snow@wall.st'); author.born = new Date('1990-03-23'); author.books.add(new Book2('B', author)); await orm.em.persistAndFlush(author); expect(mock.mock.calls[0][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[1][0]).toMatch(/insert into `author2`.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[2][0]).toMatch(/insert into `book2`.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[3][0]).toMatch(/commit.*via write connection '127\.0\.0\.1'/); orm.em.clear(); author = (await orm.em.findOne(Author2, author))!; await orm.em.findOne(Author2, author, { refresh: true }); await orm.em.findOne(Author2, author, { refresh: true }); expect(mock.mock.calls[4][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via read connection 'read-\d'/); expect(mock.mock.calls[5][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via read connection 'read-\d'/); expect(mock.mock.calls[6][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via read connection 'read-\d'/); author.name = 'Jon Blow'; await orm.em.flush(); expect(mock.mock.calls[7][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[8][0]).toMatch(/update `author2` set `name` = \?, `updated_at` = \? where `id` = \?.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[9][0]).toMatch(/commit.*via write connection '127\.0\.0\.1'/); const qb = orm.em.createQueryBuilder(Author2, 'a', 'write'); await qb.select('*').where({ name: /.*Blow/ }).execute(); expect(mock.mock.calls[10][0]).toMatch(/select `a`.* from `author2` as `a` where `a`.`name` like \?.*via write connection '127\.0\.0\.1'/); await orm.em.transactional(async em => { const book = await em.findOne(Book2, { title: 'B' }); author.name = 'Jon Flow'; author.favouriteBook = book!; await em.flush(); }); expect(mock.mock.calls[11][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[12][0]).toMatch(/select.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[13][0]).toMatch(/update.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[14][0]).toMatch(/commit.*via write connection '127\.0\.0\.1'/); }); test('can explicitly set connection type for find operations', async () => { const mock = mockLogger(orm, ['query']); const author = new Author2('Jon Snow', 'snow@wall.st'); author.born = new Date('1990-03-23'); author.books.add(new Book2('B', author)); await orm.em.persistAndFlush(author); // defaults to read await orm.em.findOne(Author2, author, { refresh: true }); expect(mock.mock.calls[4][0]).toMatch(/via read connection 'read-.*'/); // explicitly set to read await orm.em.findOne(Author2, author, { connectionType: 'read',refresh: true }); expect(mock.mock.calls[5][0]).toMatch(/via read connection 'read-.*'/); // explicitly set to write await orm.em.findOne(Author2, author, { connectionType: 'write', refresh: true }); expect(mock.mock.calls[6][0]).toMatch(/via write connection '127\.0\.0\.1'/); // when running in a transaction will always use a write connection await orm.em.transactional(async em => { return em.findOne(Author2, author, { connectionType: 'read', refresh: true }); }); expect(mock.mock.calls[7][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[8][0]).toMatch(/select.*via write connection '127\.0\.0\.1'/); }); test('can explicitly set connection type for count operations', async () => { const mock = mockLogger(orm, ['query']); const author = new Author2('Jon Snow', 'snow@wall.st'); author.born = new Date('1990-03-23'); author.books.add(new Book2('B', author)); await orm.em.persistAndFlush(author); // defaults to read await orm.em.count(Author2, {}); expect(mock.mock.calls[4][0]).toMatch(/via read connection 'read-.*'/); // explicitly set to read await orm.em.count(Author2, {},{ connectionType: 'read' }); expect(mock.mock.calls[5][0]).toMatch(/via read connection 'read-.*'/); // explicitly set to write await orm.em.count(Author2, {},{ connectionType: 'write' }); expect(mock.mock.calls[6][0]).toMatch(/via write connection '127\.0\.0\.1'/); // when running in a transaction will always use a write connection await orm.em.transactional(async em => { return em.count(Author2, {},{ connectionType: 'read' }); }); expect(mock.mock.calls[7][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[8][0]).toMatch(/select.*via write connection '127\.0\.0\.1'/); }); }); describe('when preferReadReplicas is false', () => { test('will always use write connections', async () => { orm.config.set('preferReadReplicas', false); const mock = mockLogger(orm, ['query']); let author = new Author2('Jon Snow', 'snow@wall.st'); author.born = new Date('1990-03-23'); author.books.add(new Book2('B', author)); await orm.em.persistAndFlush(author); expect(mock.mock.calls[0][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[1][0]).toMatch(/insert into `author2`.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[2][0]).toMatch(/insert into `book2`.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[3][0]).toMatch(/commit.*via write connection '127\.0\.0\.1'/); orm.em.clear(); author = (await orm.em.findOne(Author2, author))!; await orm.em.findOne(Author2, author, { refresh: true }); await orm.em.findOne(Author2, author, { refresh: true }); expect(mock.mock.calls[4][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[5][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[6][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via write connection '127\.0\.0\.1'/); author.name = 'Jon Blow'; await orm.em.flush(); expect(mock.mock.calls[7][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[8][0]).toMatch(/update `author2` set `name` = \?, `updated_at` = \? where `id` = \?.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[9][0]).toMatch(/commit.*via write connection '127\.0\.0\.1'/); const qb = orm.em.createQueryBuilder(Author2, 'a', 'write'); await qb.select('*').where({ name: /.*Blow/ }).execute(); expect(mock.mock.calls[10][0]).toMatch(/select `a`.* from `author2` as `a` where `a`.`name` like \?.*via write connection '127\.0\.0\.1'/); await orm.em.transactional(async em => { const book = await em.findOne(Book2, { title: 'B' }); author.name = 'Jon Flow'; author.favouriteBook = book!; await em.flush(); }); expect(mock.mock.calls[11][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[12][0]).toMatch(/select.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[13][0]).toMatch(/update.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[14][0]).toMatch(/commit.*via write connection '127\.0\.0\.1'/); }); test('can explicitly set connection type for find operations', async () => { orm.config.set('preferReadReplicas', false); const mock = mockLogger(orm, ['query']); const author = new Author2('Jon Snow', 'snow@wall.st'); author.born = new Date('1990-03-23'); author.books.add(new Book2('B', author)); await orm.em.persistAndFlush(author); // defaults to write await orm.em.findOne(Author2, author, { refresh: true }); expect(mock.mock.calls[4][0]).toMatch(/via write connection '127\.0\.0\.1'/); // explicitly set to read await orm.em.findOne(Author2, author, { connectionType: 'read',refresh: true }); expect(mock.mock.calls[5][0]).toMatch(/via read connection 'read-.*'/); // explicitly set to write await orm.em.findOne(Author2, author, { connectionType: 'write', refresh: true }); expect(mock.mock.calls[6][0]).toMatch(/via write connection '127\.0\.0\.1'/); // when running in a transaction will always use a write connection await orm.em.transactional(async em => { return em.findOne(Author2, author, { connectionType: 'read', refresh: true }); }); expect(mock.mock.calls[7][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[8][0]).toMatch(/select.*via write connection '127\.0\.0\.1'/); }); test('can explicitly set connection type for count operations', async () => { orm.config.set('preferReadReplicas', false); const mock = mockLogger(orm, ['query']); const author = new Author2('Jon Snow', 'snow@wall.st'); author.born = new Date('1990-03-23'); author.books.add(new Book2('B', author)); await orm.em.persistAndFlush(author); // defaults to write await orm.em.count(Author2, {}); expect(mock.mock.calls[4][0]).toMatch(/via write connection '127\.0\.0\.1'/); // explicitly set to read await orm.em.count(Author2, {},{ connectionType: 'read' }); expect(mock.mock.calls[5][0]).toMatch(/via read connection 'read-.*'/); // explicitly set to write await orm.em.count(Author2, {},{ connectionType: 'write' }); expect(mock.mock.calls[6][0]).toMatch(/via write connection '127\.0\.0\.1'/); // when running in a transaction will always use a write connection await orm.em.transactional(async em => { return em.count(Author2, {},{ connectionType: 'read' }); }); expect(mock.mock.calls[7][0]).toMatch(/begin.*via write connection '127\.0\.0\.1'/); expect(mock.mock.calls[8][0]).toMatch(/select.*via write connection '127\.0\.0\.1'/); }); }); afterAll(async () => orm.close(true)); });
the_stack
import assert from "assert"; import { ReadableStream } from "stream/web"; import { setTimeout } from "timers/promises"; import { TextDecoder, TextEncoder } from "util"; import { Response } from "@miniflare/core"; import { HTMLRewriter, HTMLRewriterPlugin } from "@miniflare/html-rewriter"; import { getObjectProperties, useMiniflareWithHandler, } from "@miniflare/shared-test"; import test, { ExecutionContext, Macro } from "ava"; import { HTMLRewriter as BaseHTMLRewriter, Comment, Doctype, DocumentEnd, Element, TextChunk, } from "html-rewriter-wasm"; // TODO (someday): debug why removing .serial breaks some of these async tests const encoder = new TextEncoder(); // Must be run in serial tests function recordFree(t: ExecutionContext): { freed: boolean } { const result = { freed: false }; const originalFree = BaseHTMLRewriter.prototype.free; BaseHTMLRewriter.prototype.free = function () { result.freed = true; originalFree.bind(this)(); }; t.teardown(() => { BaseHTMLRewriter.prototype.free = originalFree; }); return result; } // region: ELEMENT HANDLERS const mutationsMacro: Macro< [ ( rw: HTMLRewriter, handler: (token: Element | TextChunk | Comment) => void ) => HTMLRewriter, string, { beforeAfter: string; replace: string; replaceHtml: string; remove: string; } ] > = async (t, func, input, expected) => { // In all these tests, only process text chunks containing text. All test // inputs for text handlers will be single characters, so we'll only process // text nodes once. // before/after let res = func(new HTMLRewriter(), (token) => { if ("text" in token && !token.text) return; token.before("<span>before</span>"); token.before("<span>before html</span>", { html: true }); token.after("<span>after</span>"); token.after("<span>after html</span>", { html: true }); }).transform(new Response(input)); t.is(await res.text(), expected.beforeAfter); // replace res = func(new HTMLRewriter(), (token) => { if ("text" in token && !token.text) return; token.replace("<span>replace</span>"); }).transform(new Response(input)); t.is(await res.text(), expected.replace); res = func(new HTMLRewriter(), (token) => { if ("text" in token && !token.text) return; token.replace("<span>replace</span>", { html: true }); }).transform(new Response(input)); t.is(await res.text(), expected.replaceHtml); // remove res = func(new HTMLRewriter(), (token) => { if ("text" in token && !token.text) return; t.false(token.removed); token.remove(); t.true(token.removed); }).transform(new Response(input)); t.is(await res.text(), expected.remove); }; // region: element const elementMutationsInput = "<p>test</p>"; const elementMutationsExpected = { beforeAfter: [ "&lt;span&gt;before&lt;/span&gt;", "<span>before html</span>", "<p>", "test", "</p>", "<span>after html</span>", "&lt;span&gt;after&lt;/span&gt;", ].join(""), replace: "&lt;span&gt;replace&lt;/span&gt;", replaceHtml: "<span>replace</span>", remove: "", }; test("HTMLRewriter: handles element properties", async (t) => { t.plan(5); const res = new HTMLRewriter() .on("p", { element(element) { t.is(element.tagName, "p"); element.tagName = "h1"; t.deepEqual([...element.attributes], [["class", "red"]]); t.false(element.removed); t.is(element.namespaceURI, "http://www.w3.org/1999/xhtml"); }, }) .transform(new Response('<p class="red">test</p>')); t.is(await res.text(), '<h1 class="red">test</h1>'); }); test("HTMLRewriter: handles element attribute methods", async (t) => { t.plan(5); const res = new HTMLRewriter() .on("p", { element(element) { t.is(element.getAttribute("class"), "red"); t.is(element.getAttribute("id"), null); t.true(element.hasAttribute("class")); t.false(element.hasAttribute("id")); element.setAttribute("id", "header"); element.removeAttribute("class"); }, }) .transform(new Response('<p class="red">test</p>')); t.is(await res.text(), '<p id="header">test</p>'); }); test( "HTMLRewriter: handles element mutations", mutationsMacro, (rw, element) => rw.on("p", { element }), elementMutationsInput, elementMutationsExpected ); test("HTMLRewriter: handles element specific mutations", async (t) => { // prepend/append let res = new HTMLRewriter() .on("p", { element(element) { element.prepend("<span>prepend</span>"); element.prepend("<span>prepend html</span>", { html: true }); element.append("<span>append</span>"); element.append("<span>append html</span>", { html: true }); }, }) .transform(new Response("<p>test</p>")); t.is( await res.text(), [ "<p>", "<span>prepend html</span>", "&lt;span&gt;prepend&lt;/span&gt;", "test", "&lt;span&gt;append&lt;/span&gt;", "<span>append html</span>", "</p>", ].join("") ); // setInnerContent res = new HTMLRewriter() .on("p", { element(element) { element.setInnerContent("<span>replace</span>"); }, }) .transform(new Response("<p>test</p>")); t.is(await res.text(), "<p>&lt;span&gt;replace&lt;/span&gt;</p>"); res = new HTMLRewriter() .on("p", { element(element) { element.setInnerContent("<span>replace</span>", { html: true }); }, }) .transform(new Response("<p>test</p>")); t.is(await res.text(), "<p><span>replace</span></p>"); // removeAndKeepContent res = new HTMLRewriter() .on("p", { element(element) { element.removeAndKeepContent(); }, }) .transform(new Response("<p>test</p>")); t.is(await res.text(), "test"); }); test.serial("HTMLRewriter: handles element async handler", async (t) => { const res = new HTMLRewriter() .on("p", { async element(element) { await setTimeout(50); element.setInnerContent("new"); }, }) .transform(new Response("<p>test</p>")); t.is(await res.text(), "<p>new</p>"); }); test("HTMLRewriter: handles element class handler", async (t) => { class Handler { constructor(private content: string) {} // noinspection JSUnusedGlobalSymbols element(element: Element) { element.setInnerContent(this.content); } } const res = new HTMLRewriter() .on("p", new Handler("new")) .transform(new Response("<p>test</p>")); t.is(await res.text(), "<p>new</p>"); }); // endregion: element // region: comments const commentsMutationsInput = "<p><!--test--></p>"; const commentsMutationsExpected = { beforeAfter: [ "<p>", "&lt;span&gt;before&lt;/span&gt;", "<span>before html</span>", "<!--test-->", "<span>after html</span>", "&lt;span&gt;after&lt;/span&gt;", "</p>", ].join(""), replace: "<p>&lt;span&gt;replace&lt;/span&gt;</p>", replaceHtml: "<p><span>replace</span></p>", remove: "<p></p>", }; const commentPropertiesMacro: Macro< [(rw: HTMLRewriter, comments: (comment: Comment) => void) => HTMLRewriter] > = async (t, func) => { t.plan(3); const res = func(new HTMLRewriter(), (comment) => { t.false(comment.removed); t.is(comment.text, "test"); comment.text = "new"; }).transform(new Response("<p><!--test--></p>")); t.is(await res.text(), "<p><!--new--></p>"); }; test( "HTMLRewriter: handles comment properties", commentPropertiesMacro, (rw, comments) => rw.on("p", { comments }) ); test( "HTMLRewriter: handles comment mutations", mutationsMacro, (rw, comments) => rw.on("p", { comments }), commentsMutationsInput, commentsMutationsExpected ); const commentAsyncHandlerMacro: Macro< [(rw: HTMLRewriter, comments: (c: Comment) => Promise<void>) => HTMLRewriter] > = async (t, func) => { const res = func(new HTMLRewriter(), async (comment) => { await setTimeout(50); comment.text = "new"; }).transform(new Response("<p><!--test--></p>")); t.is(await res.text(), "<p><!--new--></p>"); }; test.serial( "HTMLRewriter: handles comment async handler", commentAsyncHandlerMacro, (rw, comments) => rw.on("p", { comments }) ); const commentClassHandlerMacro: Macro< [(rw: HTMLRewriter, h: { comments: (c: Comment) => void }) => HTMLRewriter] > = async (t, func) => { class Handler { constructor(private content: string) {} // noinspection JSUnusedGlobalSymbols comments(comment: Comment) { comment.text = this.content; } } const res = func(new HTMLRewriter(), new Handler("new")).transform( new Response("<p><!--test--></p>") ); t.is(await res.text(), "<p><!--new--></p>"); }; test( "HTMLRewriter: handles comment class handler", commentClassHandlerMacro, (rw, handler) => rw.on("p", handler) ); // endregion: comments // region: text const textMutationsInput = "<p>t</p>"; // Single character will be single chunk const textMutationsExpected = { beforeAfter: [ "<p>", "&lt;span&gt;before&lt;/span&gt;", "<span>before html</span>", "t", "<span>after html</span>", "&lt;span&gt;after&lt;/span&gt;", "</p>", ].join(""), replace: "<p>&lt;span&gt;replace&lt;/span&gt;</p>", replaceHtml: "<p><span>replace</span></p>", remove: "<p></p>", }; const textPropertiesMacro: Macro< [(rw: HTMLRewriter, text: (text: TextChunk) => void) => HTMLRewriter] > = async (t, func) => { t.plan(6); const res = func(new HTMLRewriter(), (text) => { // This handler should get called twice, once with lastInTextNode true t.false(text.removed); if (text.lastInTextNode) { t.pass(); t.is(text.text, ""); } else { t.is(text.text, "t"); } }).transform(new Response("<p>t</p>")); t.is(await res.text(), "<p>t</p>"); }; test("HTMLRewriter: handles text properties", textPropertiesMacro, (rw, text) => rw.on("p", { text }) ); test( "HTMLRewriter: handles text mutations", mutationsMacro, (rw, text) => rw.on("p", { text }), textMutationsInput, textMutationsExpected ); const textAsyncHandlerMacro: Macro< [(rw: HTMLRewriter, text: (t: TextChunk) => Promise<void>) => HTMLRewriter] > = async (t, func) => { const res = func(new HTMLRewriter(), async (text) => { if (text.text === "t") { await setTimeout(50); text.after(" new"); } }).transform(new Response("<p>t</p>")); t.is(await res.text(), "<p>t new</p>"); }; test.serial( "HTMLRewriter: handles text async handler", textAsyncHandlerMacro, (rw, text) => rw.on("p", { text }) ); const textClassHandlerMacro: Macro< [ ( rw: HTMLRewriter, handler: { text: (text: TextChunk) => void } ) => HTMLRewriter ] > = async (t, func) => { class Handler { constructor(private content: string) {} text(text: TextChunk) { if (text.text === "t") text.after(this.content); } } const res = func(new HTMLRewriter(), new Handler(" new")).transform( new Response("<p>t</p>") ); t.is(await res.text(), "<p>t new</p>"); }; test( "HTMLRewriter: handles text class handler", textClassHandlerMacro, (rw, handler) => rw.on("p", handler) ); // endregion: text test("HTMLRewriter: handles multiple element handlers", async (t) => { const res = new HTMLRewriter() .on("h1", { element(element) { element.setInnerContent("new h1"); }, }) .on("h2", { element(element) { element.setInnerContent("new h2"); }, }) .on("p", { element(element) { element.setInnerContent("new p"); }, }) .transform(new Response("<h1>old h1</h1><h2>old h2</h2><p>old p</p>")); t.is(await res.text(), "<h1>new h1</h1><h2>new h2</h2><p>new p</p>"); }); // endregion: ELEMENT HANDLERS // region: DOCUMENT HANDLERS // region: doctype const doctypeInput = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"></html>'; test("HTMLRewriter: handles document doctype properties", async (t) => { t.plan(4); const res = new HTMLRewriter() .onDocument({ doctype(doctype) { t.is(doctype.name, "html"); t.is(doctype.publicId, "-//W3C//DTD HTML 4.01//EN"); t.is(doctype.systemId, "http://www.w3.org/TR/html4/strict.dtd"); }, }) .transform(new Response(doctypeInput)); t.is(await res.text(), doctypeInput); }); test.serial( "HTMLRewriter: handles document doctype async handler", async (t) => { const res = new HTMLRewriter() .onDocument({ async doctype(doctype) { await setTimeout(50); t.is(doctype.name, "html"); }, }) .transform(new Response(doctypeInput)); t.is(await res.text(), doctypeInput); } ); test("HTMLRewriter: handles document doctype class handler", async (t) => { class Handler { constructor(private content: string) {} // noinspection JSUnusedGlobalSymbols doctype(doctype: Doctype) { t.is(doctype.name, "html"); t.is(this.content, "new"); } } const res = new HTMLRewriter() .onDocument(new Handler("new")) .transform(new Response(doctypeInput)); t.is(await res.text(), doctypeInput); }); // endregion: doctype // region: comments test( "HTMLRewriter: handles document comment properties", commentPropertiesMacro, (rw, comments) => rw.onDocument({ comments }) ); test( "HTMLRewriter: handles document comment mutations", mutationsMacro, (rw, comments) => rw.onDocument({ comments }), commentsMutationsInput, commentsMutationsExpected ); test.serial( "HTMLRewriter: handles document comment async handler", commentAsyncHandlerMacro, (rw, comments) => rw.onDocument({ comments }) ); test( "HTMLRewriter: handles document comment class handler", commentClassHandlerMacro, (rw, handler) => rw.onDocument(handler) ); // endregion: comments // region: text test( "HTMLRewriter: handles document text properties", textPropertiesMacro, (rw, text) => rw.onDocument({ text }) ); test( "HTMLRewriter: handles document text mutations", mutationsMacro, (rw, text) => rw.onDocument({ text }), textMutationsInput, textMutationsExpected ); test.serial( "HTMLRewriter: handles document text async handler", textAsyncHandlerMacro, (rw, text) => rw.onDocument({ text }) ); test( "HTMLRewriter: handles document text class handler", textClassHandlerMacro, (rw, handler) => rw.onDocument(handler) ); // endregion: text // region: end test("HTMLRewriter: handles document end specific mutations", async (t) => { // append const res = new HTMLRewriter() .onDocument({ end(end) { end.append("<span>append</span>"); end.append("<span>append html</span>", { html: true }); }, }) .transform(new Response("<p>test</p>")); t.is( await res.text(), [ "<p>", "test", "</p>", "&lt;span&gt;append&lt;/span&gt;", "<span>append html</span>", ].join("") ); }); test.serial("HTMLRewriter: handles document end async handler", async (t) => { const res = new HTMLRewriter() .onDocument({ async end(end) { await setTimeout(50); end.append("<span>append html</span>", { html: true }); }, }) .transform(new Response("<p>test</p>")); t.is(await res.text(), "<p>test</p><span>append html</span>"); }); test("HTMLRewriter: handles document end class handler", async (t) => { class Handler { constructor(private content: string) {} // noinspection JSUnusedGlobalSymbols end(end: DocumentEnd) { end.append(this.content, { html: true }); } } const res = new HTMLRewriter() .onDocument(new Handler("<span>append html</span>")) .transform(new Response("<p>test</p>")); t.is(await res.text(), "<p>test</p><span>append html</span>"); }); // endregion: end // endregion: DOCUMENT HANDLERS // region: HTMLRewriter MISC // region: responses test("HTMLRewriter: handles streaming responses", async (t) => { const inputStream = new ReadableStream({ async start(controller) { const chunks = [ '<html lang="en">', "<bo", "dy>", "<p>", "te", "st", "</p></body>", "</html>", ]; for (const chunk of chunks) { controller.enqueue(encoder.encode(chunk)); await setTimeout(50); } controller.close(); }, }); t.plan(8); // 6 for text handler + 2 at the end const expectedTextChunks = ["te", "st", ""]; const res = new HTMLRewriter() .on("p", { text(text) { t.is(text.text, expectedTextChunks.shift()); t.is(text.lastInTextNode, text.text === ""); }, }) .transform(new Response(inputStream)); const decoder = new TextDecoder(); const chunks: string[] = []; assert(res.body); for await (const chunk of res.body) { chunks.push(decoder.decode(chunk)); } t.true(chunks.length >= 2); t.is(chunks.join(""), '<html lang="en"><body><p>test</p></body></html>'); }); test.serial( "HTMLRewriter: handles ArrayBuffer and ArrayBufferView chunks", async (t) => { t.plan(3); const inputStream = new ReadableStream({ start(controller) { const buffer = encoder.encode("<p>").buffer; let array = encoder.encode("test"); const view1 = new Uint16Array( array.buffer, array.byteOffset, array.byteLength / Uint16Array.BYTES_PER_ELEMENT ); array = encoder.encode("</p>"); const view2 = new DataView( array.buffer, array.byteOffset, array.byteLength ); controller.enqueue(buffer); controller.enqueue(view1); controller.enqueue(view2); controller.close(); }, }); const freed = recordFree(t); const res = new HTMLRewriter() .on("p", { text(text) { if (text.text) t.is(text.text, "test"); }, }) .transform(new Response(inputStream)); t.is(await res.text(), "<p>test</p>"); t.true(freed.freed); } ); test.serial("HTMLRewriter: throws on string chunks", async (t) => { const freed = recordFree(t); const inputStream = new ReadableStream({ start(controller) { controller.enqueue("I'm a string"); controller.close(); }, }); const res = new HTMLRewriter().transform(new Response(inputStream)); await t.throwsAsync(res.text(), { instanceOf: TypeError, message: "This TransformStream is being used as a byte stream, " + "but received a string on its writable side. " + "If you wish to write a string, you'll probably want to " + "explicitly UTF-8-encode it with TextEncoder.", }); t.true(freed.freed); }); test.serial( "HTMLRewriter: throws on non-ArrayBuffer/ArrayBufferView chunks", async (t) => { const freed = recordFree(t); const inputStream = new ReadableStream({ start(controller) { controller.enqueue(42); controller.close(); }, }); const res = new HTMLRewriter().transform(new Response(inputStream)); await t.throwsAsync(res.text(), { instanceOf: TypeError, message: "This TransformStream is being used as a byte stream, " + "but received an object of non-ArrayBuffer/ArrayBufferView " + "type on its writable side.", }); t.true(freed.freed); } ); test("HTMLRewriter: handles empty response", async (t) => { // Shouldn't call BaseHTMLRewriter.write, just BaseHTMLRewriter.end const res = new HTMLRewriter() .onDocument({ end(end) { end.append("end"); }, }) .transform(new Response()); // Workers don't run the end() handler on null responses t.is(await res.text(), ""); }); test("HTMLRewriter: handles empty string response", async (t) => { const res = new HTMLRewriter() .onDocument({ end(end) { end.append("end"); }, }) .transform(new Response("")); t.is(await res.text(), "end"); }); test("HTNLRewriter: doesn't transform response until needed", async (t) => { const chunks: string[] = []; const res = new HTMLRewriter() .on("p", { text(text) { if (text.text) chunks.push(text.text); }, }) .transform(new Response("<p>1</p><p>2</p><p>3</p>")); await setTimeout(50); t.deepEqual(chunks, []); await res.arrayBuffer(); t.deepEqual(chunks, ["1", "2", "3"]); }); test("HTMLRewriter: copies response status and headers", async (t) => { const res = new HTMLRewriter().transform( new Response("<p>test</p>", { status: 404, headers: { "X-Message": "test" }, }) ); t.is(res.headers.get("X-Message"), "test"); t.is(res.status, 404); t.is(await res.text(), "<p>test</p>"); }); // endregion: responses test.serial("HTMLRewriter: rethrows error thrown in handler", async (t) => { const freed = recordFree(t); const res = new HTMLRewriter() .on("p", { element() { throw new Error("Whoops!"); }, }) .transform(new Response("<p>test</p>")); await t.throwsAsync(res.text(), { message: "Whoops!" }); await setTimeout(); t.true(freed.freed); }); test.serial("HTMLRewriter: rethrows error thrown in end handler", async (t) => { const freed = recordFree(t); const res = new HTMLRewriter() .onDocument({ end() { throw new Error("Whoops!"); }, }) .transform(new Response("<p>test</p>")); await t.throwsAsync(res.text(), { message: "Whoops!" }); await setTimeout(); t.true(freed.freed); }); test("HTMLRewriter: can use same rewriter multiple times", async (t) => { const rw = new HTMLRewriter().on("p", { element(element) { element.setInnerContent("new"); }, }); for (let i = 0; i < 3; i++) { const res = rw.transform(new Response(`<p>old ${i}</p>`)); t.is(await res.text(), "<p>new</p>"); } }); test("HTMLRewriter: handles concurrent rewriters with sync handlers", async (t) => { const rewriter = (i: number) => new HTMLRewriter() .on("p", { element(element) { element.setInnerContent(`new ${i}`); }, }) .transform(new Response(`<p>old ${i}</p>`)); const res1 = rewriter(1); const res2 = rewriter(2); t.is(await res1.text(), "<p>new 1</p>"); t.is(await res2.text(), "<p>new 2</p>"); const res3 = rewriter(3); const res4 = rewriter(4); const texts = await Promise.all([res3.text(), res4.text()]); t.deepEqual(texts, ["<p>new 3</p>", "<p>new 4</p>"]); }); test.serial( "HTMLRewriter: handles concurrent rewriters with async handlers", async (t) => { // Note this test requires the "safe" HTMLRewriter, see comments in // src/modules/rewriter.ts for more details const rewriter = (i: number) => new HTMLRewriter() .on("p", { async element(element) { await setTimeout(50); element.setInnerContent(`new ${i}`); }, }) .transform(new Response(`<p>old ${i}</p>`)); const res1 = rewriter(1); const res2 = rewriter(2); t.is(await res1.text(), "<p>new 1</p>"); t.is(await res2.text(), "<p>new 2</p>"); const res3 = rewriter(3); const res4 = rewriter(4); const texts = await Promise.all([res3.text(), res4.text()]); t.deepEqual(texts, ["<p>new 3</p>", "<p>new 4</p>"]); } ); test.serial("HTMLRewriter: handles async handlers in sandbox", async (t) => { const mf = useMiniflareWithHandler({ HTMLRewriterPlugin }, {}, (globals) => { return new globals.HTMLRewriter() .on("p", { async element(element: Element) { await new Promise((resolve) => globals.setTimeout(resolve, 50)); element.append(" append"); }, }) .transform(new globals.Response("<p>test</p>")); }); const res = await mf.dispatchFetch("http://localhost"); t.is(await res.text(), "<p>test append</p>"); }); test("HTMLRewriter: strips Content-Length header from transformed response", async (t) => { const res = new HTMLRewriter() .on("p", { element(element) { element.setInnerContent("very long new text"); }, }) .transform( new Response(`<p>old</p>`, { headers: { "Content-Type": "text/html", "Content-Length": "10", }, }) ); t.is(res.headers.get("Content-Type"), "text/html"); t.false(res.headers.has("Content-Length")); t.is(await res.text(), "<p>very long new text</p>"); }); test("HTMLRewriter: hides implementation details", (t) => { const rewriter = new HTMLRewriter(); t.deepEqual(getObjectProperties(rewriter), ["on", "onDocument", "transform"]); }); // endregion: HTMLRewriter MISC // region: SELECTORS const selectorMacro: Macro< [selector: string, input: string, expected: string] > = async (t, selector, input, expected) => { const res = new HTMLRewriter() .on(selector, { element(element) { element.setInnerContent("new"); }, }) .transform(new Response(input)); t.is(await res.text(), expected); }; selectorMacro.title = (providedTitle) => `HTMLRewriter: handles ${providedTitle} selector`; test("*", selectorMacro, "*", "<h1>1</h1><p>2</p>", "<h1>new</h1><p>new</p>"); test("E", selectorMacro, "p", "<h1>1</h1><p>2</p>", "<h1>1</h1><p>new</p>"); test( "E:nth-child(n)", selectorMacro, "p:nth-child(2)", "<div><p>1</p><p>2</p><p>3</p></div>", "<div><p>1</p><p>new</p><p>3</p></div>" ); test( "E:first-child", selectorMacro, "p:first-child", "<div><p>1</p><p>2</p><p>3</p></div>", "<div><p>new</p><p>2</p><p>3</p></div>" ); test( "E:nth-of-type(n)", selectorMacro, "p:nth-of-type(2)", "<div><p>1</p><h1>2</h1><p>3</p><h1>4</h1><p>5</p></div>", "<div><p>1</p><h1>2</h1><p>new</p><h1>4</h1><p>5</p></div>" ); test( "E:first-of-type", selectorMacro, "p:first-of-type", "<div><h1>1</h1><p>2</p><p>3</p></div>", "<div><h1>1</h1><p>new</p><p>3</p></div>" ); test( "E:not(s)", selectorMacro, "p:not(:first-child)", "<div><p>1</p><p>2</p><p>3</p></div>", "<div><p>1</p><p>new</p><p>new</p></div>" ); test( "E.class", selectorMacro, "p.red", '<p class="red">1</p><p>2</p>', '<p class="red">new</p><p>2</p>' ); test( "E#id", selectorMacro, "h1#header", '<h1 id="header">1</h1><h1>2</h1>', '<h1 id="header">new</h1><h1>2</h1>' ); test( "E[attr]", selectorMacro, "p[data-test]", "<p data-test>1</p><p>2</p>", "<p data-test>new</p><p>2</p>" ); test( 'E[attr="value"]', selectorMacro, 'p[data-test="one"]', '<p data-test="one">1</p><p data-test="two">2</p>', '<p data-test="one">new</p><p data-test="two">2</p>' ); test( 'E[attr="value" i]', selectorMacro, 'p[data-test="one" i]', '<p data-test="one">1</p><p data-test="OnE">2</p><p data-test="two">3</p>', '<p data-test="one">new</p><p data-test="OnE">new</p><p data-test="two">3</p>' ); test( 'E[attr="value" s]', selectorMacro, 'p[data-test="one" s]', '<p data-test="one">1</p><p data-test="OnE">2</p><p data-test="two">3</p>', '<p data-test="one">new</p><p data-test="OnE">2</p><p data-test="two">3</p>' ); test( 'E[attr~="value"]', selectorMacro, 'p[data-test~="two"]', '<p data-test="one two three">1</p><p data-test="one two">2</p><p data-test="one">3</p>', '<p data-test="one two three">new</p><p data-test="one two">new</p><p data-test="one">3</p>' ); test( 'E[attr^="value"]', selectorMacro, 'p[data-test^="a"]', '<p data-test="a1">1</p><p data-test="a2">2</p><p data-test="b1">3</p>', '<p data-test="a1">new</p><p data-test="a2">new</p><p data-test="b1">3</p>' ); test( 'E[attr$="value"]', selectorMacro, 'p[data-test$="1"]', '<p data-test="a1">1</p><p data-test="a2">2</p><p data-test="b1">3</p>', '<p data-test="a1">new</p><p data-test="a2">2</p><p data-test="b1">new</p>' ); test( 'E[attr*="value"]', selectorMacro, 'p[data-test*="b"]', '<p data-test="abc">1</p><p data-test="ab">2</p><p data-test="a">3</p>', '<p data-test="abc">new</p><p data-test="ab">new</p><p data-test="a">3</p>' ); test( 'E[attr|="value"]', selectorMacro, 'p[data-test|="a"]', '<p data-test="a">1</p><p data-test="a-1">2</p><p data-test="a2">3</p>', '<p data-test="a">new</p><p data-test="a-1">new</p><p data-test="a2">3</p>' ); test( "E F", selectorMacro, "div span", "<div><h1><span>1</span></h1><span>2</span><b>3</b></div>", "<div><h1><span>new</span></h1><span>new</span><b>3</b></div>" ); test( "E > F", selectorMacro, "div > span", "<div><h1><span>1</span></h1><span>2</span><b>3</b></div>", "<div><h1><span>1</span></h1><span>new</span><b>3</b></div>" ); test.serial("HTMLRewriter: throws error on unsupported selector", async (t) => { const freed = recordFree(t); const res = new HTMLRewriter() .on("p:last-child", { element(element) { element.setInnerContent("new"); }, }) .transform(new Response("<p>old</p>")); // Cannot use t.throwsAsync here as promise rejects with string not error type try { await res.text(); t.fail(); } catch (e) { t.is(e, "Unsupported pseudo-class or pseudo-element in selector."); } t.true(freed.freed); }); // endregion: SELECTORS
the_stack
import { Color, RGBA, HSLA, HSVA } from '../../src/common/color'; describe('Color', () => { test('isLighterColor', () => { const color1 = new Color(new HSLA(60, 1, 0.5, 1)); const color2 = new Color(new HSLA(0, 0, 0.753, 1)); expect(color1.isLighterThan(color2)).toBeTruthy(); // Abyss theme expect(Color.fromHex('#770811').isLighterThan(Color.fromHex('#000c18'))).toBeTruthy(); }); test('getLighterColor', () => { const color1 = new Color(new HSLA(60, 1, 0.5, 1)); const color2 = new Color(new HSLA(0, 0, 0.753, 1)); expect(color1.hsla).toEqual(Color.getLighterColor(color1, color2).hsla); expect(new HSLA(0, 0, 0.916, 1)).toEqual(Color.getLighterColor(color2, color1).hsla); expect(new HSLA(0, 0, 0.851, 1)).toEqual(Color.getLighterColor(color2, color1, 0.3).hsla); expect(new HSLA(0, 0, 0.981, 1)).toEqual(Color.getLighterColor(color2, color1, 0.7).hsla); expect(new HSLA(0, 0, 1, 1)).toEqual(Color.getLighterColor(color2, color1, 1).hsla); }); test('isDarkerColor', () => { const color1 = new Color(new HSLA(60, 1, 0.5, 1)); const color2 = new Color(new HSLA(0, 0, 0.753, 1)); expect(color2.isDarkerThan(color1)).toBeTruthy(); }); test('getDarkerColor', () => { const color1 = new Color(new HSLA(60, 1, 0.5, 1)); const color2 = new Color(new HSLA(0, 0, 0.753, 1)); expect(color2.hsla).toEqual(Color.getDarkerColor(color2, color1).hsla); expect(new HSLA(60, 1, 0.392, 1)).toEqual(Color.getDarkerColor(color1, color2).hsla); expect(new HSLA(60, 1, 0.435, 1)).toEqual(Color.getDarkerColor(color1, color2, 0.3).hsla); expect(new HSLA(60, 1, 0.349, 1)).toEqual(Color.getDarkerColor(color1, color2, 0.7).hsla); expect(new HSLA(60, 1, 0.284, 1)).toEqual(Color.getDarkerColor(color1, color2, 1).hsla); // Abyss theme expect(new HSLA(355, 0.874, 0.157, 1)).toEqual( Color.getDarkerColor(Color.fromHex('#770811'), Color.fromHex('#000c18'), 0.4).hsla, ); }); test('luminance', () => { expect(0).toEqual(new Color(new RGBA(0, 0, 0, 1)).getRelativeLuminance()); expect(1).toEqual(new Color(new RGBA(255, 255, 255, 1)).getRelativeLuminance()); expect(0.2126).toEqual(new Color(new RGBA(255, 0, 0, 1)).getRelativeLuminance()); expect(0.7152).toEqual(new Color(new RGBA(0, 255, 0, 1)).getRelativeLuminance()); expect(0.0722).toEqual(new Color(new RGBA(0, 0, 255, 1)).getRelativeLuminance()); expect(0.9278).toEqual(new Color(new RGBA(255, 255, 0, 1)).getRelativeLuminance()); expect(0.7874).toEqual(new Color(new RGBA(0, 255, 255, 1)).getRelativeLuminance()); expect(0.2848).toEqual(new Color(new RGBA(255, 0, 255, 1)).getRelativeLuminance()); expect(0.5271).toEqual(new Color(new RGBA(192, 192, 192, 1)).getRelativeLuminance()); expect(0.2159).toEqual(new Color(new RGBA(128, 128, 128, 1)).getRelativeLuminance()); expect(0.0459).toEqual(new Color(new RGBA(128, 0, 0, 1)).getRelativeLuminance()); expect(0.2003).toEqual(new Color(new RGBA(128, 128, 0, 1)).getRelativeLuminance()); expect(0.1544).toEqual(new Color(new RGBA(0, 128, 0, 1)).getRelativeLuminance()); expect(0.0615).toEqual(new Color(new RGBA(128, 0, 128, 1)).getRelativeLuminance()); expect(0.17).toEqual(new Color(new RGBA(0, 128, 128, 1)).getRelativeLuminance()); expect(0.0156).toEqual(new Color(new RGBA(0, 0, 128, 1)).getRelativeLuminance()); }); test('blending', () => { expect(new Color(new RGBA(0, 0, 0, 0)).blend(new Color(new RGBA(243, 34, 43)))).toEqual( new Color(new RGBA(243, 34, 43)), ); expect(new Color(new RGBA(255, 255, 255)).blend(new Color(new RGBA(243, 34, 43)))).toEqual( new Color(new RGBA(255, 255, 255)), ); expect(new Color(new RGBA(122, 122, 122, 0.7)).blend(new Color(new RGBA(243, 34, 43)))).toEqual( new Color(new RGBA(158, 95, 98)), ); expect(new Color(new RGBA(0, 0, 0, 0.58)).blend(new Color(new RGBA(255, 255, 255, 0.33)))).toEqual( new Color(new RGBA(49, 49, 49, 0.719)), ); }); describe('HSLA', () => { test('HSLA.toRGBA', () => { expect(HSLA.toRGBA(new HSLA(0, 0, 0, 0))).toEqual(new RGBA(0, 0, 0, 0)); expect(HSLA.toRGBA(new HSLA(0, 0, 0, 1))).toEqual(new RGBA(0, 0, 0, 1)); expect(HSLA.toRGBA(new HSLA(0, 0, 1, 1))).toEqual(new RGBA(255, 255, 255, 1)); expect(HSLA.toRGBA(new HSLA(0, 1, 0.5, 1))).toEqual(new RGBA(255, 0, 0, 1)); expect(HSLA.toRGBA(new HSLA(120, 1, 0.5, 1))).toEqual(new RGBA(0, 255, 0, 1)); expect(HSLA.toRGBA(new HSLA(240, 1, 0.5, 1))).toEqual(new RGBA(0, 0, 255, 1)); expect(HSLA.toRGBA(new HSLA(60, 1, 0.5, 1))).toEqual(new RGBA(255, 255, 0, 1)); expect(HSLA.toRGBA(new HSLA(180, 1, 0.5, 1))).toEqual(new RGBA(0, 255, 255, 1)); expect(HSLA.toRGBA(new HSLA(300, 1, 0.5, 1))).toEqual(new RGBA(255, 0, 255, 1)); expect(HSLA.toRGBA(new HSLA(0, 0, 0.753, 1))).toEqual(new RGBA(192, 192, 192, 1)); expect(HSLA.toRGBA(new HSLA(0, 0, 0.502, 1))).toEqual(new RGBA(128, 128, 128, 1)); expect(HSLA.toRGBA(new HSLA(0, 1, 0.251, 1))).toEqual(new RGBA(128, 0, 0, 1)); expect(HSLA.toRGBA(new HSLA(60, 1, 0.251, 1))).toEqual(new RGBA(128, 128, 0, 1)); expect(HSLA.toRGBA(new HSLA(120, 1, 0.251, 1))).toEqual(new RGBA(0, 128, 0, 1)); expect(HSLA.toRGBA(new HSLA(300, 1, 0.251, 1))).toEqual(new RGBA(128, 0, 128, 1)); expect(HSLA.toRGBA(new HSLA(180, 1, 0.251, 1))).toEqual(new RGBA(0, 128, 128, 1)); expect(HSLA.toRGBA(new HSLA(240, 1, 0.251, 1))).toEqual(new RGBA(0, 0, 128, 1)); }); test('HSLA.fromRGBA', () => { expect(HSLA.fromRGBA(new RGBA(0, 0, 0, 0))).toEqual(new HSLA(0, 0, 0, 0)); expect(HSLA.fromRGBA(new RGBA(0, 0, 0, 1))).toEqual(new HSLA(0, 0, 0, 1)); expect(HSLA.fromRGBA(new RGBA(255, 255, 255, 1))).toEqual(new HSLA(0, 0, 1, 1)); expect(HSLA.fromRGBA(new RGBA(255, 0, 0, 1))).toEqual(new HSLA(0, 1, 0.5, 1)); expect(HSLA.fromRGBA(new RGBA(0, 255, 0, 1))).toEqual(new HSLA(120, 1, 0.5, 1)); expect(HSLA.fromRGBA(new RGBA(0, 0, 255, 1))).toEqual(new HSLA(240, 1, 0.5, 1)); expect(HSLA.fromRGBA(new RGBA(255, 255, 0, 1))).toEqual(new HSLA(60, 1, 0.5, 1)); expect(HSLA.fromRGBA(new RGBA(0, 255, 255, 1))).toEqual(new HSLA(180, 1, 0.5, 1)); expect(HSLA.fromRGBA(new RGBA(255, 0, 255, 1))).toEqual(new HSLA(300, 1, 0.5, 1)); expect(HSLA.fromRGBA(new RGBA(192, 192, 192, 1))).toEqual(new HSLA(0, 0, 0.753, 1)); expect(HSLA.fromRGBA(new RGBA(128, 128, 128, 1))).toEqual(new HSLA(0, 0, 0.502, 1)); expect(HSLA.fromRGBA(new RGBA(128, 0, 0, 1))).toEqual(new HSLA(0, 1, 0.251, 1)); expect(HSLA.fromRGBA(new RGBA(128, 128, 0, 1))).toEqual(new HSLA(60, 1, 0.251, 1)); expect(HSLA.fromRGBA(new RGBA(0, 128, 0, 1))).toEqual(new HSLA(120, 1, 0.251, 1)); expect(HSLA.fromRGBA(new RGBA(128, 0, 128, 1))).toEqual(new HSLA(300, 1, 0.251, 1)); expect(HSLA.fromRGBA(new RGBA(0, 128, 128, 1))).toEqual(new HSLA(180, 1, 0.251, 1)); expect(HSLA.fromRGBA(new RGBA(0, 0, 128, 1))).toEqual(new HSLA(240, 1, 0.251, 1)); }); }); describe('HSVA', () => { test('HSVA.toRGBA', () => { expect(HSVA.toRGBA(new HSVA(0, 0, 0, 0))).toEqual(new RGBA(0, 0, 0, 0)); expect(HSVA.toRGBA(new HSVA(0, 0, 0, 1))).toEqual(new RGBA(0, 0, 0, 1)); expect(HSVA.toRGBA(new HSVA(0, 0, 1, 1))).toEqual(new RGBA(255, 255, 255, 1)); expect(HSVA.toRGBA(new HSVA(0, 1, 1, 1))).toEqual(new RGBA(255, 0, 0, 1)); expect(HSVA.toRGBA(new HSVA(120, 1, 1, 1))).toEqual(new RGBA(0, 255, 0, 1)); expect(HSVA.toRGBA(new HSVA(240, 1, 1, 1))).toEqual(new RGBA(0, 0, 255, 1)); expect(HSVA.toRGBA(new HSVA(60, 1, 1, 1))).toEqual(new RGBA(255, 255, 0, 1)); expect(HSVA.toRGBA(new HSVA(180, 1, 1, 1))).toEqual(new RGBA(0, 255, 255, 1)); expect(HSVA.toRGBA(new HSVA(300, 1, 1, 1))).toEqual(new RGBA(255, 0, 255, 1)); expect(HSVA.toRGBA(new HSVA(0, 0, 0.753, 1))).toEqual(new RGBA(192, 192, 192, 1)); expect(HSVA.toRGBA(new HSVA(0, 0, 0.502, 1))).toEqual(new RGBA(128, 128, 128, 1)); expect(HSVA.toRGBA(new HSVA(0, 1, 0.502, 1))).toEqual(new RGBA(128, 0, 0, 1)); expect(HSVA.toRGBA(new HSVA(60, 1, 0.502, 1))).toEqual(new RGBA(128, 128, 0, 1)); expect(HSVA.toRGBA(new HSVA(120, 1, 0.502, 1))).toEqual(new RGBA(0, 128, 0, 1)); expect(HSVA.toRGBA(new HSVA(300, 1, 0.502, 1))).toEqual(new RGBA(128, 0, 128, 1)); expect(HSVA.toRGBA(new HSVA(180, 1, 0.502, 1))).toEqual(new RGBA(0, 128, 128, 1)); expect(HSVA.toRGBA(new HSVA(240, 1, 0.502, 1))).toEqual(new RGBA(0, 0, 128, 1)); expect(HSVA.toRGBA(new HSVA(360, 0, 0, 0))).toEqual(new RGBA(0, 0, 0, 0)); expect(HSVA.toRGBA(new HSVA(360, 0, 0, 1))).toEqual(new RGBA(0, 0, 0, 1)); expect(HSVA.toRGBA(new HSVA(360, 0, 1, 1))).toEqual(new RGBA(255, 255, 255, 1)); expect(HSVA.toRGBA(new HSVA(360, 0, 0.753, 1))).toEqual(new RGBA(192, 192, 192, 1)); expect(HSVA.toRGBA(new HSVA(360, 0, 0.502, 1))).toEqual(new RGBA(128, 128, 128, 1)); }); test('HSVA.fromRGBA', () => { expect(HSVA.fromRGBA(new RGBA(0, 0, 0, 0))).toEqual(new HSVA(0, 0, 0, 0)); expect(HSVA.fromRGBA(new RGBA(0, 0, 0, 1))).toEqual(new HSVA(0, 0, 0, 1)); expect(HSVA.fromRGBA(new RGBA(255, 255, 255, 1))).toEqual(new HSVA(0, 0, 1, 1)); expect(HSVA.fromRGBA(new RGBA(255, 0, 0, 1))).toEqual(new HSVA(0, 1, 1, 1)); expect(HSVA.fromRGBA(new RGBA(0, 255, 0, 1))).toEqual(new HSVA(120, 1, 1, 1)); expect(HSVA.fromRGBA(new RGBA(0, 0, 255, 1))).toEqual(new HSVA(240, 1, 1, 1)); expect(HSVA.fromRGBA(new RGBA(255, 255, 0, 1))).toEqual(new HSVA(60, 1, 1, 1)); expect(HSVA.fromRGBA(new RGBA(0, 255, 255, 1))).toEqual(new HSVA(180, 1, 1, 1)); expect(HSVA.fromRGBA(new RGBA(255, 0, 255, 1))).toEqual(new HSVA(300, 1, 1, 1)); expect(HSVA.fromRGBA(new RGBA(192, 192, 192, 1))).toEqual(new HSVA(0, 0, 0.753, 1)); expect(HSVA.fromRGBA(new RGBA(128, 128, 128, 1))).toEqual(new HSVA(0, 0, 0.502, 1)); expect(HSVA.fromRGBA(new RGBA(128, 0, 0, 1))).toEqual(new HSVA(0, 1, 0.502, 1)); expect(HSVA.fromRGBA(new RGBA(128, 128, 0, 1))).toEqual(new HSVA(60, 1, 0.502, 1)); expect(HSVA.fromRGBA(new RGBA(0, 128, 0, 1))).toEqual(new HSVA(120, 1, 0.502, 1)); expect(HSVA.fromRGBA(new RGBA(128, 0, 128, 1))).toEqual(new HSVA(300, 1, 0.502, 1)); expect(HSVA.fromRGBA(new RGBA(0, 128, 128, 1))).toEqual(new HSVA(180, 1, 0.502, 1)); expect(HSVA.fromRGBA(new RGBA(0, 0, 128, 1))).toEqual(new HSVA(240, 1, 0.502, 1)); }); test('Keep hue value when saturation is 0', () => { expect(HSVA.toRGBA(new HSVA(10, 0, 0, 0))).toEqual(HSVA.toRGBA(new HSVA(20, 0, 0, 0))); expect(new Color(new HSVA(10, 0, 0, 0)).rgba).toEqual(new Color(new HSVA(20, 0, 0, 0)).rgba); expect(new Color(new HSVA(10, 0, 0, 0)).hsva).not.toEqual(new Color(new HSVA(20, 0, 0, 0)).hsva); }); test('bug#36240', () => { expect(HSVA.fromRGBA(new RGBA(92, 106, 196, 1))).toEqual(new HSVA(232, 0.531, 0.769, 1)); expect(HSVA.toRGBA(HSVA.fromRGBA(new RGBA(92, 106, 196, 1)))).toEqual(new RGBA(92, 106, 196, 1)); }); }); describe('Format', () => { describe('CSS', () => { test('parseHex', () => { // invalid expect(Color.Format.CSS.parseHex('')).toEqual(null); expect(Color.Format.CSS.parseHex('#')).toEqual(null); expect(Color.Format.CSS.parseHex('#0102030')).toEqual(null); // somewhat valid expect(Color.Format.CSS.parseHex('#FFFFG0')!.rgba).toEqual(new RGBA(255, 255, 0, 1)); expect(Color.Format.CSS.parseHex('#FFFFg0')!.rgba).toEqual(new RGBA(255, 255, 0, 1)); expect(Color.Format.CSS.parseHex('#-FFF00')!.rgba).toEqual(new RGBA(15, 255, 0, 1)); // valid expect(Color.Format.CSS.parseHex('#000000')!.rgba).toEqual(new RGBA(0, 0, 0, 1)); expect(Color.Format.CSS.parseHex('#FFFFFF')!.rgba).toEqual(new RGBA(255, 255, 255, 1)); expect(Color.Format.CSS.parseHex('#FF0000')!.rgba).toEqual(new RGBA(255, 0, 0, 1)); expect(Color.Format.CSS.parseHex('#00FF00')!.rgba).toEqual(new RGBA(0, 255, 0, 1)); expect(Color.Format.CSS.parseHex('#0000FF')!.rgba).toEqual(new RGBA(0, 0, 255, 1)); expect(Color.Format.CSS.parseHex('#FFFF00')!.rgba).toEqual(new RGBA(255, 255, 0, 1)); expect(Color.Format.CSS.parseHex('#00FFFF')!.rgba).toEqual(new RGBA(0, 255, 255, 1)); expect(Color.Format.CSS.parseHex('#FF00FF')!.rgba).toEqual(new RGBA(255, 0, 255, 1)); expect(Color.Format.CSS.parseHex('#C0C0C0')!.rgba).toEqual(new RGBA(192, 192, 192, 1)); expect(Color.Format.CSS.parseHex('#808080')!.rgba).toEqual(new RGBA(128, 128, 128, 1)); expect(Color.Format.CSS.parseHex('#800000')!.rgba).toEqual(new RGBA(128, 0, 0, 1)); expect(Color.Format.CSS.parseHex('#808000')!.rgba).toEqual(new RGBA(128, 128, 0, 1)); expect(Color.Format.CSS.parseHex('#008000')!.rgba).toEqual(new RGBA(0, 128, 0, 1)); expect(Color.Format.CSS.parseHex('#800080')!.rgba).toEqual(new RGBA(128, 0, 128, 1)); expect(Color.Format.CSS.parseHex('#008080')!.rgba).toEqual(new RGBA(0, 128, 128, 1)); expect(Color.Format.CSS.parseHex('#000080')!.rgba).toEqual(new RGBA(0, 0, 128, 1)); expect(Color.Format.CSS.parseHex('#010203')!.rgba).toEqual(new RGBA(1, 2, 3, 1)); expect(Color.Format.CSS.parseHex('#040506')!.rgba).toEqual(new RGBA(4, 5, 6, 1)); expect(Color.Format.CSS.parseHex('#070809')!.rgba).toEqual(new RGBA(7, 8, 9, 1)); expect(Color.Format.CSS.parseHex('#0a0A0a')!.rgba).toEqual(new RGBA(10, 10, 10, 1)); expect(Color.Format.CSS.parseHex('#0b0B0b')!.rgba).toEqual(new RGBA(11, 11, 11, 1)); expect(Color.Format.CSS.parseHex('#0c0C0c')!.rgba).toEqual(new RGBA(12, 12, 12, 1)); expect(Color.Format.CSS.parseHex('#0d0D0d')!.rgba).toEqual(new RGBA(13, 13, 13, 1)); expect(Color.Format.CSS.parseHex('#0e0E0e')!.rgba).toEqual(new RGBA(14, 14, 14, 1)); expect(Color.Format.CSS.parseHex('#0f0F0f')!.rgba).toEqual(new RGBA(15, 15, 15, 1)); expect(Color.Format.CSS.parseHex('#a0A0a0')!.rgba).toEqual(new RGBA(160, 160, 160, 1)); expect(Color.Format.CSS.parseHex('#CFA')!.rgba).toEqual(new RGBA(204, 255, 170, 1)); expect(Color.Format.CSS.parseHex('#CFA8')!.rgba).toEqual(new RGBA(204, 255, 170, 0.533)); }); }); }); });
the_stack
import { commands, Disposable, window, ExtensionContext } from "vscode"; import { MusicControlManager, displayMusicTimeMetricsMarkdownDashboard } from "./music/MusicControlManager"; import { launchMusicAnalytics, launchWebUrl } from "./Util"; import { PlaylistItem, PlayerName, PlayerDevice, playSpotifyDevice } from "cody-music"; import { SocialShareManager } from "./social/SocialShareManager"; import { connectSlackWorkspace, disconnectSlack, disconnectSlackAuth } from "./managers/SlackManager"; import { showGenreSelections, showMoodSelections } from "./selector/RecTypeSelectorManager"; import { showSortPlaylistMenu } from "./selector/SortPlaylistSelectorManager"; import { showDeviceSelectorMenu } from "./selector/SpotifyDeviceSelectorManager"; import { MusicCommandUtil } from "./music/MusicCommandUtil"; import { showSearchInput } from "./selector/SearchSelectorManager"; import { MusicStateManager } from "./music/MusicStateManager"; import { connectSpotify, disconnectSpotify, switchSpotifyAccount } from "./managers/SpotifyManager"; import { displayReadmeIfNotExists } from "./managers/FileManager"; import { launchLogin, showLogInMenuOptions, showSignUpMenuOptions } from "./managers/UserStatusManager"; import { MusicTimeWebviewSidebar } from "./sidebar/MusicTimeWebviewSidebar"; import { SPOTIFY_LIKED_SONGS_PLAYLIST_ID } from "./app/utils/view_constants"; import { fetchTracksForLikedSongs, fetchTracksForPlaylist, followSpotifyPlaylist, getAlbumForTrack, getBestActiveDevice, getCurrentRecommendations, getMixedAudioFeatureRecs, getRecommendations, getTrackRecommendations, populateSpotifyDevices, refreshRecommendations, removeTrackFromPlaylist, requiresSpotifyAccess, updateSelectedPlaylistId, updateSelectedTabView, updateSort, } from "./managers/PlaylistDataManager"; import { launchTrackPlayer, playSelectedItem } from "./managers/PlaylistControlManager"; import { vscode_mt_issues_url } from "./Constants"; /** * add the commands to vscode.... */ export function createCommands( ctx: ExtensionContext ): { dispose: () => void; } { let cmds = []; const controller: MusicControlManager = MusicControlManager.getInstance(); // DISPLAY README CMD cmds.push( commands.registerCommand("musictime.launchReadme", () => { displayReadmeIfNotExists(true /*override*/); }) ); // DISPLAY REPORT DASHBOARD CMD cmds.push( commands.registerCommand("musictime.displayDashboard", () => { displayMusicTimeMetricsMarkdownDashboard(); }) ); // PLAY NEXT CMD cmds.push( commands.registerCommand("musictime.next", () => { controller.nextSong(); }) ); // PLAY PREV CMD cmds.push( commands.registerCommand("musictime.previous", () => { controller.previousSong(); }) ); // PLAY CMD cmds.push( commands.registerCommand("musictime.play", async () => { controller.playSong(1); }) ); // MUTE CMD cmds.push( commands.registerCommand("musictime.mute", async () => { controller.setMuteOn(); }) ); // UNMUTE CMD cmds.push( commands.registerCommand("musictime.unMute", async () => { controller.setMuteOff(); }) ); // REMOVE TRACK CMD cmds.push( commands.registerCommand("musictime.removeTrack", async (p: PlaylistItem) => { removeTrackFromPlaylist(p); }) ); // SHARE CMD cmds.push( commands.registerCommand("musictime.shareTrack", (node: PlaylistItem) => { SocialShareManager.getInstance().showMenu(node.id, node.name, false); }) ); // SEARCH CMD cmds.push( commands.registerCommand("musictime.searchTracks", () => { // show the search input popup showSearchInput(); }) ); // PAUSE CMD cmds.push( commands.registerCommand("musictime.pause", () => { controller.pauseSong(); }) ); // LIKE CMD cmds.push( commands.registerCommand("musictime.like", (track: any) => { controller.setLiked(track, true); }) ); // UNLIKE CMD cmds.push( commands.registerCommand("musictime.unlike", (track: any) => { controller.setLiked(track, false); }) ); cmds.push( commands.registerCommand("musictime.shuffleOff", () => { controller.setShuffleOff(); }) ); cmds.push( commands.registerCommand("musictime.shuffleOn", () => { controller.setShuffleOn(); }) ); cmds.push( commands.registerCommand("musictime.muteOn", () => { controller.setMuteOn(); }) ); cmds.push( commands.registerCommand("musictime.muteOff", () => { controller.setMuteOff(); }) ); // REPEAT OFF CMD cmds.push( commands.registerCommand("musictime.repeatOn", () => { controller.setRepeatOnOff(true); }) ); cmds.push( commands.registerCommand("musictime.repeatTrack", () => { controller.setRepeatTrackOn(); }) ); cmds.push( commands.registerCommand("musictime.repeatPlaylist", () => { controller.setRepeatPlaylistOn(); }) ); // REPEAT ON OFF CMD cmds.push( commands.registerCommand("musictime.repeatOff", () => { controller.setRepeatOnOff(false); }) ); // SHOW MENU CMD cmds.push( commands.registerCommand("musictime.menu", () => { controller.showMenu(); }) ); // FOLLOW PLAYLIST CMD cmds.push( commands.registerCommand("musictime.follow", (p: PlaylistItem) => { followSpotifyPlaylist(p); }) ); // DISPLAY CURRENT SONG CMD cmds.push( commands.registerCommand("musictime.currentSong", () => { launchTrackPlayer(); }) ); cmds.push( commands.registerCommand("musictime.songTitleRefresh", async () => { const device = getBestActiveDevice(); if (!device) { await populateSpotifyDevices(false); } MusicStateManager.getInstance().fetchTrack(); }) ); // SWITCH SPOTIFY cmds.push( commands.registerCommand("musictime.switchSpotifyAccount", async () => { switchSpotifyAccount(); }) ); // CONNECT SPOTIFY CMD cmds.push( commands.registerCommand("musictime.connectSpotify", async () => { connectSpotify(); }) ); // CONNECT SLACK cmds.push( commands.registerCommand("musictime.connectSlack", () => { connectSlackWorkspace(); }) ); // DISCONNECT SPOTIFY cmds.push( commands.registerCommand("musictime.disconnectSpotify", () => { disconnectSpotify(); }) ); // DISCONNECT SLACK cmds.push( commands.registerCommand("musictime.disconnectSlack", (item: any) => { if (!item) { disconnectSlack(); } else { disconnectSlackAuth(item.value); } }) ); // this should only be attached to the refresh button cmds.push( commands.registerCommand("musictime.refreshDeviceInfo", async () => { if (!requiresSpotifyAccess()) { await populateSpotifyDevices(false); } }) ); cmds.push( commands.registerCommand("musictime.launchSpotify", () => { launchTrackPlayer(PlayerName.SpotifyWeb); }) ); cmds.push( commands.registerCommand("musictime.launchAnalytics", () => { launchMusicAnalytics(); }) ); const deviceSelectTransferCmd = commands.registerCommand("musictime.transferToDevice", async (d: PlayerDevice) => { // transfer to this device window.showInformationMessage(`Connected to ${d.name}`); await MusicCommandUtil.getInstance().runSpotifyCommand(playSpotifyDevice, [d.id]); setTimeout(() => { // refresh the tree, no need to refresh playlists commands.executeCommand("musictime.refreshDeviceInfo"); }, 3000); }); cmds.push(deviceSelectTransferCmd); const genreRecListCmd = commands.registerCommand("musictime.songGenreSelector", () => { showGenreSelections(); }); cmds.push(genreRecListCmd); const categoryRecListCmd = commands.registerCommand("musictime.songMoodSelector", () => { showMoodSelections(); }); cmds.push(categoryRecListCmd); const deviceSelectorCmd = commands.registerCommand("musictime.deviceSelector", () => { showDeviceSelectorMenu(); }); cmds.push(deviceSelectorCmd); // UPDATE RECOMMENDATIONS CMD cmds.push( commands.registerCommand("musictime.updateRecommendations", (args) => { // there's always at least 3 args const label = args[0]; const likedSongSeedLimit = args[1]; const seed_genres = args[2]; const features = args.length > 3 ? args[3] : {}; getRecommendations(label, likedSongSeedLimit, seed_genres, features); }) ); cmds.push( commands.registerCommand("musictime.refreshRecommendations", (args) => { refreshRecommendations(); }) ); // signup button click cmds.push( commands.registerCommand("musictime.signUpAccount", async () => { showSignUpMenuOptions(); }) ); cmds.push( commands.registerCommand("musictime.logInAccount", async () => { showLogInMenuOptions(); }) ); // login button click cmds.push( commands.registerCommand("musictime.googleLogin", async () => { launchLogin("google", true); }) ); cmds.push( commands.registerCommand("musictime.githubLogin", async () => { launchLogin("github", true); }) ); cmds.push( commands.registerCommand("musictime.emailSignup", async () => { launchLogin("software", false); }) ); cmds.push( commands.registerCommand("musictime.emailLogin", async () => { launchLogin("software", true); }) ); // WEB VIEW PROVIDER const mtWebviewSidebar: MusicTimeWebviewSidebar = new MusicTimeWebviewSidebar(ctx.extensionUri); cmds.push( window.registerWebviewViewProvider("musictime.webView", mtWebviewSidebar, { webviewOptions: { retainContextWhenHidden: true, }, }) ); cmds.push( commands.registerCommand("musictime.refreshMusicTimeView", (tab_view: undefined, playlist_id: undefined, loading = false) => { mtWebviewSidebar.refresh(tab_view, playlist_id, loading); }) ); cmds.push( commands.registerCommand("musictime.submitAnIssue", () => { launchWebUrl(vscode_mt_issues_url); }) ); // SORT TITLE COMMAND cmds.push( commands.registerCommand("musictime.sortIcon", () => { showSortPlaylistMenu(); }) ); cmds.push( commands.registerCommand("musictime.sortAlphabetically", async () => { updateSort(true); }) ); cmds.push( commands.registerCommand("musictime.sortToOriginal", async () => { updateSort(false); }) ); cmds.push( commands.registerCommand("musictime.getTrackRecommendations", async (node: PlaylistItem) => { getTrackRecommendations(node); }) ); cmds.push( commands.registerCommand("musictime.getAudioFeatureRecommendations", async (features: any) => { getMixedAudioFeatureRecs(features); }) ); cmds.push( commands.registerCommand("musictime.showAlbum", async (item: PlaylistItem) => { getAlbumForTrack(item); }) ); cmds.push( commands.registerCommand("musictime.fetchPlaylistTracks", async (playlist_id) => { if (playlist_id === SPOTIFY_LIKED_SONGS_PLAYLIST_ID) { fetchTracksForLikedSongs(); } else { fetchTracksForPlaylist(playlist_id); } }) ); cmds.push( commands.registerCommand("musictime.updateSelectedPlaylist", async (playlist_id) => { updateSelectedPlaylistId(playlist_id); }) ); cmds.push( commands.registerCommand("musictime.playTrack", async (item: PlaylistItem) => { updateSelectedPlaylistId(item["playlist_id"]); playSelectedItem(item); }) ); cmds.push( commands.registerCommand("musictime.updateSelectedTabView", async (tabView: string) => { updateSelectedTabView(tabView); if (tabView === "recommendations") { // populate familiar recs, but don't refreshMusicTimeView // as the final logic will make that call await getCurrentRecommendations(); } else { // refresh the music time view commands.executeCommand("musictime.refreshMusicTimeView"); } }) ); cmds.push( commands.registerCommand("musictime.installCodeTime", async (item: PlaylistItem) => { launchWebUrl("vscode:extension/softwaredotcom.swdc-vscode"); }) ); cmds.push( commands.registerCommand("musictime.displaySidebar", () => { // logic to open the sidebar (need to figure out how to reveal the sidebar webview) commands.executeCommand("workbench.view.extension.music-time-sidebar"); }) ); cmds.push( commands.registerCommand("musictime.addToPlaylist", async (p: PlaylistItem) => { controller.addToPlaylistMenu(p); }) ); return Disposable.from(...cmds); }
the_stack
import StateMachine from '../src/app/app' import LifecycleLogger from './helpers/lifecycle_logger' //------------------------------------------------------------------------------------------------- test('lifecycle events occur in correct order', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ transitions: [ { name: 'step', from: 'none', to: 'complete' } ], methods: { onBeforeTransition: logger, onBeforeStep: logger, onLeaveState: logger, onLeaveNone: logger, onLeaveComplete: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onEnterComplete: logger, onAfterTransition: logger, onAfterStep: logger } }); expect(fsm.state).toBe('none'); fsm.step(); expect(fsm.state).toBe('complete'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onEnterState', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onEnterComplete', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onAfterTransition', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onAfterStep', transition: 'step', from: 'none', to: 'complete', current: 'complete' } ]); }); test('lifecycle events occur in correct order - for same state transition', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ transitions: [ { name: 'noop', from: 'none', to: 'none' } ], methods: { onBeforeTransition: logger, onBeforeNoop: logger, onLeaveState: logger, onLeaveNone: logger, onLeaveComplete: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onEnterComplete: logger, onAfterTransition: logger, onAfterNoop: logger } }); expect(fsm.state).toBe('none'); fsm.noop(); expect(fsm.state).toBe('none'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onBeforeNoop', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onAfterTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onAfterNoop', transition: 'noop', from: 'none', to: 'none', current: 'none' } ]); }); test('lifecycle events using shortcut names', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ init: 'solid', transitions: [ { name: 'melt', from: 'solid', to: 'liquid' }, { name: 'freeze', from: 'liquid', to: 'solid' }, { name: 'vaporize', from: 'liquid', to: 'gas' }, { name: 'condense', from: 'gas', to: 'liquid' } ], methods: { onNone: logger, onSolid: logger, onLiquid: logger, onGas: logger, onInit: logger, onMelt: logger, onFreeze: logger, onVaporize: logger, onCondense: logger } }); expect(fsm.state).toBe('solid'); expect(logger.log).toEqual([ { event: "onSolid", transition: "init", from: "none", to: "solid", current: "solid" }, { event: "onInit", transition: "init", from: "none", to: "solid", current: "solid" } ]); logger.clear(); fsm.melt(); expect(fsm.state).toBe('liquid'); expect(logger.log).toEqual([ { event: "onLiquid", transition: "melt", from: "solid", to: "liquid", current: "liquid" }, { event: "onMelt", transition: "melt", from: "solid", to: "liquid", current: "liquid" } ]); }); test('lifecycle events with dash or underscore are camelized', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ init: 'has-dash', transitions: [ { name: 'do-with-dash', from: 'has-dash', to: 'has_underscore' }, { name: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized' }, { name: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash' } ], methods: { onBeforeTransition: logger, onBeforeInit: logger, onBeforeDoWithDash: logger, onBeforeDoWithUnderscore: logger, onBeforeDoAlreadyCamelized: logger, onLeaveState: logger, onLeaveNone: logger, onLeaveHasDash: logger, onLeaveHasUnderscore: logger, onLeaveAlreadyCamelized: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onEnterHasDash: logger, onEnterHasUnderscore: logger, onEnterAlreadyCamelized: logger, onAfterTransition: logger, onAfterInit: logger, onAfterDoWithDash: logger, onAfterDoWithUnderscore: logger, onAfterDoAlreadyCamelized: logger } }); expect(fsm.state).toBe('has-dash'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'init', from: 'none', to: 'has-dash', current: 'none' }, { event: 'onBeforeInit', transition: 'init', from: 'none', to: 'has-dash', current: 'none' }, { event: 'onLeaveState', transition: 'init', from: 'none', to: 'has-dash', current: 'none' }, { event: 'onLeaveNone', transition: 'init', from: 'none', to: 'has-dash', current: 'none' }, { event: 'onTransition', transition: 'init', from: 'none', to: 'has-dash', current: 'none' }, { event: 'onEnterState', transition: 'init', from: 'none', to: 'has-dash', current: 'has-dash' }, { event: 'onEnterHasDash', transition: 'init', from: 'none', to: 'has-dash', current: 'has-dash' }, { event: 'onAfterTransition', transition: 'init', from: 'none', to: 'has-dash', current: 'has-dash' }, { event: 'onAfterInit', transition: 'init', from: 'none', to: 'has-dash', current: 'has-dash' } ]); logger.clear(); fsm.doWithDash(); expect(fsm.state).toBe('has_underscore'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has-dash' }, { event: 'onBeforeDoWithDash', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has-dash' }, { event: 'onLeaveState', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has-dash' }, { event: 'onLeaveHasDash', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has-dash' }, { event: 'onTransition', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has-dash' }, { event: 'onEnterState', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has_underscore' }, { event: 'onEnterHasUnderscore', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has_underscore' }, { event: 'onAfterTransition', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has_underscore' }, { event: 'onAfterDoWithDash', transition: 'do-with-dash', from: 'has-dash', to: 'has_underscore', current: 'has_underscore' } ]); logger.clear(); fsm.doWithUnderscore(); expect(fsm.state).toBe('alreadyCamelized'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'has_underscore' }, { event: 'onBeforeDoWithUnderscore', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'has_underscore' }, { event: 'onLeaveState', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'has_underscore' }, { event: 'onLeaveHasUnderscore', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'has_underscore' }, { event: 'onTransition', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'has_underscore' }, { event: 'onEnterState', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'alreadyCamelized' }, { event: 'onEnterAlreadyCamelized', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'alreadyCamelized' }, { event: 'onAfterTransition', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'alreadyCamelized' }, { event: 'onAfterDoWithUnderscore', transition: 'do_with_underscore', from: 'has_underscore', to: 'alreadyCamelized', current: 'alreadyCamelized' } ]); logger.clear(); fsm.doAlreadyCamelized(); expect(fsm.state).toBe('has-dash'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'alreadyCamelized' }, { event: 'onBeforeDoAlreadyCamelized', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'alreadyCamelized' }, { event: 'onLeaveState', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'alreadyCamelized' }, { event: 'onLeaveAlreadyCamelized', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'alreadyCamelized' }, { event: 'onTransition', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'alreadyCamelized' }, { event: 'onEnterState', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'has-dash' }, { event: 'onEnterHasDash', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'has-dash' }, { event: 'onAfterTransition', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'has-dash' }, { event: 'onAfterDoAlreadyCamelized', transition: 'doAlreadyCamelized', from: 'alreadyCamelized', to: 'has-dash', current: 'has-dash' } ]); }); test('lifecycle event names that are all uppercase are camelized', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ init: 'FIRST', transitions: [ { name: 'GO', from: 'FIRST', to: 'SECOND_STATE' }, { name: 'DO_IT', from: 'SECOND_STATE', to: 'FIRST' } ], methods: { onBeforeGo: logger, onBeforeDoIt: logger, onLeaveFirst: logger, onLeaveSecondState: logger, onEnterFirst: logger, onEnterSecondState: logger, onAfterGo: logger, onAfterDoIt: logger } }); expect(fsm.state).toBe('FIRST'); expect(logger.log).toEqual([ { event: 'onEnterFirst', transition: 'init', from: 'none', to: 'FIRST', current: 'FIRST' }, ]) logger.clear() fsm.go() expect(fsm.state).toBe('SECOND_STATE'); expect(logger.log).toEqual([ { event: 'onBeforeGo', transition: 'GO', from: 'FIRST', to: 'SECOND_STATE', current: 'FIRST' }, { event: 'onLeaveFirst', transition: 'GO', from: 'FIRST', to: 'SECOND_STATE', current: 'FIRST' }, { event: 'onEnterSecondState', transition: 'GO', from: 'FIRST', to: 'SECOND_STATE', current: 'SECOND_STATE' }, { event: 'onAfterGo', transition: 'GO', from: 'FIRST', to: 'SECOND_STATE', current: 'SECOND_STATE' } ]) logger.clear(); fsm.doIt(); expect(fsm.state).toBe('FIRST'); expect(logger.log).toEqual([ { event: 'onBeforeDoIt', transition: 'DO_IT', from: 'SECOND_STATE', to: 'FIRST', current: 'SECOND_STATE' }, { event: 'onLeaveSecondState', transition: 'DO_IT', from: 'SECOND_STATE', to: 'FIRST', current: 'SECOND_STATE' }, { event: 'onEnterFirst', transition: 'DO_IT', from: 'SECOND_STATE', to: 'FIRST', current: 'FIRST' }, { event: 'onAfterDoIt', transition: 'DO_IT', from: 'SECOND_STATE', to: 'FIRST', current: 'FIRST' } ]); }); test('lifecycle events receive arbitrary transition arguments', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ transitions: [ { name: 'init', from: 'none', to: 'A' }, { name: 'step', from: 'A', to: 'B' } ], methods: { onBeforeTransition: logger, onBeforeInit: logger, onBeforeStep: logger, onLeaveState: logger, onLeaveNone: logger, onLeaveA: logger, onLeaveB: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onEnterA: logger, onEnterB: logger, onAfterTransition: logger, onAfterInit: logger, onAfterStep: logger } }); expect(fsm.state).toBe('none'); expect(logger.log).toEqual([]); fsm.init(); expect(fsm.state).toBe('A'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onBeforeInit', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onLeaveState', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onLeaveNone', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onTransition', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onEnterState', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onEnterA', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onAfterTransition', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onAfterInit', transition: 'init', from: 'none', to: 'A', current: 'A' } ]); logger.clear(); fsm.step('with', 4, 'more', 'arguments'); expect(fsm.state).toBe('B'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'A', to: 'B', current: 'A', args: [ 'with', 4, 'more', 'arguments' ] }, { event: 'onBeforeStep', transition: 'step', from: 'A', to: 'B', current: 'A', args: [ 'with', 4, 'more', 'arguments' ] }, { event: 'onLeaveState', transition: 'step', from: 'A', to: 'B', current: 'A', args: [ 'with', 4, 'more', 'arguments' ] }, { event: 'onLeaveA', transition: 'step', from: 'A', to: 'B', current: 'A', args: [ 'with', 4, 'more', 'arguments' ] }, { event: 'onTransition', transition: 'step', from: 'A', to: 'B', current: 'A', args: [ 'with', 4, 'more', 'arguments' ] }, { event: 'onEnterState', transition: 'step', from: 'A', to: 'B', current: 'B', args: [ 'with', 4, 'more', 'arguments' ] }, { event: 'onEnterB', transition: 'step', from: 'A', to: 'B', current: 'B', args: [ 'with', 4, 'more', 'arguments' ] }, { event: 'onAfterTransition', transition: 'step', from: 'A', to: 'B', current: 'B', args: [ 'with', 4, 'more', 'arguments' ] }, { event: 'onAfterStep', transition: 'step', from: 'A', to: 'B', current: 'B', args: [ 'with', 4, 'more', 'arguments' ] } ]); }); test('lifecycle events are cancelable', () => { const FSM = StateMachine.factory({ transitions: [ { name: 'step', from: 'none', to: 'complete' } ], data: function(cancel) { return { cancel: cancel, // @ts-ignore logger: new LifecycleLogger(), } }, methods: { // @ts-ignore onBeforeTransition: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onBeforeStep: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onEnterState: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onEnterNone: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onEnterComplete: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onTransition: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onLeaveState: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onLeaveNone: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onLeaveComplete: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onAfterTransition: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel }, // @ts-ignore onAfterStep: function(lifecycle) { this.logger(lifecycle); return lifecycle.event !== this.cancel } }, }); const cancelledBeforeTransition = new FSM('onBeforeTransition'); const cancelledBeforeStep = new FSM('onBeforeStep'); const cancelledLeaveState = new FSM('onLeaveState'); const cancelledLeaveNone = new FSM('onLeaveNone'); const cancelledTransition = new FSM('onTransition'); const cancelledEnterState = new FSM('onEnterState'); const cancelledEnterComplete = new FSM('onEnterComplete'); const cancelledAfterTransition = new FSM('onAfterTransition'); const cancelledAfterStep = new FSM('onAfterStep'); expect(cancelledBeforeTransition.state).toBe('none'); expect(cancelledBeforeStep.state).toBe('none'); expect(cancelledLeaveState.state).toBe('none'); expect(cancelledLeaveNone.state).toBe('none'); expect(cancelledTransition.state).toBe('none'); expect(cancelledEnterState.state).toBe('none'); expect(cancelledEnterComplete.state).toBe('none'); expect(cancelledAfterTransition.state).toBe('none'); expect(cancelledAfterStep.state).toBe('none'); cancelledBeforeTransition.step(); cancelledBeforeStep.step(); cancelledLeaveState.step(); cancelledLeaveNone.step(); cancelledTransition.step(); cancelledEnterState.step(); cancelledEnterComplete.step(); cancelledAfterTransition.step(); cancelledAfterStep.step(); expect(cancelledBeforeTransition.state).toBe('none'); expect(cancelledBeforeStep.state).toBe('none'); expect(cancelledLeaveState.state).toBe('none'); expect(cancelledLeaveNone.state).toBe('none'); expect(cancelledTransition.state).toBe('none'); expect(cancelledEnterState.state).toBe('complete'); expect(cancelledEnterComplete.state).toBe('complete'); expect(cancelledAfterTransition.state).toBe('complete'); expect(cancelledAfterStep.state).toBe('complete'); expect(cancelledBeforeTransition.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' } ]); expect(cancelledBeforeStep.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' } ]); expect(cancelledLeaveState.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none' } ]); expect(cancelledLeaveNone.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none' } ]); expect(cancelledTransition.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' } ]); expect(cancelledEnterState.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onEnterState', transition: 'step', from: 'none', to: 'complete', current: 'complete' } ]); expect(cancelledEnterComplete.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onEnterState', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onEnterComplete', transition: 'step', from: 'none', to: 'complete', current: 'complete' } ]); expect(cancelledAfterTransition.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onEnterState', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onEnterComplete', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onAfterTransition', transition: 'step', from: 'none', to: 'complete', current: 'complete' } ]); expect(cancelledAfterStep.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onTransition', transition: 'step', from: 'none', to: 'complete', current: 'none' }, { event: 'onEnterState', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onEnterComplete', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onAfterTransition', transition: 'step', from: 'none', to: 'complete', current: 'complete' }, { event: 'onAfterStep', transition: 'step', from: 'none', to: 'complete', current: 'complete' } ]); }); test('lifecycle events can be deferred using a promise', async () => { // @ts-ignore const logger = new LifecycleLogger(); const start = Date.now(); const pause = function(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('resolved') }, ms); }); }; const fsm = new StateMachine({ transitions: [ { name: 'step', from: 'none', to: 'complete' } ], methods: { // @ts-ignore onBeforeTransition: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onBeforeStep: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onEnterState: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onEnterNone: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onEnterComplete: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, // @ts-ignore onTransition: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, // @ts-ignore onLeaveState: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onLeaveNone: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onLeaveComplete: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onAfterTransition: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onAfterStep: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); } } }); function done(answer) { const duration = Date.now() - start; expect(fsm.state).toBe('complete'); expect(duration > 600).toBe(true); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onTransition', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onEnterState', transition: 'step', from: 'none', to: 'complete', current: 'complete', args: [ 'additional', 'arguments' ] }, { event: 'onEnterComplete', transition: 'step', from: 'none', to: 'complete', current: 'complete', args: [ 'additional', 'arguments' ] }, { event: 'onAfterTransition', transition: 'step', from: 'none', to: 'complete', current: 'complete', args: [ 'additional', 'arguments' ] }, { event: 'onAfterStep', transition: 'step', from: 'none', to: 'complete', current: 'complete', args: [ 'additional', 'arguments' ] }, ]) expect(answer).toBe('resolved'); } await fsm.step('additional', 'arguments') .then(done); }); test('lifecycle events can be cancelled using a promise', async () => { // @ts-ignore const logger = new LifecycleLogger(); const start = Date.now(); const pause = function(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('resolved') }, ms); }); }; const cancel = function(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { reject('rejected'); }, ms); }); }; const fsm = new StateMachine({ transitions: [ { name: 'step', from: 'none', to: 'complete' } ], methods: { // @ts-ignore onBeforeTransition: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onBeforeStep: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onEnterState: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onEnterNone: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, onEnterComplete: function(lifecycle, a, b) { logger(lifecycle, a, b); return pause(100); }, // @ts-ignore onTransition: function(lifecycle, a, b) { logger(lifecycle, a, b); return cancel(100); }, // @ts-ignore onLeaveState: function(lifecycle, a, b) { logger(lifecycle, a, b); }, onLeaveNone: function(lifecycle, a, b) { logger(lifecycle, a, b); }, onLeaveComplete: function(lifecycle, a, b) { logger(lifecycle, a, b); }, onAfterTransition: function(lifecycle, a, b) { logger(lifecycle, a, b); }, onAfterStep: function(lifecycle, a, b) { logger(lifecycle, a, b); } } }); function done(answer) { const duration = Date.now() - start; expect(fsm.state).toBe('none'); expect(duration > 300).toBe(true); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onBeforeStep', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onLeaveState', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onLeaveNone', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] }, { event: 'onTransition', transition: 'step', from: 'none', to: 'complete', current: 'none', args: [ 'additional', 'arguments' ] } ]); expect(answer).toBe('rejected'); } await fsm.step('additional', 'arguments') .then(function() { done('promise was rejected so this should never happen'); }) .catch(done) }); test('transition cannot fire while lifecycle event is in progress', () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'step', from: 'A', to: 'B' }, { name: 'other', from: '*', to: 'X' } ], methods: { onBeforeStep: function(lifecycle) { // @ts-ignore expect(this.can('other')).toBe(false); try { fsm.other(); } catch (e) { expect(e.message).toBe('transition is invalid while previous transition is still in progress'); expect(e.transition).toBe('other'); expect(e.from).toBe('A'); expect(e.to).toBe('X'); expect(e.current).toBe('A'); } }, onAfterStep: function(lifecycle) { // @ts-ignore expect(this.can('other')).toBe(false); try { fsm.other(); } catch (e) { expect(e.message).toBe('transition is invalid while previous transition is still in progress'); expect(e.transition).toBe('other'); expect(e.from).toBe('B'); expect(e.to).toBe('X'); expect(e.current).toBe('B'); } }, onBeforeOther: function(lifecycle) { throw new Error('should never happen'); }, onAfterOther: function(lifecycle) { throw new Error('should never happen'); }, // @ts-ignore onLeaveA: function(lifecycle) { expect(this.can('other')).toBe(false); }, // @ts-ignore onEnterB: function(lifecycle) { expect(this.can('other')).toBe(false); }, onLeaveB: function(lifecycle) { throw new Error('should never happen'); }, onEnterX: function(lifecycle) { throw new Error('should never happen'); }, onLeaveX: function(lifecycle) { throw new Error('should never happen'); } } }); expect(fsm.state).toBe('A'); expect(fsm.can('other')).toBe(true); fsm.step(); expect(fsm.state).toBe('B'); expect(fsm.can('other')).toBe(true); }); test('transition cannot fire while asynchronous lifecycle event is in progress', async () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'step', from: 'A', to: 'B' }, { name: 'other', from: '*', to: 'X' } ], methods: { onBeforeStep: function(lifecycle) { return new Promise((resolve, reject) => { setTimeout(() => { // @ts-ignore expect(this.can('other')).toBe(false); try { fsm.other(); } catch (e) { expect(e.message).toBe('transition is invalid while previous transition is still in progress'); expect(e.transition).toBe('other'); expect(e.from).toBe('A'); expect(e.to).toBe('X'); expect(e.current).toBe('A'); } // @ts-ignore resolve(); }, 200); }); }, onAfterStep: function(lifecycle) { return new Promise((resolve, reject) => { setTimeout(() => { // @ts-ignore expect(this.can('other')).toBe(false); try { fsm.other(); } catch (e) { expect(e.message).toBe('transition is invalid while previous transition is still in progress'); expect(e.transition).toBe('other'); expect(e.from).toBe('B'); expect(e.to).toBe('X'); expect(e.current).toBe('B'); } // @ts-ignore resolve(); setTimeout(done, 0); // HACK - let lifecycle finish before calling done() }, 200); }); }, onBeforeOther: function(lifecycle) { throw new Error('should never happen'); }, onAfterOther: function(lifecycle) { throw new Error('should never happen'); }, // @ts-ignore onLeaveA: function(lifecycle) { expect(this.can('other')).toBe(false); }, // @ts-ignore onEnterB: function(lifecycle) { expect(this.can('other')).toBe(false); }, onLeaveB: function(lifecycle) { throw new Error('should never happen'); }, onEnterX: function(lifecycle) { throw new Error('should never happen'); }, onLeaveX: function(lifecycle) { throw new Error('should never happen'); } } }); expect(fsm.state).toBe('A'); expect(fsm.can('other')).toBe(true); function done() { expect(fsm.state).toBe('B'); expect(fsm.can('other')).toBe(true); } await fsm.step(); // kick off the async behavior }); test('lifecycle events for transitions with multiple :from or :to states', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ init: 'hungry', transitions: [ { name: 'eat', from: 'hungry', to: 'satisfied' }, { name: 'eat', from: 'satisfied', to: 'full' }, { name: 'rest', from: [ 'satisfied', 'full' ], to: 'hungry' } ], methods: { onBeforeTransition: logger, onBeforeEat: logger, onBeforeRest: logger, onLeaveState: logger, onLeaveHungry: logger, onLeaveSatisfied: logger, onLeaveFull: logger, onTransition: logger, onEnterState: logger, onEnterHungry: logger, onEnterSatisfied: logger, onEnterFull: logger, onAfterTransition: logger, onAfterEat: logger, onAfterRest: logger } }); expect(fsm.state).toBe('hungry'); logger.clear(); fsm.eat(); expect(fsm.state).toBe('satisfied'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'hungry' }, { event: 'onBeforeEat', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'hungry' }, { event: 'onLeaveState', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'hungry' }, { event: 'onLeaveHungry', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'hungry' }, { event: 'onTransition', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'hungry' }, { event: 'onEnterState', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'satisfied' }, { event: 'onEnterSatisfied', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'satisfied' }, { event: 'onAfterTransition', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'satisfied' }, { event: 'onAfterEat', transition: 'eat', from: 'hungry', to: 'satisfied', current: 'satisfied' } ]); logger.clear(); fsm.eat(); expect(fsm.state).toBe('full'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'eat', from: 'satisfied', to: 'full', current: 'satisfied' }, { event: 'onBeforeEat', transition: 'eat', from: 'satisfied', to: 'full', current: 'satisfied' }, { event: 'onLeaveState', transition: 'eat', from: 'satisfied', to: 'full', current: 'satisfied' }, { event: 'onLeaveSatisfied', transition: 'eat', from: 'satisfied', to: 'full', current: 'satisfied' }, { event: 'onTransition', transition: 'eat', from: 'satisfied', to: 'full', current: 'satisfied' }, { event: 'onEnterState', transition: 'eat', from: 'satisfied', to: 'full', current: 'full' }, { event: 'onEnterFull', transition: 'eat', from: 'satisfied', to: 'full', current: 'full' }, { event: 'onAfterTransition', transition: 'eat', from: 'satisfied', to: 'full', current: 'full' }, { event: 'onAfterEat', transition: 'eat', from: 'satisfied', to: 'full', current: 'full' } ]); logger.clear(); fsm.rest(); expect(fsm.state).toBe('hungry'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'rest', from: 'full', to: 'hungry', current: 'full' }, { event: 'onBeforeRest', transition: 'rest', from: 'full', to: 'hungry', current: 'full' }, { event: 'onLeaveState', transition: 'rest', from: 'full', to: 'hungry', current: 'full' }, { event: 'onLeaveFull', transition: 'rest', from: 'full', to: 'hungry', current: 'full' }, { event: 'onTransition', transition: 'rest', from: 'full', to: 'hungry', current: 'full' }, { event: 'onEnterState', transition: 'rest', from: 'full', to: 'hungry', current: 'hungry' }, { event: 'onEnterHungry', transition: 'rest', from: 'full', to: 'hungry', current: 'hungry' }, { event: 'onAfterTransition', transition: 'rest', from: 'full', to: 'hungry', current: 'hungry' }, { event: 'onAfterRest', transition: 'rest', from: 'full', to: 'hungry', current: 'hungry' } ]); }); test('lifecycle events for factory generated state machines', () => { const FSM = StateMachine.factory({ transitions: [ { name: 'stepA', from: 'none', to: 'A' }, { name: 'stepB', from: 'none', to: 'B' } ], data: function(name) { return { name: name, // @ts-ignore logger: new LifecycleLogger() } }, methods: { // @ts-ignore onBeforeTransition: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onBeforeStepA: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onBeforeStepB: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onLeaveState: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onLeaveNone: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onLeaveA: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onLeaveB: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onTransition: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onEnterState: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onEnterNone: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onEnterA: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onEnterB: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onAfterTransition: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onAfterStepA: function(lifecycle) { this.logger(lifecycle) }, // @ts-ignore onAfterStepB: function(lifecycle) { this.logger(lifecycle) } } }); const a = new FSM('a'), b = new FSM('b'); expect(a.state).toBe('none'); expect(b.state).toBe('none'); expect(a.logger.log).toEqual([]); expect(b.logger.log).toEqual([]); a.stepA(); b.stepB(); expect(a.state).toBe('A'); expect(b.state).toBe('B'); expect(a.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'stepA', from: 'none', to: 'A', current: 'none' }, { event: 'onBeforeStepA', transition: 'stepA', from: 'none', to: 'A', current: 'none' }, { event: 'onLeaveState', transition: 'stepA', from: 'none', to: 'A', current: 'none' }, { event: 'onLeaveNone', transition: 'stepA', from: 'none', to: 'A', current: 'none' }, { event: 'onTransition', transition: 'stepA', from: 'none', to: 'A', current: 'none' }, { event: 'onEnterState', transition: 'stepA', from: 'none', to: 'A', current: 'A' }, { event: 'onEnterA', transition: 'stepA', from: 'none', to: 'A', current: 'A' }, { event: 'onAfterTransition', transition: 'stepA', from: 'none', to: 'A', current: 'A' }, { event: 'onAfterStepA', transition: 'stepA', from: 'none', to: 'A', current: 'A' } ]); expect(b.logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'stepB', from: 'none', to: 'B', current: 'none' }, { event: 'onBeforeStepB', transition: 'stepB', from: 'none', to: 'B', current: 'none' }, { event: 'onLeaveState', transition: 'stepB', from: 'none', to: 'B', current: 'none' }, { event: 'onLeaveNone', transition: 'stepB', from: 'none', to: 'B', current: 'none' }, { event: 'onTransition', transition: 'stepB', from: 'none', to: 'B', current: 'none' }, { event: 'onEnterState', transition: 'stepB', from: 'none', to: 'B', current: 'B' }, { event: 'onEnterB', transition: 'stepB', from: 'none', to: 'B', current: 'B' }, { event: 'onAfterTransition', transition: 'stepB', from: 'none', to: 'B', current: 'B' }, { event: 'onAfterStepB', transition: 'stepB', from: 'none', to: 'B', current: 'B' } ]); }); test('lifecycle events for custom init transition', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ init: { name: 'boot', from: 'booting', to: 'complete' }, methods: { onBeforeTransition: logger, onBeforeInit: logger, onBeforeBoot: logger, onLeaveState: logger, onLeaveNone: logger, onLeaveBooting: logger, onLeaveComplete: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onEnterBooting: logger, onEnterComplete: logger, onAfterTransition: logger, onAfterInit: logger, onAfterBoot: logger } }); expect(fsm.state).toBe('complete'); expect(fsm.allStates()).toEqual([ 'booting', 'complete' ]); expect(fsm.allTransitions()).toEqual([ 'boot' ]); expect(fsm.transitions()).toEqual([ ]); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'boot', from: 'booting', to: 'complete', current: 'booting' }, { event: 'onBeforeBoot', transition: 'boot', from: 'booting', to: 'complete', current: 'booting' }, { event: 'onLeaveState', transition: 'boot', from: 'booting', to: 'complete', current: 'booting' }, { event: 'onLeaveBooting', transition: 'boot', from: 'booting', to: 'complete', current: 'booting' }, { event: 'onTransition', transition: 'boot', from: 'booting', to: 'complete', current: 'booting' }, { event: 'onEnterState', transition: 'boot', from: 'booting', to: 'complete', current: 'complete' }, { event: 'onEnterComplete', transition: 'boot', from: 'booting', to: 'complete', current: 'complete' }, { event: 'onAfterTransition', transition: 'boot', from: 'booting', to: 'complete', current: 'complete' }, { event: 'onAfterBoot', transition: 'boot', from: 'booting', to: 'complete', current: 'complete' } ]); }); export {}
the_stack
import * as Autosuggest from 'react-autosuggest'; import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Utils, PathRegion, Helpable, TagItem } from './Utils'; import AutoComplete from './AutoComplete'; import * as FontAwesome from 'react-fontawesome'; import Tags from './Tags'; // When suggestion is clicked, Autosuggest needs to populate the input // based on the clicked suggestion. Teach Autosuggest how to calculate the // input value for every given suggestion. const getSuggestionValue = suggestion => suggestion; // Use your imagination to render suggestions. const renderSuggestion = suggestion => <div>{suggestion}</div>; interface PathRegionProps { pos: PathRegion; posUpdate: (reg: PathRegion) => void; posConcat: (reg: PathRegion[], featureId: number) => void; onItemSelect: () => void; onItemDelete: () => void; closeVisible: boolean; reference: string; color: string; } interface PathRegionState { pos: string; posInner: PathRegion; suggestions: string[]; } class PathRegionForm extends React.Component<PathRegionProps, PathRegionState> implements Helpable { constructor(props: PathRegionProps) { super(props); this._posChange = this._posChange.bind(this); this._posUpdate = this._posUpdate.bind(this); this._scaleDown = this._scaleDown.bind(this); this._scaleUp = this._scaleUp.bind(this); this._scaleLeft = this._scaleLeft.bind(this); this._scaleRight = this._scaleRight.bind(this); this._chunkLeft = this._chunkLeft.bind(this); this._chunkRight = this._chunkRight.bind(this); this._tagsUpdate = this._tagsUpdate.bind(this); this._pinnedToggle = this._pinnedToggle.bind(this); // Autosuggest is a controlled component. // This means that you need to provide an input value // and an onChange handler that updates this value (see below). // Suggestions also need to be provided to the Autosuggest, // and they are initially empty because the Autosuggest is closed. this.state = { pos: props.pos.toString(), posInner: props.pos, suggestions: [] }; } _posChange(event: any) { this.setState({ pos: event.target.value }); } _tagsUpdate(newTags: TagItem[]) { let pos = this.props.pos; pos.name = newTags; this.props.posUpdate(pos); } _pinnedToggle() { let pos = this.props.pos; pos.isLocked = !pos.isLocked; this.props.posUpdate(pos); } _posUpdate(event: any) { event.preventDefault(); const pos = Utils.strToRegion(this.state.pos); // console.log(pos, 'PathReg'); const _this = this; if (pos[0] !== null) { // if it is the correct region. pos[0].name = this.state.posInner.name; this.props.posUpdate(pos[0]); } else { fetch( '/api/v2/feature?ref=' + this.props.reference + '&equals=' + this.state.pos.toUpperCase() ) .then(function(response: Response) { return response.json(); }) .then(function(json2: any) { // FIXME() It discards the orient of gene. var pos2; if (Object.prototype.toString.call(json2) === '[object object]') json2[1] = json2; // For Compatible const pos = String(_this.state.pos); if (json2[1].start <= json2[1].stop) { pos2 = new PathRegion( json2[1].path, json2[1].start, json2[1].stop, true, [json2[0]] ); } else { pos2 = new PathRegion( json2[1].path, json2[1].stop, json2[1].start, true, [json2[0]] ); } _this.props.posUpdate(pos2); _this.setState({ pos: pos2.toString() }); }) .catch(function(err: any) { // handle error console.error(err); }); } } _scaleDown(event: any) { this.props.posUpdate(this.state.posInner.scaleDown()); } _scaleUp(event: any) { this.props.posUpdate(this.state.posInner.scaleUp()); } _scaleLeft(event: any) { this.props.posUpdate(this.state.posInner.scaleLeft()); } _scaleRight(event: any) { this.props.posUpdate(this.state.posInner.scaleRight()); } _chunkLeft(event: any) { this.props.posUpdate(this.state.posInner.chunkLeft()); } _chunkRight(event: any) { this.props.posUpdate(this.state.posInner.chunkRight()); } _getSuggestions(value: string) { const _this = this; if (value.length >= 2) { fetch( '/api/v2/feature?ref=' + this.props.reference + '&startsWith=' + value.toUpperCase() ) .then(function(response: Response) { return response.json(); }) .then(function(json: any) { _this.setState({ suggestions: json }); }) .catch(function(err: any) { // handle error console.error(err); }); } } help() { return ( <div> <h3>Path-Inputbox</h3> <p> Put the target coordinate such as (chr:start or chr:start-end) on the input box. </p> </div> ); } link() { return 'path-regionform'; } onChange = (event, { newValue }) => { this.setState({ pos: newValue }); }; // Autosuggest will call this function every time you need to update suggestions. // You already implemented this logic above, so just use it. onSuggestionsFetchRequested = ({ value }) => { this._getSuggestions(value); }; // Autosuggest will call this function every time you need to clear suggestions. onSuggestionsClearRequested = () => { this.setState({ suggestions: [] }); }; componentWillReceiveProps(props: PathRegionProps) { this.setState({ posInner: props.pos, pos: props.pos.toString() }); } render() { const value = this.state.pos; const suggestions = this.state.suggestions; // Autosuggest will pass through all these props to the input. const inputProps = { placeholder: 'Type a genomic region(path:start-stop) or gene name.', value, onChange: this.onChange, style: { width: 350 } }; // Finally, render it! return ( <div className="CurrentPosition" style={{ display: 'flux' }}> <div style={{ display: 'flex' }}> <div style={{ marginRight: 'auto' }}> <Tags suggestions={this.state.suggestions} tags={this.props.pos.name} tagsUpdate={this._tagsUpdate} /> </div> <button className="btn btn-primary" onClick={this.props.onItemSelect}> <FontAwesome name="bullseye" /> </button> {(() => { if (this.props.closeVisible) { return ( <button className="btn btn-danger" onClick={this.props.onItemDelete}> <FontAwesome name="times-circle" /> </button> ); } })()} </div> <form className="commentForm" onSubmit={this._posUpdate}> <div style={{ display: 'flex', marginTop: '3px', marginBottom: '3px' }}> <span style={{ color: this.props.color, transition: 'all .3s ease', marginLeft: '2px' }}> &#x25cf; </span> <AutoComplete value={this.state.pos} onChange={this.onChange} reference={this.props.reference} placeholder="Type a genomic region(path:start-stop) or gene name." width={310} /> {' '} <button className="btn btn-outline-primary" onClick={this._posUpdate} type="submit" title="Submit the region" disabled={this.state.posInner.isLocked}> <FontAwesome name="dot-circle-o" ariaLabel="OK" /> </button> </div> </form> <button className="btn btn-outline-secondary" onClick={this._scaleUp} disabled={this.state.posInner.isLocked} title="Zoom up"> + </button> <button className="btn btn-outline-secondary" onClick={this._scaleDown} disabled={this.state.posInner.isLocked} title="Zoom down"> - </button> <button className="btn btn-outline-secondary" onClick={this._scaleLeft} disabled={this.state.posInner.isLocked} title="Move left"> <FontAwesome name="arrow-left" /> </button> <button className="btn btn-outline-secondary" onClick={this._scaleRight} disabled={this.state.posInner.isLocked} title="Move right"> <FontAwesome name="arrow-right" /> </button> <button className="btn btn-outline-secondary" onClick={this._chunkLeft} disabled={this.state.posInner.isLocked} title="Move left"> <FontAwesome name="align-left" /> </button> <button className="btn btn-outline-secondary" onClick={this._chunkRight} disabled={this.state.posInner.isLocked} title="Move right"> <FontAwesome name="align-right" /> </button> <button className="btn btn-outline-secondary" onClick={() => this.props.posConcat([this.state.posInner], null)} title="Clone region"> <FontAwesome name="clone" /> </button> <button className={`btn ${ this.state.posInner.isLocked ? 'btn-danger' : 'btn-outline-danger' }`} onClick={this._pinnedToggle}> <FontAwesome name="thumb-tack" /> </button> </div> ); } } export default PathRegionForm;
the_stack
import * as _ from 'lodash'; import * as handlebars from 'handlebars'; import * as yaml from '../yaml'; import {logger} from '../logger'; import { Env, $EnvValues, AnyButUndefined, ExtendedCfnDoc, GlobalSection, GlobalSectionNames, MaybeStackFrame, validateTemplateParameter, interpolateHandlebarsString, appendPath } from './index'; const HANDLEBARS_RE = /{{(.*?)}}/; const CFN_SUB_RE = /\${([^!].*?)}/g; const _flatten = <T>(arrs: T[][]): T[] => _.flatten(arrs) const _isPlainMap = (node: any): node is object => _.isObject(node) && !_.get(node, 'is_yaml_tag') && !_.isDate(node) && !_.isRegExp(node) && !_.isFunction(node); /** * Splits an import `!$ string` into dot-delimited chunks. * Dynamic key segments within brackets are included in the preceeding chunk. * * See examples in ../tests/test-visitor.ts under this fn's name. */ export const _parse$includeKeyChunks = (key: string, path: string): string[] => { const keyChunks = []; let remaining = key; let i = 0; let bracketDepth = 0; while (i < remaining.length) { if (remaining[i] === '.' && bracketDepth === 0) { keyChunks.push(remaining.slice(0, i)); remaining = remaining.slice(i + 1); i = 0 } else if (remaining[i] === '[') { bracketDepth++ i++ } else if (remaining[i] === ']') { bracketDepth-- i++ } else { i++ } if (i === remaining.length) { keyChunks.push(remaining); if (bracketDepth > 0) { throw new Error(`Unclosed brackets path=${path} pos=${i} bracketDepth=${bracketDepth} remaining=${remaining}`); } break; } } return keyChunks; } export const mkSubEnv = (env: Env, $envValues: $EnvValues, frame: MaybeStackFrame): Env => { const stackFrame = { location: frame.location || env.Stack[env.Stack.length - 1].location, // tslint:disable-line path: frame.path }; return { GlobalAccumulator: env.GlobalAccumulator, $envValues, Stack: env.Stack.concat([stackFrame]) }; }; const _liftKVPairs = (objects: {key: string, value: any}[]) => _.fromPairs(_.map(objects, ({key, value}) => [key, value])) export const iidyDollarKeywordsAndInternalKeys = [ '$imports', '$defs', '$params', '$location', '$envValues' ]; function lookupInEnv(key: string, path: string, env: Env): AnyButUndefined { if (typeof key !== 'string') { // tslint:disable-line // this is called with the .data attribute of custom yaml tags which might not be // strings. throw new Error(`Invalid lookup key ${JSON.stringify(key)} at ${path}`) } const res = env.$envValues[key]; if (_.isUndefined(res)) { logger.debug(`Could not find "${key}" at ${path}}`, {env}) throw new Error(`Could not find "${key}" at ${path}`); } else { return res; } } export class Visitor { // The functions in this class are stateless - they are only wrapped in a // class so that the functionality can be extended visitYamlTagNode(node: yaml.Tag, path: string, env: Env): AnyButUndefined { if (node instanceof yaml.$include) { return this.visit$include(node, path, env); } else if (node instanceof yaml.$expand) { return this.visit$expand(node, path, env); } else if (node instanceof yaml.$escape) { return this.visit$escape(node, path, env); } else if (node instanceof yaml.$string) { return this.visit$string(node, path, env); } else if (node instanceof yaml.$parseYaml) { return this.visit$parseYaml(node, path, env); } else if (node instanceof yaml.$toJsonString) { return this.visit$toJsonString(node, path, env); } else if (node instanceof yaml.$parseJson) { return this.visit$parseJson(node, path, env); } else if (node instanceof yaml.$if) { return this.visit$if(node, path, env); } else if (node instanceof yaml.$eq) { return this.visit$eq(node, path, env); } else if (node instanceof yaml.$not) { return this.visit$not(node, path, env); } else if (node instanceof yaml.$let) { return this.visit$let(node, path, env); } else if (node instanceof yaml.$map) { return this.visit$map(node, path, env); } else if (node instanceof yaml.$mapValues) { return this.visit$mapValues(node, path, env); } else if (node instanceof yaml.$merge) { return this.visit$merge(node, path, env); } else if (node instanceof yaml.$mergeMap) { return this.visit$mergeMap(node, path, env); } else if (node instanceof yaml.$concat) { return this.visit$concat(node, path, env); } else if (node instanceof yaml.$concatMap) { return this.visit$concatMap(node, path, env); } else if (node instanceof yaml.$mapListToHash) { return this.visit$mapListToHash(node, path, env); } else if (node instanceof yaml.$groupBy) { return this.visit$groupBy(node, path, env); } else if (node instanceof yaml.$fromPairs) { return this.visit$fromPairs(node, path, env); } else if (node instanceof yaml.$split) { return this.visit$split(node, path, env); } else if (node instanceof yaml.$join) { return this.visit$join(node, path, env); } else if (node instanceof yaml.Ref) { return this.visitRef(node, path, env); } else if (node instanceof yaml.GetAtt) { return this.visitGetAtt(node, path, env); } else if (node instanceof yaml.Sub) { return this.visitSub(node, path, env); } else { if (_.isArray(node.data) && node.data.length === 1 && node.data[0] instanceof yaml.Tag) { // unwrap Tags like !ImportValue [!$ someVar] return node.update(this.visitNode(node.data[0], path, env)); } else { return node.update(this.visitNode(node.data, path, env)); } } } visit$escape(node: yaml.$escape, _path: string, _env: Env): AnyButUndefined { return node.data; } visit$expand(node: yaml.$expand, path: string, env: Env): AnyButUndefined { if (!_.isEqual(_.sortBy(_.keys(node.data)), ['params', 'template'])) { // TODO use json schema instead throw new Error(`Invalid arguments to $expand: ${_.sortBy(_.keys(node.data))}`); } else { const {template: templateName, params} = node.data; // TODO remove the need for this cast const template: ExtendedCfnDoc = _.clone(lookupInEnv(templateName, path, env)) as ExtendedCfnDoc; const stackFrame = {location: template.$location, path: appendPath(path, '!$expand')}; const $paramDefaultsEnv = mkSubEnv(env, {...template.$envValues}, stackFrame); const $paramDefaults = _.fromPairs( _.filter( _.map( template.$params, (v) => [ v.Name, this.visitNode(v.Default, appendPath(path, `$params.${v.Name}`), $paramDefaultsEnv)]), ([_k, v]) => !_.isUndefined(v))); const providedParams = this.visitNode(params, appendPath(path, 'params'), env); const mergedParams = _.assign({}, $paramDefaults, providedParams); _.forEach(template.$params, (param) => validateTemplateParameter(param, mergedParams, '!$expand', env)); const subEnv = mkSubEnv(env, {...mergedParams, ...template.$envValues}, stackFrame); delete template.$params; // TODO might also need to delete template.$imports, template.$envValues, and template.$defs return this.visitNode(template, path, subEnv); } } visit$include(node: yaml.$include, path: string, env: Env): AnyButUndefined { const searchChunks = _parse$includeKeyChunks(node.data, path) const lookupRes: any = searchChunks.reduce( // tslint:disable-line:no-any (result0: any, subKey: string, i) => { // tslint:disable-line:no-any const result = this.visitNode(result0, path, env); // calling this.visitNode here fixes issue #75 if (_.isUndefined(result) && i > 0) { throw new Error(`Could not find ${subKey} in ${node.data} at ${path}`); } // the result0 might contain pre-processor constructs that need evaluation before continuing const bracketsMatch = subKey.match(/\[(.*)\] *$/); // dynamic key chunk if (bracketsMatch) { // e.g. !$ foo[bar], foo[bar[baz]], etc. const basekey = subKey.slice(0, bracketsMatch.index); const dynamicKey = bracketsMatch[1].trim(); return this._visit$includeDynamicKey(dynamicKey, basekey, `${dynamicKey} in ${path}`, env, result); } else { const subEnv = i === 0 ? env : mkSubEnv(env, {...result}, {path}); return lookupInEnv(subKey.trim(), `${subKey} in ${path}`, subEnv); } }, undefined); if (_.isUndefined(lookupRes)) { throw new Error(`Could not find ${node.data} at ${path}`); } else { return this.visitNode(lookupRes, path, env); } } _visit$includeDynamicKey(dynamicKey: string, basekey: string, path: string, env: Env, lastResult: any) { const newKeyParts: string[] = []; for (const part of dynamicKey.trim().split('][')) { // this loop enables handling of successive, unnested dynamic keys // e.g. 'obj[key1][key2]'. See the tests in src/test/test-visitor.ts if (Number.isSafeInteger(parseInt(part, 10))) { newKeyParts.push(part) } else { const bracketVal = this.visit$include(new yaml.$include(part), `${path} / ${dynamicKey}`, env); if (typeof bracketVal === 'number') { newKeyParts.push(String(bracketVal)) } else if (typeof bracketVal === 'string') { newKeyParts.push(bracketVal) } else { throw new Error(`Invalid dynamic key value ${bracketVal} for ${dynamicKey} at ${path}`); } } } const newKey = basekey + '.' + newKeyParts.join('.'); const subEnv = _.isUndefined(lastResult) ? env : mkSubEnv(env, {...lastResult}, {path}); return this.visit$include(new yaml.$include(newKey), `${newKey} from ${basekey} in ${path}`, subEnv); } visit$if(node: yaml.$if, path: string, env: Env): AnyButUndefined { if (this.visitNode(node.data.test, path, env)) { return this.visitNode(node.data.then, path, env); } else { return this.visitNode(node.data.else, path, env); } } visit$eq(node: yaml.$eq, path: string, env: Env): AnyButUndefined { return this.visitNode(node.data[0], path, env) == this.visitNode(node.data[1], path, env); } visit$not(node: yaml.$not, path: string, env: Env): AnyButUndefined { const expr = (_.isArray(node.data) && node.data.length === 1) ? node.data[0] : node.data; return !this.visitNode(expr, path, env); } visit$let(node: yaml.$let, path: string, env: Env): AnyButUndefined { const subEnv = mkSubEnv( env, {...env.$envValues, ...this.visitNode(_.omit(node.data, ['in']), path, env)}, {path}); return this.visitNode(node.data.in, path, subEnv); } visit$map(node: yaml.$map, path: string, env: Env): AnyButUndefined { // TODO validate node.data's shape or even better do this during parsing // template: any, items: [...] const {template, items} = node.data // TODO handle nested maps const varName = node.data.var || 'item'; const SENTINEL = {}; const mapped = _.without(_.map(this.visitNode(items, path, env), (item0: any, idx: number) => { // TODO improve stackFrame details const subPath = appendPath(path, idx.toString()); const item = this.visitNode(item0, subPath, env); // visit pre expansion const subEnv = mkSubEnv( env, {...env.$envValues, [varName]: item, [varName + 'Idx']: idx}, {path: subPath}); if (node.data.filter && !this.visitNode(node.data.filter, path, subEnv)) { return SENTINEL; } else { return this.visitNode(template, subPath, subEnv); } }), SENTINEL); return this.visitNode(mapped, path, env); // TODO do we need to visit again like this? } visit$mapValues(node: yaml.$mapValues, path: string, env: Env): AnyButUndefined { const input = this.visitNode(node.data.items, path, env); const keys = this.visitNode(_.keys(input), path, env); const varName = node.data.var || 'item'; const valuesMap = new yaml.$map({ items: _.map(input, (value, key) => ({value, key})), template: node.data.template, 'var': varName }); return _.fromPairs(_.zip(keys, this.visitNode(valuesMap, path, env))); } visit$string(node: yaml.$string, path: string, env: Env): string { const stringSource = (_.isArray(node.data) && node.data.length === 1) ? node.data[0] : node.data; return yaml.dump(this.visitNode(stringSource, path, env)); } visit$merge(node: yaml.$merge, path: string, env: Env): AnyButUndefined[] { const input: any = _.isString(node.data) ? this.visit$include(new yaml.$include(node.data), path, env) : this.visitNode(node.data, path, env); if (!_.isArray(input) && _.every(input, _.isObject)) { throw new Error(`Invalid argument to $merge at "${path}".` + " Must be array of arrays."); } return this.visitNode(_.merge.apply(_, input), path, env); } visit$mergeMap(node: yaml.$mergeMap, path: string, env: Env): AnyButUndefined { return _.merge.apply(_, this.visitNode(new yaml.$map(node.data), path, env)); } visit$concat(node: yaml.$concat, path: string, env: Env): AnyButUndefined[] { const error = new Error(`Invalid argument to $concat at "${path}".` + " Must be array of arrays.") if (!_.isArray(node.data)) { throw error; } const data = _.map(node.data, (d) => this.visitNode(d, path, env)); if (!_.every(data, _.isArray)) { throw error; } return _flatten(data); } visit$parseYaml(node: yaml.$parseYaml, path: string, env: Env): AnyButUndefined { const visited = this.visitNode(node.data, path, env); if (!_.isString(visited)) { throw new Error( `Invalid argument to !$parseYaml: expected string, got ${node.data}`); } return this.visitNode(yaml.loadString(visited, path), path, env); } visit$toJsonString(node: yaml.$toJsonString, path: string, env: Env): string { const stringSource = (_.isArray(node.data) && node.data.length === 1) ? node.data[0] : node.data; return JSON.stringify(this.visitNode(stringSource, path, env)); } visit$parseJson(node: yaml.$parseJson, path: string, env: Env): AnyButUndefined { const visited = this.visitNode(node.data, path, env); if (!_.isString(visited)) { throw new Error( `Invalid argument to !$parseJson: expected string, got ${node.data}`); } return this.visitNode(JSON.parse(visited), path, env); } visit$concatMap(node: yaml.$concatMap, path: string, env: Env): AnyButUndefined { return _flatten(this.visitNode(new yaml.$map(node.data), path, env)); } visit$groupBy(node: yaml.$groupBy, path: string, env: Env): AnyButUndefined { const varName = node.data.var || 'item'; const grouped = _.groupBy(this.visitNode(node.data.items, path, env), (item0) => { const item = this.visitNode(item0, path, env); // visit pre expansion const subEnv = mkSubEnv(env, {...env.$envValues, [varName]: item}, {path}); return this.visitNode(node.data.key, path, subEnv); }); if (node.data.template) { return _.mapValues( grouped, (items) => _.map(items, (item0) => { const item = this.visitNode(item0, path, env); // visit pre expansion const subEnv = mkSubEnv(env, {...env.$envValues, [varName]: item}, {path}); return this.visitNode(node.data.template, path, subEnv); })); } else { return grouped; } } visit$fromPairs(node: yaml.$fromPairs, path: string, env: Env): AnyButUndefined { let input: any = node.data; // TODO tighten this type if (input.length === 1 && input[0] instanceof yaml.$include) { input = this.visit$include(input[0], path, env); } if (input.length > 0 && _.has(input[0], 'Key') && _.has(input[0], 'Value')) { input = _.map(input, (i) => ({key: _.get(i, 'Key') as string, value: _.get(i, 'Value')})) } return this.visitNode(_liftKVPairs(input), path, env); } visit$split(node: yaml.$split, path: string, env: Env): string[] { if (_.isArray(node.data) && node.data.length === 2) { const [delimiter, str]: [string, string] = node.data; const visitedDelimiter = this.visitNode(delimiter, path, env); return _.dropRightWhile( this.visitNode(str, path, env).toString().split(visitedDelimiter), (s) => s === "" // Remove empty elements from trailing delimiters ); } else { throw new Error(`Invalid argument to $split at "${path}".` + " Must be array with two elements: a delimiter to split on and a string to split"); } } visit$join(node: yaml.$join, path: string, env: Env): string { const error = new Error(`Invalid argument to $join at "${path}".` + " Must be array with two elements: a delimiter to join on and a list of strings to join"); if (_.isArray(node.data) && node.data.length === 2) { const [delimiter, strs]: [string, string[]] = node.data; const visitedDelimiter = this.visitNode(delimiter, path, env); const visitedStrs = this.visitNode(strs, path, env); if (_.isString(visitedDelimiter) && _.isArray(visitedStrs)) { return visitedStrs.join(visitedDelimiter); } else { throw error; } } else { throw error; } } visit$mapListToHash(node: yaml.$mapListToHash, path: string, env: Env): AnyButUndefined { return _liftKVPairs(this.visitNode(new yaml.$map(node.data), path, env)); } shouldRewriteRef(ref: string, env: Env) { const globalRefs = env.$envValues.$globalRefs || {}; const isGlobal = _.has(globalRefs, ref); return env.$envValues.Prefix && !(isGlobal || ref.startsWith('AWS:')); } maybeRewriteRef(ref0: string, path: string, env: Env) { const ref = this.visitNode(ref0, path, env); if (this.shouldRewriteRef(ref.trim().split('.')[0], env)) { return `${env.$envValues.Prefix || ''}${ref.trim()}`; } else { return ref; } } visitRef(node: yaml.Ref, path: string, env: Env): yaml.Ref { if (node.visited) { return node; } const refInput = _.isArray(node.data) ? node.data[0] : node.data; const ref = this.visitNode(refInput, path, env); if (!_.isString(ref)) { throw new Error( `Invalid argument to !Ref: expected string, got ${ref} ${typeof ref}`); } return new yaml.Ref(this.maybeRewriteRef(ref, path, env), true /* visited */); } visitGetAtt(node: yaml.GetAtt, path: string, env: Env): yaml.GetAtt { if (node.visited) { return node; } const arg = this.visitNode(node.data, path, env); if (!(_.isString(arg) || (_.isArray(arg) && _.isString(arg[0])))) { throw new Error( `Invalid argument to !GetAtt: expected string or list, got ${node.data} type=${typeof node.data}`); } if (_.isArray(arg)) { const argsArray = _.clone(arg); argsArray[0] = this.maybeRewriteRef(argsArray[0], path, env); return new yaml.GetAtt(argsArray.length === 1 ? argsArray[0] : argsArray, true /* visited */); } else { // it should be a string return new yaml.GetAtt(this.maybeRewriteRef(arg, path, env), true /* visited */); } } visitSubStringTemplate(template0: string, path: string, env: Env) { let template = this.visitString(template0, path, env); if (template.search(CFN_SUB_RE) > -1) { template = template.replace(CFN_SUB_RE, (match, g1) => { if (this.shouldRewriteRef(g1.trim().split('.')[0], env)) { return `\${${this.maybeRewriteRef(g1, path, env)}}` } else { return match; } }); } return template; } visitSub(node: yaml.Sub, path: string, env: Env): yaml.Sub { if (_.isArray(node.data) && node.data.length === 1) { const subArg = this.visitNode(node.data[0], path, env); if (!_.isString(subArg)) { throw new Error( `Invalid argument to !Sub: expected string, got ${node.data[0]}`); } return new yaml.Sub(this.visitSubStringTemplate(subArg, path, env)); } else if (_.isArray(node.data) && node.data.length === 2) { const subArg0 = this.visitNode(node.data[0], path, env); if (!_.isString(subArg0)) { throw new Error( `Invalid argument to !Sub: expected first member of list to be string, got ${node.data[0]}: ${subArg0}`); } const templateEnv = node.data[1]; const subEnv = mkSubEnv( env, { ...env.$envValues, $globalRefs: _.fromPairs( _.map(_.keys(templateEnv), (k) => [k, true])) }, {path}); const template = this.visitSubStringTemplate(subArg0, path, subEnv); return new yaml.Sub([template, this.visitNode(templateEnv, path, env)]); } else if (_.isString(node.data)) { return new yaml.Sub(this.visitSubStringTemplate(node.data, path, env)); } else { throw new Error(`Invalid arguments to !Sub: ${node.data}`); } } visitNode(node: any, path: string, env: Env): any { const currNode = path.split('.').pop(); // Avoid serializing large `env` data when debug is not enabled if (logger.isDebugEnabled()) { logger.debug(`entering ${path}:`, {node, nodeType: typeof node, env}); } const result = (() => { if (currNode === 'Resources' && path === 'Root.Resources') { return this.visitResourceNode(node, path, env); } else if (currNode === '$envValues') { // filtered out in visitMapNode throw new Error(`Shouldn't be able to reach here: ${path}`); } else if (node instanceof yaml.Tag) { return this.visitYamlTagNode(node, path, env); } else if (_.isArray(node)) { return this.visitArray(node, path, env); } else if (_isPlainMap(node)) { return this.visitPlainMap(node, path, env); } else if (node instanceof Date) { return this.visitDate(node, path, env); } else if (typeof node === 'string') { return this.visitString(node, path, env); } else { return node; } })(); if (logger.isDebugEnabled()) { logger.debug(`exiting ${path}:`, {result, node, env});; } return result; }; visitImportedDoc(node: ExtendedCfnDoc, path: string, env: Env): AnyButUndefined { // This node comes from a yaml or json document that was imported. // We need to resolve/reify all !$ includes fully rather than // letting them leak out of the documents $imports: scope and be // resolved incorrectly if they're used in other scopes. If we // didn't do this any values defined with $defs: in a document that // is then imported into other documents would be unresolvable. // To achieve this, before calling visitNode on the node // itself we visit/resolve all entries in $envValues so the // environment we use when visiting the node doesn't have // unresolved references in it. // TODO add tests to ensure we don't have $! leakage issues in the templates also. // TODO tighten the output type const stackFrame = {location: node.$location, path: path}; // TODO improve for Root, ... const subEnv0 = mkSubEnv(env, node.$envValues || {}, {location: node.$location, path: path}); const nodeTypes = _.groupBy(_.toPairs(node.$envValues), ([_k, v]) => `${_.has(v, '$params')}`); const nonTemplates = _.fromPairs(_.get(nodeTypes, 'false')); const templates = _.fromPairs(_.get(nodeTypes, 'true')); const processedEnvValues = _.merge({}, this.visitNode(nonTemplates, path, subEnv0), templates); const subEnv = mkSubEnv(env, processedEnvValues, stackFrame); return this.visitMapNode(node, path, subEnv); } visitDate(node: Date, path: string, _env: Env): Date | string { const currNode = path.split('.').pop(); if (_.includes(['Version', 'AWSTemplateFormatVersion'], currNode)) { // common error in cfn / yaml return node.toISOString().split('T')[0]; } else { return node; } } _isImportedDoc(node: {}): node is ExtendedCfnDoc { return _isPlainMap(node) && _.has(node, '$envValues') } visitPlainMap(node: {}, path: string, env: Env): AnyButUndefined { // TODO tighten node type if (_.has(node, '$params')) { throw new Error( `Templates should be called via !$expand or as CFN resource types: ${path}\n ${yaml.dump(node)}`); } else if (this._isImportedDoc(node)) { return this.visitImportedDoc(node, path, env); } else { return this.visitMapNode(node, path, env); } } visitMapNode(node: any, path: string, env: Env): AnyButUndefined { // without $merge it would just be: //return _.mapValues(node, (v, k) => visitNode(v, appendPath(path, k), env)); const res: {[key: string]: any} = {}; for (const k in node) { if (k.indexOf('$merge') === 0) { const sub: any = this.visitNode(node[k], appendPath(path, k), env); for (const k2 in sub) { // mutate in place to acheive a deep merge _.merge(res, {[this.visitNode(k2, path, env)]: sub[k2]}); } // TODO handle ref rewriting on the Fn:Ref, Fn:GetAtt type functions //} else if ( .. Fn:Ref, etc. ) { } else if (_.includes(iidyDollarKeywordsAndInternalKeys, k)) { // we don't want to include things like $imports and $envValues in the output doc continue; } else { res[this.visitNode(k, path, env)] = this.visitNode(node[k], appendPath(path, k), env); } } return res; } visitArray(node: AnyButUndefined[], path: string, env: Env): AnyButUndefined[] { return _.map(node, (v, i) => this.visitNode(v, appendPath(path, i.toString()), env)); } visitHandlebarsString(node: string, path: string, env: Env): string { return interpolateHandlebarsString(node, env.$envValues, path); } visitString(node: string, path: string, env: Env): string { // NOTE: devs, please assert node is string before calling this let res: string; if (node.search(HANDLEBARS_RE) > -1) { res = this.visitHandlebarsString(node, path, env); } else { res = node; } if (res.match(/^(0\d+)$/)) { // this encoding works around non-octal numbers with leading 0s // not being quoted by jsyaml.dump which then causes issues with // CloudFormation mis-parsing those as octal numbers. The encoding // is removed in ../yaml.ts:dump // js-yaml devs don't want to change the behaviour so we need this // workaround https://github.com/nodeca/js-yaml/issues/394 res = `$0string ${res}`; } return res; } // Special handling for CloudFormation `Resource` entries and iidy custom Resource templates. visitResourceNode(node: any, path: string, env: Env): AnyButUndefined { if (node instanceof yaml.Tag) { const resolved = this.visitNode(node, appendPath(path, `!${node.constructor.name}`), env); if (resolved instanceof yaml.Tag) { throw new Error(`Invalid value for cloudformation Resources node: ${node}`); } return this.visitResourceNode(resolved, path, env); } else { const expanded: {[key: string]: any} = {}; for (const k in node) { if (k.indexOf('$merge') === 0) { const sub: any = this.visitNode(node[k], appendPath(path, k), env); for (const k2 in sub) { expanded[this.visitString(k2, appendPath(path, `key:${k2}`), env)] = sub[k2]; // ^ rather than visitNode as that could land us back here. } } else if (_.includes(iidyDollarKeywordsAndInternalKeys, k)) { continue; } else { expanded[this.visitString(k, appendPath(path, `key:${k}`), env)] = node[k]; // TODO? visitNode(node[k], appendPath(path, k), env); } } return this._visitResourceNode(expanded, path, env); } } // TODO tighten up the return type here: {[key: string]: any} _visitResourceNode(node: object, path: string, env: Env): AnyButUndefined { return _.fromPairs( _flatten( // as we may output > 1 resource for each template _.map(_.toPairs(node), ([name, resource]) => { if (_.has(resource, 'Condition')) { resource.Condition = this.maybeRewriteRef( resource.Condition, appendPath(path, 'Condition'), env); } if (_.has(resource, 'DependsOn')) { if (_.isArray(resource.DependsOn)) { const subPath = appendPath(path, 'DependsOn'); resource.DependsOn = _.map(resource.DependsOn, (item: any, idx: number) => { return this.maybeRewriteRef(item, appendPath(subPath, idx.toString()), env); }); } else { resource.DependsOn = this.maybeRewriteRef( resource.DependsOn, appendPath(path, 'DependsOn'), env); } } if (_.has(env.$envValues, resource.Type)) { return this.visitCustomResource(name, resource, path, env); } else if (resource.Type && (resource.Type.indexOf('AWS') === 0 || resource.Type.indexOf('Custom') === 0)) { return [[name, this.visitNode(resource, appendPath(path, name), env)]] } else { throw new Error( `Invalid resource type: ${resource.Type} at ${path}: ${JSON.stringify(resource, null, ' ')}`) } }) )); } visitCustomResource(name: string, resource: any, path: string, env: Env) { const template: ExtendedCfnDoc = env.$envValues[resource.Type] as ExtendedCfnDoc; if (_.isUndefined(template)) { throw new Error( `Invalid custom resource type: ${resource.Type} at ${path}: ${JSON.stringify(resource, null, ' ')}`) } // TODO s/NamePrefix/$namePrefix/ const prefix = _.isUndefined(resource.NamePrefix) ? name : resource.NamePrefix; const stackFrame = {location: template.$location, path: appendPath(path, name)}; const resourceDoc = _.merge( {}, template, this.visitNode(resource.Overrides, appendPath(path, `${name}.Overrides`), // This is pre template expansion so the names // used by $include, etc. must be in scope of the current // environment, not in the template's env. env)); // flag any names in the Template that should not be // prefixed by visitRef, etc. const $globalRefs: {[key: string]: boolean} = {}; _.forOwn(_.merge({}, resourceDoc.Parameters, resourceDoc.Resources, resourceDoc.Mappings, resourceDoc.Conditions), (param, key) => { if (param.$global) { $globalRefs[key] = true; } }); const $paramDefaultsEnv = mkSubEnv(env, {Prefix: prefix, ...template.$envValues}, stackFrame); const $paramDefaults = _.fromPairs( _.filter( _.map( template.$params, (v) => [v.Name, this.visitNode(v.Default, appendPath(path, `${name}.$params.${v.Name}`), $paramDefaultsEnv)]), ([_k, v]) => !_.isUndefined(v))); const providedParams = this.visitNode(resource.Properties, appendPath(path, `${name}.Properties`), env); // TODO factor this out: // TODO validate providedParams against template.$params[].type json-schema // ! 1 find any missing params with no defaults // 2 check against AllowedValues and AllowedPattern // 3 check min/max Value / Length const mergedParams = _.assign({}, $paramDefaults, providedParams); _.forEach(template.$params, (param) => validateTemplateParameter(param, mergedParams, name, env)); const subEnv = mkSubEnv( env, { Prefix: prefix, $globalRefs, ...mergedParams, ...template.$envValues }, stackFrame); // TODO consider just visitNode on the entire resourceDoc here // ... that requires finding a way to avoid double processing of .Resources const outputResources = this.visitNode(resourceDoc.Resources, appendPath(path, `${name}.Resources`), subEnv) // this will call visitNode on each section as it goes. See above ^ this._mapCustomResourceToGlobalSections(resourceDoc, path, subEnv); // TODO allow individual output resources to have distinct $namePrefixes // prefix could be a map of resname: prefix // Could also add a special char prefix individual resource names and global sections to // override this name remapping. // This ties in with supporting singleton custom resources that should be shared amongst templates return _.map(_.toPairs(outputResources), ([resname, val]: [string, any]) => { const isGlobal = _.has(val, '$global'); delete val.$global; if (isGlobal) { return [resname, val]; } else { return [`${subEnv.$envValues.Prefix}${resname}`, val]; } }); } _mapCustomResourceToGlobalSections(resourceDoc: ExtendedCfnDoc, path: string, env: Env): void { _.forEach(GlobalSectionNames, (section: GlobalSection) => { if (resourceDoc[section]) { const res = _.merge( env.GlobalAccumulator[section], // mutate in place _.fromPairs( // TOOD is this the right place to be visiting the subsections _.map(_.toPairs(this.visitNode(resourceDoc[section], appendPath(path, section), env)), ([k, v]: [string, any]) => { const isGlobal = _.has(v, '$global'); delete v.$global; if (isGlobal) { // TODO validate that there is no clash with // values already in env.GlobalAccumulator return [k, v]; } else { return [`${env.$envValues.Prefix}${k}`, v]; } })) ); return res; } }); } } class HandlebarsVariablesTrackingVisitor extends handlebars.Visitor { constructor(public variables: string[]) { super(); }; BlockStatement(block: hbs.AST.BlockStatement): void { if (_.isEmpty(block.params)) { if ('original' in block.path) { this.variables.push(block.path.original); } } else { for (const expression of block.params) { this.Expression(expression); } } } PartialBlockStatement(partial: hbs.AST.PartialBlockStatement): void { for (const expression of partial.params) { this.Expression(expression); } } MustacheStatement(mustache: hbs.AST.MustacheStatement): void { if (_.isEmpty(mustache.params)) { if ('original' in mustache.path) { this.variables.push(mustache.path.original); } } else { for (const expression of mustache.params) { this.Expression(expression); } } } // Expression is not part of handlebars.Visitor Expression(expression: hbs.AST.Expression): void { if ('params' in expression) { for (const ex of (expression as hbs.AST.SubExpression).params) { this.Expression(ex); } } else { if ('original' in expression) { this.variables.push((expression as hbs.AST.PathExpression).original); } } } } export class VariablesTrackingVisitor extends Visitor { public variables: string[] = []; visitHandlebarsString(node: string, _path: string, _env: Env): string { const ast = handlebars.parse(node); const v = new HandlebarsVariablesTrackingVisitor(this.variables); v.accept(ast); return node; } visit$include(node: yaml.$include, _path: string, _env: Env): AnyButUndefined { this.variables.push(node.data); return node.data; } visitMapNode(node: any, path: string, env: Env): AnyButUndefined { for (const key in node) { if (_.includes(['$imports', '$defs'], key)) { this.visitNode(node[key], appendPath(path, key), env); } } return super.visitMapNode(node, path, env); } }
the_stack